diff --git a/.env.example b/.env.example index 55f0508..ab65d39 100644 --- a/.env.example +++ b/.env.example @@ -8,8 +8,10 @@ POSTGRES_USER=huehuehue POSTGRES_PASSWORD=huehuehue POSTGRES_DB=huehuehue -DRAGONFLY_HOST=redis -DRAGONFLY_PORT=6379 -DRAGONFLY_PASSWORD=huehuehue +REDIS_HOST=redis +REDIS_PORT=6379 +REDIS_PASSWORD=huehuehue -JUDGE0_URI=https://google.com \ No newline at end of file +JUDGE0_URI=https://google.com + +JWT_KEY=secret diff --git a/database/queries/user.sql b/database/queries/user.sql index 56fb46a..7258e21 100644 --- a/database/queries/user.sql +++ b/database/queries/user.sql @@ -9,4 +9,8 @@ WHERE email = $1; -- name: GetUserByUsername :one SELECT id, email, "regNo", password, role, "roundQualified", "score", name FROM "user" -WHERE name = $1; \ No newline at end of file +WHERE name = $1; +-- name: GetUserById :one +SELECT id, email, "regNo", password, role, "roundQualified", "score", name +FROM "user" +WHERE id = $1; \ No newline at end of file diff --git a/go.mod b/go.mod index 8f85650..8e3f89d 100644 --- a/go.mod +++ b/go.mod @@ -4,7 +4,9 @@ go 1.22 require ( github.com/go-chi/chi/v5 v5.1.0 - github.com/golang-jwt/jwt/v5 v5.2.1 + github.com/go-chi/jwtauth/v5 v5.3.1 + github.com/go-chi/render v1.0.3 + github.com/golang-jwt/jwt/v4 v4.5.0 github.com/google/uuid v1.6.0 github.com/jackc/pgx/v5 v5.6.0 github.com/joho/godotenv v1.5.1 @@ -17,10 +19,7 @@ require ( github.com/cespare/xxhash/v2 v2.2.0 // indirect github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0 // indirect github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect - github.com/go-chi/jwtauth/v5 v5.3.1 // indirect github.com/goccy/go-json v0.10.2 // indirect - github.com/go-chi/render v1.0.3 // indirect - github.com/golang-jwt/jwt/v4 v4.5.0 // indirect github.com/jackc/pgpassfile v1.0.0 // indirect github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirect github.com/jackc/puddle/v2 v2.2.1 // indirect @@ -31,7 +30,6 @@ require ( github.com/lestrrat-go/jwx/v2 v2.0.20 // indirect github.com/lestrrat-go/option v1.0.1 // indirect github.com/segmentio/asm v1.2.0 // indirect - github.com/stretchr/testify v1.8.4 // indirect go.uber.org/multierr v1.10.0 // indirect golang.org/x/crypto v0.21.0 // indirect golang.org/x/sync v0.1.0 // indirect diff --git a/go.sum b/go.sum index f0fb937..409b4d9 100644 --- a/go.sum +++ b/go.sum @@ -17,12 +17,10 @@ github.com/go-chi/chi/v5 v5.1.0 h1:acVI1TYaD+hhedDJ3r54HyA6sExp3HfXq7QWEEY/xMw= github.com/go-chi/chi/v5 v5.1.0/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8= github.com/go-chi/jwtauth/v5 v5.3.1 h1:1ePWrjVctvp1tyBq5b/2ER8Th/+RbYc7x4qNsc5rh5A= github.com/go-chi/jwtauth/v5 v5.3.1/go.mod h1:6Fl2RRmWXs3tJYE1IQGX81FsPoGqDwq9c15j52R5q80= -github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU= -github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= -github.com/golang-jwt/jwt/v5 v5.2.1 h1:OuVbFODueb089Lh128TAcimifWaLhJwVflnrgM17wHk= -github.com/golang-jwt/jwt/v5 v5.2.1/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk= github.com/go-chi/render v1.0.3 h1:AsXqd2a1/INaIfUSKq3G5uA8weYx20FOsM7uSoCyyt4= github.com/go-chi/render v1.0.3/go.mod h1:/gr3hVkmYR0YlEy3LxCuVRFzEu9Ruok+gFqbIofjao0= +github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU= +github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= github.com/golang-jwt/jwt/v4 v4.5.0 h1:7cYmW1XlMY7h7ii7UhUyChSgS5wUJEnm9uZVTGqOWzg= github.com/golang-jwt/jwt/v4 v4.5.0/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= diff --git a/internal/controllers/refresh_token.go b/internal/controllers/refresh_token.go index dd49857..8884562 100644 --- a/internal/controllers/refresh_token.go +++ b/internal/controllers/refresh_token.go @@ -8,6 +8,7 @@ import ( httphelpers "github.com/CodeChefVIT/cookoff-backend/internal/helpers/http" logger "github.com/CodeChefVIT/cookoff-backend/internal/helpers/logging" "github.com/go-chi/jwtauth/v5" + "github.com/google/uuid" ) func RefreshTokenHandler(w http.ResponseWriter, r *http.Request) { @@ -25,23 +26,30 @@ func RefreshTokenHandler(w http.ResponseWriter, r *http.Request) { return } - userName, ok := claims.PrivateClaims()["username"].(string) + userId, ok := claims.PrivateClaims()["user_id"].(string) if !ok { - logger.Errof("Invalid token claims, email not found") + logger.Errof("Invalid token claims, user_id not found") httphelpers.WriteError(w, http.StatusUnauthorized, "invalid token claims") return } - user, err := database.Queries.GetUserByUsername(r.Context(), userName) + userIdUUID, err := uuid.Parse(userId) if err != nil { - logger.Errof("User not found: %s, err: %v", userName, err) + logger.Errof("Invalid user_id: %s, err: %v", userId, err) + httphelpers.WriteError(w, http.StatusUnauthorized, "invalid user_id") + return + } + + user, err := database.Queries.GetUserById(r.Context(), userIdUUID) + if err != nil { + logger.Errof("User not found: %s, err: %v", user.Name, err) httphelpers.WriteError(w, http.StatusUnauthorized, "user not found") return } accessToken, accessExp, err := helpers.GenerateJWT(&user, false) if err != nil { - logger.Errof("Failed to generate new access token for user: %s, err: %v", userName, err) + logger.Errof("Failed to generate new access token for user: %s, err: %v", user.Name, err) httphelpers.WriteError(w, http.StatusUnauthorized, "failed to generate token") return } @@ -57,7 +65,7 @@ func RefreshTokenHandler(w http.ResponseWriter, r *http.Request) { refreshToken, refreshExp, err := helpers.GenerateJWT(&user, true) if err != nil { - logger.Errof("Failed to generate new refresh token for user: %s, err: %v", userName, err) + logger.Errof("Failed to generate new refresh token for user: %s, err: %v", user.Name, err) httphelpers.WriteError(w, http.StatusUnauthorized, "failed to generate token") return } diff --git a/internal/db/user.sql.go b/internal/db/user.sql.go index 99640df..11b4be2 100644 --- a/internal/db/user.sql.go +++ b/internal/db/user.sql.go @@ -7,6 +7,8 @@ package db import ( "context" + + "github.com/google/uuid" ) const getUserByEmail = `-- name: GetUserByEmail :one @@ -31,6 +33,28 @@ func (q *Queries) GetUserByEmail(ctx context.Context, email string) (User, error return i, err } +const getUserById = `-- name: GetUserById :one +SELECT id, email, "regNo", password, role, "roundQualified", "score", name +FROM "user" +WHERE id = $1 +` + +func (q *Queries) GetUserById(ctx context.Context, id uuid.UUID) (User, error) { + row := q.db.QueryRow(ctx, getUserById, id) + var i User + err := row.Scan( + &i.ID, + &i.Email, + &i.RegNo, + &i.Password, + &i.Role, + &i.RoundQualified, + &i.Score, + &i.Name, + ) + return i, err +} + const getUserByUsername = `-- name: GetUserByUsername :one SELECT id, email, "regNo", password, role, "roundQualified", "score", name FROM "user" diff --git a/internal/helpers/auth/jwt.go b/internal/helpers/auth/jwt.go index 6d2ef9e..a02a38b 100644 --- a/internal/helpers/auth/jwt.go +++ b/internal/helpers/auth/jwt.go @@ -23,7 +23,7 @@ func GenerateJWT(user *db.User, isRefresh bool) (string, time.Time, error) { var expirationTime time.Time if !isRefresh { - expirationTime = time.Now().Add(time.Hour / 2) + expirationTime = time.Now().Add(time.Hour / 4) _, tokenString, err := TokenAuth.Encode(map[string]interface{}{ "username": user.Name, "role": user.Role, @@ -33,11 +33,11 @@ func GenerateJWT(user *db.User, isRefresh bool) (string, time.Time, error) { return tokenString, expirationTime, err } - expirationTime = time.Now().Add(time.Hour * 2) + expirationTime = time.Now().Add(time.Hour*1 + time.Minute*30) _, tokenString, err := TokenAuth.Encode(map[string]interface{}{ - "username": user.Name, - "type": "refresh", - "exp": expirationTime.Unix(), + "user_id": user.ID, + "type": "refresh", + "exp": expirationTime.Unix(), }) return tokenString, expirationTime, err }