Skip to content

Commit

Permalink
Merge pull request #1 from atul24112001/feature/fiber
Browse files Browse the repository at this point in the history
Feature/fiber
  • Loading branch information
atul24112001 authored Nov 7, 2024
2 parents 4a3b63b + d251db2 commit 5308e90
Show file tree
Hide file tree
Showing 29 changed files with 587 additions and 452 deletions.
3 changes: 2 additions & 1 deletion server/.gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
.env
errors.txt
errors.txt
flappy-bird-server
42 changes: 42 additions & 0 deletions server/admin/get-metric.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package admin

import (
gameManager "flappy-bird-server/game-manager"

"github.com/gofiber/fiber/v2"
)

type Game struct {
Id string `json:"id"`
Status string `json:"status"`
Users []string `json:"users"`
}

func getMetrics(c *fiber.Ctx) error {
ongoingGames := []Game{}
for gameId, game := range gameManager.GetInstance().StartedGames {
users := make([]string, 0, len(game.Users))
for k := range game.Users {
users = append(users, k)
}

ongoingGames = append(ongoingGames, Game{
Id: gameId,
Status: game.Status,
Users: users,
})
}

activeUsers := make([]string, 0, len(gameManager.GetInstance().Users))
for k := range gameManager.GetInstance().Users {
activeUsers = append(activeUsers, k)
}

return c.Status(200).JSON(map[string]interface{}{
"message": "success",
"data": map[string]interface{}{
"ongoingGames": ongoingGames,
"activeUsers": activeUsers,
},
})
}
14 changes: 14 additions & 0 deletions server/admin/index.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package admin

import (
"flappy-bird-server/middleware"

"github.com/gofiber/fiber/v2"
)

func Router(api fiber.Router) {
adminRoute := api.Group("/admin")

adminRoute.Get("/metric", middleware.CheckAccess, middleware.CheckIsAdmin, getMetrics)
adminRoute.Get("/maintenance", middleware.CheckAccess, middleware.CheckIsAdmin, updateUnderMaintenance)
}
15 changes: 15 additions & 0 deletions server/admin/update-under-maintenance.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package admin

import (
"flappy-bird-server/lib"

"github.com/gofiber/fiber/v2"
)

func updateUnderMaintenance(c *fiber.Ctx) error {
lib.UnderMaintenance = !lib.UnderMaintenance
return c.JSON(map[string]interface{}{
"message": "Maintenance status updated successfully",
"currentStatus": lib.UnderMaintenance,
})
}
14 changes: 7 additions & 7 deletions server/auth/index.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
package auth

import "net/http"
import (
"github.com/gofiber/fiber/v2"
)

func Handler(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPost {
authenticate(w, r)
return
}
http.Error(w, "method not allowed", 400)
func Router(api fiber.Router) {
authRoute := api.Group("/auth")

authRoute.Post("/", authenticate)
}
62 changes: 34 additions & 28 deletions server/auth/register.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ import (
"errors"
"flappy-bird-server/lib"
"flappy-bird-server/model"
"net/http"

"github.com/gofiber/fiber/v2"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
)
Expand All @@ -15,74 +15,80 @@ type AuthenticateRequestBody struct {
Password string `json:"password"`
}

func authenticate(w http.ResponseWriter, r *http.Request) {
func authenticate(c *fiber.Ctx) error {
var body AuthenticateRequestBody
err := lib.ReadJsonFromBody(r, w, &body)
err := c.BodyParser(&body)
if err != nil {
lib.ErrorJson(w, err)
return
return c.Status(400).JSON(map[string]interface{}{
"message": err.Error(),
})
}

if len(body.Password) < 7 {
lib.ErrorJsonWithCode(w, errors.New("password length should be more than 7"))
return
return c.Status(400).JSON(map[string]interface{}{
"message": "password length should be more than 7",
})
}
if len(body.Password) > 15 {
lib.ErrorJsonWithCode(w, errors.New("password length should be less then 16"))
return
return c.Status(400).JSON(map[string]interface{}{
"message": "password length should be less then 16",
})
}

var user model.User
var passwordHash string

getUserDetailsQuery := `SELECT id, name, email, "inrBalance", "solanaBalance", password FROM public.users WHERE email = $1`
err = lib.Pool.QueryRow(r.Context(), getUserDetailsQuery, body.Identifier).Scan(&user.Id, &user.Name, &user.Email, &user.INRBalance, &user.SolanaBalance, &passwordHash)
err = lib.Pool.QueryRow(c.Context(), getUserDetailsQuery, body.Identifier).Scan(&user.Id, &user.Name, &user.Email, &user.INRBalance, &user.SolanaBalance, &passwordHash)
if err != nil {
if err == pgx.ErrNoRows {
newUserId, err := uuid.NewRandom()
if err != nil {
lib.ErrorJsonWithCode(w, err, 500)
return
return c.Status(500).JSON(map[string]interface{}{
"message": err.Error(),
})
}
passwordHash = lib.HashString(body.Password)
err = lib.Pool.QueryRow(r.Context(), "INSERT INTO public.users (id, name, email, password) VALUES ($1, $2, $3, $4) RETURNING id, name, email", newUserId.String(), body.Identifier, body.Identifier, passwordHash).Scan(&user.Id, &user.Name, &user.Email)
err = lib.Pool.QueryRow(c.Context(), "INSERT INTO public.users (id, name, email, password) VALUES ($1, $2, $3, $4) RETURNING id, name, email", newUserId.String(), body.Identifier, body.Identifier, passwordHash).Scan(&user.Id, &user.Name, &user.Email)
if err != nil {
lib.ErrorJsonWithCode(w, err, 500)
return
return c.Status(500).JSON(map[string]interface{}{
"message": err.Error(),
})
}
token, err := lib.GenerateToken(user.Id)
if err != nil {
lib.ErrorJsonWithCode(w, err, 500)
return
return c.Status(500).JSON(map[string]interface{}{
"message": err.Error(),
})
}
lib.WriteJson(w, http.StatusOK, map[string]interface{}{
return c.Status(200).JSON(map[string]interface{}{
"message": "Registered successfully",
"token": token,
"data": user,
})
return
} else {

lib.ErrorJsonWithCode(w, err, 500)
return
return c.Status(500).JSON(map[string]interface{}{
"message": err.Error(),
})
}
}
currentPasswordHash := lib.HashString(body.Password)
token, err := lib.GenerateToken(user.Id)
if err != nil {
lib.ErrorJsonWithCode(w, err, 500)
return
return c.Status(500).JSON(map[string]interface{}{
"message": err.Error(),
})
}

if passwordHash != currentPasswordHash {
lib.ErrorJsonWithCode(w, errors.New("invalid password"), 400)
return
return c.Status(400).JSON(map[string]interface{}{
"message": errors.New("invalid password"),
})
}

lib.WriteJson(w, http.StatusOK, map[string]interface{}{
return c.Status(200).JSON(map[string]interface{}{
"message": "Login successfully",
"token": token,
"data": user,
})

}
31 changes: 12 additions & 19 deletions server/game-manager/index.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ import (
"sync"
"time"

"github.com/gofiber/contrib/websocket"
"github.com/google/uuid"
"github.com/gorilla/websocket"
)

type NewGame struct {
Expand Down Expand Up @@ -95,7 +95,10 @@ func (gameManger *GameManager) CreateGame(maxUserCount int, winnerPrice int, ent
}

func (gameManger *GameManager) JoinGame(userId string, gameTypeId string) {
targetUser, _ := gameManger.GetUser(userId)
targetUser, exist := gameManger.GetUser(userId)
if !exist {
return
}
newGameMap, newGameMapExist := gameManger.NewGame[gameTypeId]
log.Println(newGameMap.Game.Users)
if !newGameMapExist {
Expand Down Expand Up @@ -300,18 +303,9 @@ func (gameManger *GameManager) DeleteGame(gameId string) {
}

func (gameManager *GameManager) UpdateBoard(gameId string, userId string) {
// targetString := fmt.Sprintf("%s update score by 1 in %s", userId, gameId)
// hash := lib.HashString(targetString)

// if hash != token {
// targetUser, userExist := gameManager.GetUser(userId)
// if userExist {
// targetUser.SendMessage("error", map[string]interface{}{
// "message": "Invalid request",
// })
// }
// return
// }
if _, exist := gameManager.GetUser(userId); !exist {
return
}
targetGame := gameManager.GetGame(gameId)
targetGame.UpdateScore(userId)

Expand All @@ -326,7 +320,6 @@ func (gameManager *GameManager) UpdateBoard(gameId string, userId string) {

func (gameManager *GameManager) GameOver(gameId string, userId string) {
targetGame := gameManager.GetGame(gameId)
log.Println("Game over", userId)
targetGame.GameOver(userId)

var alivePlayers = 0
Expand Down Expand Up @@ -354,7 +347,7 @@ func (gameManager *GameManager) GameOver(gameId string, userId string) {
if err != nil {
log.Println(err.Error())
newLine := fmt.Sprintf("ERROR_UPDATING_GAME-gameId_%s-status_%s-userId_%s-amount-%d\n", gameId, "completed", userId, targetGame.WinnerPrice)
lib.ErrorLogger(newLine)
lib.ErrorLogger(newLine, "errors.txt")
return
}

Expand All @@ -363,7 +356,7 @@ func (gameManager *GameManager) GameOver(gameId string, userId string) {
if err != nil {
log.Println(err.Error())
newLine := fmt.Sprintf("ERROR_UPDATING_USER_BALANCE-userId_%s-amount_%d\n", winnerId, targetGame.WinnerPrice)
lib.ErrorLogger(newLine)
lib.ErrorLogger(newLine, "errors.txt")
return
}
}
Expand Down Expand Up @@ -429,7 +422,7 @@ func (gameManager *GameManager) GameOver2(gameId string, userId string) {
)
if err != nil {
newLine := fmt.Sprintf("ERROR_UPDATING_GAME-gameId_%s-status_%s\n", gameId, "completed")
lib.ErrorLogger(newLine)
lib.ErrorLogger(newLine, "errors.txt")
return
}

Expand All @@ -441,7 +434,7 @@ func (gameManager *GameManager) GameOver2(gameId string, userId string) {
).Scan(&newBalance)
if err != nil {
newLine := fmt.Sprintf("ERROR_UPDATING_USER_BALANCE-userId_%s-amount_%d\n", winnerId, targetGame.WinnerPrice)
lib.ErrorLogger(newLine)
lib.ErrorLogger(newLine, "errors.txt")
} else {
gameManager.DeleteGame(gameId)
}
Expand Down
3 changes: 2 additions & 1 deletion server/game-manager/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ import (
"encoding/json"
"log"

"github.com/gorilla/websocket"
"github.com/gofiber/contrib/websocket"
// "github.com/gorilla/websocket"
)

type User struct {
Expand Down
22 changes: 13 additions & 9 deletions server/game-type/get.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,28 +3,32 @@ package gametype
import (
"flappy-bird-server/lib"
"flappy-bird-server/model"
"net/http"

"github.com/gofiber/fiber/v2"
)

func getGameTypes(w http.ResponseWriter, r *http.Request) {
rows, err := lib.Pool.Query(r.Context(), "SELECT id, title, entry, winner, currency FROM public.gametypes")
func getGameTypes(c *fiber.Ctx) error {
gameTypes := []model.GameType{}

rows, err := lib.Pool.Query(c.Context(), "SELECT id, title, entry, winner, currency FROM public.gametypes")
if err != nil {
lib.ErrorJsonWithCode(w, err, http.StatusInternalServerError)
return
return c.Status(500).JSON(map[string]interface{}{
"message": err.Error(),
})
}
defer rows.Close()

gameTypes := []model.GameType{}
for rows.Next() {
var i model.GameType
if err := rows.Scan(&i.Id, &i.Title, &i.Entry, &i.Winner, &i.Currency); err != nil {
lib.ErrorJsonWithCode(w, err, http.StatusInternalServerError)
return
return c.Status(500).JSON(map[string]interface{}{
"message": err.Error(),
})
}
gameTypes = append(gameTypes, i)
}

lib.WriteJson(w, http.StatusOK, map[string]interface{}{
return c.Status(200).JSON(map[string]interface{}{
"data": gameTypes,
"message": "success",
})
Expand Down
19 changes: 8 additions & 11 deletions server/game-type/index.go
Original file line number Diff line number Diff line change
@@ -1,17 +1,14 @@
package gametype

import (
"net/http"
"flappy-bird-server/middleware"

"github.com/gofiber/fiber/v2"
)

func Handler(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPost {
addGameType(w, r)
return
}
if r.Method == http.MethodGet {
getGameTypes(w, r)
return
}
http.Error(w, "method not allowed", 400)
func Router(api fiber.Router) {
gameTypeRoute := api.Group("/game-type")

gameTypeRoute.Post("/", middleware.CheckAccess, addGameType)
gameTypeRoute.Get("/", getGameTypes)
}
Loading

0 comments on commit 5308e90

Please sign in to comment.