All checks were successful
continuous-integration/drone/push Build is passing
67 lines
1.4 KiB
Go
67 lines
1.4 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
|
|
}
|
|
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
|
|
}
|
|
|
|
ur, err := models.GetUserRoleByID(user_id)
|
|
|
|
if err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
|
c.Abort()
|
|
return
|
|
}
|
|
log.Printf("JwtAuthAdminMiddleware retrieved UserRole object for UserId '%d'\n", ur.UserId)
|
|
|
|
// Verify that the user has a role with the admin flag set
|
|
if !ur.Admin {
|
|
c.String(http.StatusUnauthorized, "User role is Non-Admin")
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
// What does this do?
|
|
c.Next()
|
|
}
|
|
}
|