admin only route is working

This commit is contained in:
2023-03-29 19:52:46 +11:00
parent 1654ff87ed
commit cc4a890064
7 changed files with 127 additions and 10 deletions

View File

@@ -1,8 +1,10 @@
package middlewares
import (
"fmt"
"net/http"
"ccsecrets/models"
"ccsecrets/utils/token"
"github.com/gin-gonic/gin"
@@ -18,5 +20,45 @@ func JwtAuthMiddleware() gin.HandlerFunc {
}
c.Next()
}
}
func JwtAuthAdminMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
// TODO - also verify user role of admin
err := token.TokenValid(c)
if err != nil {
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 {
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
}
fmt.Printf("JwtAuthAdminMiddleware retrieved UserRole object '%v'\n", ur)
if !ur.Admin {
c.String(http.StatusUnauthorized, "User role is Non-Admin")
c.Abort()
return
}
// What does this do?
c.Next()
}
}