From 8d85b0f87590b0941dfb2d8815aa2c7b7462a89f Mon Sep 17 00:00:00 2001 From: Vidhu Kant Sharma Date: Sun, 4 Dec 2022 19:14:41 +0530 Subject: saving and checking refreshToken in DB --- auth/jwt_middleware.go | 30 +++++++++++++++++++++++++----- 1 file changed, 25 insertions(+), 5 deletions(-) (limited to 'auth/jwt_middleware.go') diff --git a/auth/jwt_middleware.go b/auth/jwt_middleware.go index 22d1fd7..8dd77b8 100644 --- a/auth/jwt_middleware.go +++ b/auth/jwt_middleware.go @@ -18,9 +18,13 @@ package auth import ( - "net/http" + "github.com/MikunoNaka/OpenBills-server/user" + "go.mongodb.org/mongo-driver/bson/primitive" + "go.mongodb.org/mongo-driver/bson" "github.com/golang-jwt/jwt/v4" "github.com/gin-gonic/gin" + "net/http" + "context" ) func Authorize() gin.HandlerFunc { @@ -51,11 +55,27 @@ func verifyRefreshToken() gin.HandlerFunc { token, err := jwt.ParseWithClaims(refreshToken, &jwt.StandardClaims{}, func(token *jwt.Token) (interface{}, error) { return []byte(refreshSecret), nil }) - if err != nil { + if err != nil { // invalid token ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"message": "refresh token expired"}) - } else { - ctx.Set("userId", token.Claims.(*jwt.StandardClaims).Issuer) - ctx.Next() + } else { // valid token + // convert id from string to ObjectID + id, _ := primitive.ObjectIDFromHex(token.Claims.(*jwt.StandardClaims).Issuer) + + // check if user exists + var u user.User + if err := db.FindOne(context.TODO(), bson.M{"_id": id}).Decode(&u); err != nil { + ctx.AbortWithStatusJSON(http.StatusNotFound, gin.H{"message": "user not found"}) + } else { + // check if this refreshToken is in DB + for _, i := range u.Sessions { + if i.Token == refreshToken { + ctx.Set("user", u) + ctx.Next() + } else { + ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"message": "refresh token expired"}) + } + } + } } } else { // invalid Authorization header -- cgit v1.2.3