All checks were successful
continuous-integration/drone/push Build is passing
105 lines
2.5 KiB
Go
105 lines
2.5 KiB
Go
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)
|
|
c.Set("user-id", user_id)
|
|
|
|
/*
|
|
//user_id := c.GetInt("user-id")
|
|
var user_id int
|
|
if val, ok := c.Get("user-id"); !ok {
|
|
log.Printf("JwtAuthAdminMiddleware : user-id not in context. Keys : '%+v'\n", c.Keys)
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "error determining user id"})
|
|
return
|
|
} else {
|
|
user_id = val.(int)
|
|
}
|
|
|
|
if user_id == 0 {
|
|
errString := "could not extract user ID from context"
|
|
log.Printf("JwtAuthAdminMiddleware '%s'\n", errString)
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": errString})
|
|
c.Abort()
|
|
return
|
|
}
|
|
*/
|
|
|
|
// TODO determine user role
|
|
|
|
//ur, err := models.GetUserRoleByID(user_id)
|
|
ug, err := models.UserGetGroupByID(uint(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()
|
|
}
|
|
}
|