Skip to content

Commit

Permalink
Merge pull request #24 from JothishKamal/master
Browse files Browse the repository at this point in the history
feat: get user by uuid for refresh token + update .env.example
  • Loading branch information
RustyDev24 authored Sep 14, 2024
2 parents fe6f253 + b7ef276 commit 51abfd9
Show file tree
Hide file tree
Showing 7 changed files with 59 additions and 25 deletions.
10 changes: 6 additions & 4 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -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
JUDGE0_URI=https://google.com

JWT_KEY=secret
6 changes: 5 additions & 1 deletion database/queries/user.sql
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,8 @@ WHERE email = $1;
-- name: GetUserByUsername :one
SELECT id, email, "regNo", password, role, "roundQualified", "score", name
FROM "user"
WHERE name = $1;
WHERE name = $1;
-- name: GetUserById :one
SELECT id, email, "regNo", password, role, "roundQualified", "score", name
FROM "user"
WHERE id = $1;
8 changes: 3 additions & 5 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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
Expand Down
6 changes: 2 additions & 4 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -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=
Expand Down
20 changes: 14 additions & 6 deletions internal/controllers/refresh_token.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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
}
Expand All @@ -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
}
Expand Down
24 changes: 24 additions & 0 deletions internal/db/user.sql.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 5 additions & 5 deletions internal/helpers/auth/jwt.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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
}

0 comments on commit 51abfd9

Please sign in to comment.