package middlewares import ( "log" "net/http" "smt/models" "smt/utils/token" "github.com/gin-gonic/gin" ) func JwtAuthMiddleware() gin.HandlerFunc { return func(c *gin.Context) { err := token.TokenValid(c) if err != nil { log.Printf("JwtAuthMiddleware token is not valid : '%s'\n", err) c.String(http.StatusUnauthorized, "Unauthorized") c.Abort() return } // Token is valid, extract user_id user_id, err := token.ExtractTokenID(c) if err != nil { log.Printf("JwtAuthMiddleware user_id could not be parsed : '%s'\n", err) c.String(http.StatusUnauthorized, "Unauthorized") c.Abort() return } // Store user id in context for accessing later log.Printf("JwtAuthMiddleware storing user-id '%d'\n", user_id) c.Set("user-id", user_id) c.Next() } } func JwtAuthAdminMiddleware() gin.HandlerFunc { return func(c *gin.Context) { err := token.TokenValid(c) if err != nil { log.Printf("JwtAuthAdminMiddleware token is not valid : '%s'\n", err) c.String(http.StatusUnauthorized, "Unauthorized") c.Abort() return } // Once we know the token is valid, figure out if this user is an admin user_id, err := token.ExtractTokenID(c) if err != nil { log.Printf("JwtAuthAdminMiddleware could not extract user ID from context : '%s'\n", err) c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) c.Abort() return } log.Printf("JwtAuthAdminMiddleware determined user id as '%v'\n", user_id) // TODO determine user role //ur, err := models.GetUserRoleByID(user_id) ug, err := models.UserGetGroupByID(user_id) if err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) c.Abort() return } log.Printf("JwtAuthAdminMiddleware retrieved UserGroup object for UserId '%d'\n", ug.UserId) // Verify that the user has a role with the admin flag set if !ug.Admin { c.String(http.StatusUnauthorized, "User role is Non-Admin") c.Abort() return } // What does this do? c.Next() } }