Skip to content

Commit

Permalink
Using gorilla mux
Browse files Browse the repository at this point in the history
  • Loading branch information
atul24112001 committed Nov 12, 2024
1 parent 5cd05c1 commit afbca50
Show file tree
Hide file tree
Showing 16 changed files with 495 additions and 172 deletions.
16 changes: 4 additions & 12 deletions server/admin/index.go
Original file line number Diff line number Diff line change
@@ -1,18 +1,10 @@
package admin

import (
"flappy-bird-server/lib"
"net/http"
"github.com/gorilla/mux"
)

func Handler(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet {
GetMetrics(w, r)
return
}
if r.Method == http.MethodPost {
UpdateUnderMaintenance(w, r)
return
}
lib.ErrorJson(w, 405, "Method not allowed", "")
func Handler(r *mux.Router) {
r.HandleFunc("/metric", GetMetrics).Methods("GET")
r.HandleFunc("/maintenance", UpdateUnderMaintenance).Methods("GET")
}
12 changes: 4 additions & 8 deletions server/auth/index.go
Original file line number Diff line number Diff line change
@@ -1,14 +1,10 @@
package auth

import (
"flappy-bird-server/lib"
"net/http"
"github.com/gorilla/mux"
)

func Handler(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPost {
authenticate(w, r)
return
}
lib.ErrorJson(w, 405, "Method not allowed", "")
func Handler(r *mux.Router) {
r.HandleFunc("/register", register).Methods("POST")
r.HandleFunc("/login", login).Methods("POST")
}
63 changes: 63 additions & 0 deletions server/auth/login.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
package auth

import (
gameManager "flappy-bird-server/game-manager"
"flappy-bird-server/lib"
"flappy-bird-server/model"
"fmt"
"log"
"net/http"
"time"
)

type LoginRequestBody struct {
Identifier string `json:"identifier"`
Password string `json:"password"`
}

func login(w http.ResponseWriter, r *http.Request) {
log.Println("Login")
var body LoginRequestBody
err := lib.ReadJsonFromBody(r, w, &body)
if err != nil {
lib.ErrorJson(w, http.StatusBadRequest, err.Error(), "")
return
}
if len(body.Password) < 7 {
lib.ErrorJson(w, http.StatusBadRequest, "password length should be more than 7", "")
return
}
if len(body.Password) > 15 {
lib.ErrorJson(w, http.StatusBadRequest, "password length should be less then 16", "")
return
}

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)
if err != nil {
lib.ErrorJson(w, http.StatusBadRequest, err.Error(), "")
return
}
currentPasswordHash := lib.HashString(body.Password)
token, err := lib.GenerateToken(user.Id)
if err != nil {
lib.ErrorJson(w, http.StatusBadRequest, err.Error(), "")
return
}

if passwordHash != currentPasswordHash {
lib.ErrorJson(w, http.StatusBadRequest, "invalid password", "")
return
}

gameManager.GetInstance().RedisClient.Set(r.Context(), fmt.Sprintf("mr-balance-%s", user.Id), user.SolanaBalance, 24*time.Hour)

lib.WriteJson(w, http.StatusOK, map[string]interface{}{
"message": "Login successfully",
"token": token,
"data": user,
})
}
101 changes: 60 additions & 41 deletions server/auth/register.go
Original file line number Diff line number Diff line change
@@ -1,23 +1,24 @@
package auth

import (
gameManager "flappy-bird-server/game-manager"
"flappy-bird-server/lib"
"flappy-bird-server/model"
"fmt"
"net/http"
"time"

"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/mr-tron/base58/base58"

"crypto/ed25519"
)

type AuthenticateRequestBody struct {
Identifier string `json:"identifier"`
Password string `json:"password"`
Identifier string `json:"identifier"`
Password string `json:"password"`
Signature []uint8 `json:"signature"`
}

func authenticate(w http.ResponseWriter, r *http.Request) {
func register(w http.ResponseWriter, r *http.Request) {
var body AuthenticateRequestBody
err := lib.ReadJsonFromBody(r, w, &body)
if err != nil {
Expand All @@ -38,52 +39,70 @@ func authenticate(w http.ResponseWriter, r *http.Request) {

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)
if err != nil {
if err == pgx.ErrNoRows {
newUserId, err := uuid.NewRandom()
if err != nil {
lib.ErrorJson(w, http.StatusBadRequest, err.Error(), "")
return
}
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)
if err != nil {
lib.ErrorJson(w, http.StatusBadRequest, err.Error(), "")
return
}
token, err := lib.GenerateToken(user.Id)
if err != nil {
lib.ErrorJson(w, http.StatusBadRequest, err.Error(), "")
return
}
lib.WriteJson(w, http.StatusOK, map[string]interface{}{
"message": "Registered successfully",
"token": token,
"data": user,
})
return
} else {
lib.ErrorJson(w, http.StatusBadRequest, err.Error(), "")
return
}
if err == nil {
lib.ErrorJson(w, http.StatusBadRequest, "User already exist", "")
return
} else if err != pgx.ErrNoRows {
lib.ErrorJson(w, http.StatusBadRequest, err.Error(), "")
return
}
currentPasswordHash := lib.HashString(body.Password)
token, err := lib.GenerateToken(user.Id)

publicKey, err := base58.Decode(body.Identifier)
if err != nil {
lib.ErrorJson(w, http.StatusBadRequest, err.Error(), "")
return
}
// signature, err := hex.DecodeString(body.Signature)
// if err != nil {
// lib.ErrorJson(w, http.StatusBadRequest, err.Error(), "")
// return
// }

if passwordHash != currentPasswordHash {
lib.ErrorJson(w, http.StatusBadRequest, "invalid password", "")
isValid := ed25519.Verify(publicKey, []byte(body.Password), body.Signature)
if !isValid {
lib.ErrorJson(w, http.StatusBadRequest, "Invalid signature", "")
return
}

gameManager.GetInstance().RedisClient.Set(r.Context(), fmt.Sprintf("mr-balance-%s", user.Id), user.SolanaBalance, 24*time.Hour)

newUserId, err := uuid.NewRandom()
if err != nil {
lib.ErrorJson(w, http.StatusBadRequest, err.Error(), "")
return
}
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)
if err != nil {
lib.ErrorJson(w, http.StatusBadRequest, err.Error(), "")
return
}
token, err := lib.GenerateToken(user.Id)
if err != nil {
lib.ErrorJson(w, http.StatusBadRequest, err.Error(), "")
return
}
lib.WriteJson(w, http.StatusOK, map[string]interface{}{
"message": "Login successfully",
"message": "Registered successfully",
"token": token,
"data": user,
})

// currentPasswordHash := lib.HashString(body.Password)
// token, err := lib.GenerateToken(user.Id)
// if err != nil {
// lib.ErrorJson(w, http.StatusBadRequest, err.Error(), "")
// return
// }

// if passwordHash != currentPasswordHash {
// lib.ErrorJson(w, http.StatusBadRequest, "invalid password", "")
// return
// }

// gameManager.GetInstance().RedisClient.Set(r.Context(), fmt.Sprintf("mr-balance-%s", user.Id), user.SolanaBalance, 24*time.Hour)

// lib.WriteJson(w, http.StatusOK, map[string]interface{}{
// "message": "Login successfully",
// "token": token,
// "data": user,
// })
}
19 changes: 13 additions & 6 deletions server/game-manager/index.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,12 +46,19 @@ var once sync.Once

func GetInstance() *GameManager {
once.Do(func() {
client := redis.NewClient(&redis.Options{
Addr: os.Getenv("REDIS_ADDRESS"),
Password: os.Getenv("REDIS_PASSWORD"),
DB: 0,
})
// client := redis.NewClient(&redis.Options{
// Addr: os.Getenv("REDIS_ADDRESS"),
// Password: os.Getenv("REDIS_PASSWORD"),
// DB: 0,
// })

opt, err := redis.ParseURL(os.Getenv("REDIS_URL"))
if err != nil {
log.Fatal("Error parsing redis url: ", err.Error())
return
}

client := redis.NewClient(opt)
dbQueue := Queue{
client: client,
queueName: "mari-arena-db-queue",
Expand All @@ -78,7 +85,7 @@ func GetInstance() *GameManager {
for i := 0; i < 3; i++ {
log.Println("Checking redis connection")
if r := client.Ping(ctx); r.Err() != nil && i > 1 {
log.Fatal("Error connecting redis", r.Err().Error())
log.Fatal("Error connecting redis: ", r.Err().Error())
time.Sleep(1 * time.Second)
}
}
Expand Down
5 changes: 5 additions & 0 deletions server/game-type/index.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,11 @@ import (
"net/http"
)

// func Handler(r *mux.Router) {
// r.HandleFunc("/", getGameTypes).Methods("GET")
// r.HandleFunc("/", addGameType).Methods("POST")
// }

func Handler(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPost {
addGameType(w, r)
Expand Down
4 changes: 4 additions & 0 deletions server/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,13 @@ require (
require (
github.com/cespare/xxhash/v2 v2.2.0 // indirect
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
github.com/felixge/httpsnoop v1.0.3 // indirect
github.com/gorilla/handlers v1.5.2 // indirect
github.com/gorilla/mux v1.8.1 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
github.com/jackc/puddle/v2 v2.2.2 // indirect
github.com/mr-tron/base58 v1.2.0 // indirect
github.com/redis/go-redis/v9 v9.7.0 // indirect
github.com/robfig/cron v1.2.0 // indirect
github.com/stretchr/testify v1.9.0 // indirect
Expand Down
8 changes: 8 additions & 0 deletions server/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,16 @@ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
github.com/felixge/httpsnoop v1.0.3 h1:s/nj+GCswXYzN5v2DpNMuMQYe+0DDwt5WVCU6CWBdXk=
github.com/felixge/httpsnoop v1.0.3/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=
github.com/golang-jwt/jwt v3.2.2+incompatible h1:IfV12K8xAKAnZqdXVzCZ+TOjboZ2keLg81eXfW3O+oY=
github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gorilla/handlers v1.5.2 h1:cLTUSsNkgcwhgRqvCNmdbRWG0A3N4F+M2nWKdScwyEE=
github.com/gorilla/handlers v1.5.2/go.mod h1:dX+xVpaxdSw+q0Qek8SSsl3dfMk3jNddUkMzo0GtH0w=
github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY=
github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ=
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
Expand All @@ -21,6 +27,8 @@ github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
github.com/mr-tron/base58 v1.2.0 h1:T/HDJBh4ZCPbU39/+c3rRvE0uKBQlU27+QI8LJ4t64o=
github.com/mr-tron/base58 v1.2.0/go.mod h1:BinMc/sQntlIE1frQmRFPUoPA1Zkr8VRgBdjWI2mNwc=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/redis/go-redis/v9 v9.7.0 h1:HhLSs+B6O021gwzl+locl0zEDnyNkxMtf/Z3NNBMa9E=
Expand Down
Loading

0 comments on commit afbca50

Please sign in to comment.