@@ -15,6 +15,7 @@ import (
1515 "github.com/gin-gonic/gin"
1616 "github.com/golang-jwt/jwt/v5"
1717 "go.mongodb.org/mongo-driver/bson"
18+ "go.mongodb.org/mongo-driver/mongo"
1819)
1920
2021func AuthMiddleware (configPath string ) gin.HandlerFunc {
@@ -62,10 +63,16 @@ func AuthMiddleware(configPath string) gin.HandlerFunc {
6263 return
6364 }
6465
65- email := claims ["sub" ].(string )
66+ email , ok := claims ["sub" ].(string )
67+ if ! ok || email == "" {
68+ log .Printf ("Invalid or missing 'sub' claim in JWT" )
69+ c .JSON (http .StatusUnauthorized , gin.H {"error" : "Invalid token claims" })
70+ c .Abort ()
71+ return
72+ }
6673
6774 // Fetch user from database
68- dbCtx , cancel := context .WithTimeout (context . Background (), 5 * time .Second )
75+ dbCtx , cancel := context .WithTimeout (c . Request . Context (), 5 * time .Second )
6976 defer cancel ()
7077
7178 if db .MongoDatabase == nil {
@@ -77,7 +84,12 @@ func AuthMiddleware(configPath string) gin.HandlerFunc {
7784 var user models.User
7885 err = db .MongoDatabase .Collection ("users" ).FindOne (dbCtx , bson.M {"email" : email }).Decode (& user )
7986 if err != nil {
80- c .JSON (http .StatusUnauthorized , gin.H {"error" : "User not found" })
87+ if errors .Is (err , mongo .ErrNoDocuments ) {
88+ c .JSON (http .StatusUnauthorized , gin.H {"error" : "User not found" })
89+ } else {
90+ log .Printf ("Failed to load user %s: %v" , email , err )
91+ c .JSON (http .StatusInternalServerError , gin.H {"error" : "Authentication lookup failed" })
92+ }
8193 c .Abort ()
8294 return
8395 }
0 commit comments