diff --git a/routes/user/userEndpoints.go b/routes/user/userEndpoints.go index 57e62c2..64ff1dc 100644 --- a/routes/user/userEndpoints.go +++ b/routes/user/userEndpoints.go @@ -1,7 +1,6 @@ package user import ( - //"git.rwth-aachen.de/acs/public/villas/villasweb-backend-go/common" "fmt" "github.com/dgrijalva/jwt-go" "github.com/gin-gonic/gin" @@ -17,7 +16,7 @@ const jwtSigningSecret = "This should NOT be here!!@33$8&" const weekHours = time.Hour * 24 * 7 type tokenClaims struct { - UserID string `json:"id"` + UserID uint `json:"id"` Role string `json:"role"` jwt.StandardClaims } @@ -96,7 +95,7 @@ func authenticate(c *gin.Context) { // create authentication token claims := tokenClaims{ - string(user.ID), + user.ID, user.Role, jwt.StandardClaims{ ExpiresAt: time.Now().Add(weekHours).Unix(), diff --git a/routes/user/userMiddleware.go b/routes/user/userMiddleware.go index d98fea6..beb0470 100644 --- a/routes/user/userMiddleware.go +++ b/routes/user/userMiddleware.go @@ -2,28 +2,32 @@ package user import ( "fmt" - "git.rwth-aachen.de/acs/public/villas/villasweb-backend-go/common" "github.com/dgrijalva/jwt-go" "github.com/dgrijalva/jwt-go/request" "github.com/gin-gonic/gin" "net/http" - "strconv" ) -func UserToContext(ctx *gin.Context, user_id uint) { - var user common.User - if user_id != 0 { - db := common.GetDB() - db.First(&user, user_id) +func userToContext(ctx *gin.Context, user_id uint) { + + var user User + + err := user.byID(user_id) + if err != nil { + ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{ + "succes": false, + "message": "Authentication failed (user not found)", + }) + return } + + ctx.Set("user_role", user.Role) ctx.Set("user_id", user_id) - ctx.Set("user", user) } func Authentication(unauthorized bool) gin.HandlerFunc { + return func(ctx *gin.Context) { - // Initialize user_id and model in the context - UserToContext(ctx, 0) // Authentication's access token extraction // XXX: if we have a multi-header for Authorization (e.g. in @@ -49,7 +53,7 @@ func Authentication(unauthorized bool) gin.HandlerFunc { if unauthorized { ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{ "succes": false, - "message": "Authentication failed", + "message": "Authentication failed (claims extraction)", }) } return @@ -57,8 +61,18 @@ func Authentication(unauthorized bool) gin.HandlerFunc { // If the token is ok, pass user_id to context if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid { - user_id, _ := strconv.ParseInt(claims["id"].(string), 10, 64) - UserToContext(ctx, uint(user_id)) + + user_id, ok := claims["id"].(float64) + + if !ok { + ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{ + "succes": false, + "message": "Authentication failed (claims casting)", + }) + return + } + + userToContext(ctx, uint(user_id)) } } }