chenged display of devices according to user`s role. all changes are made in backend
This commit is contained in:
@@ -3,12 +3,20 @@ package handlers
|
||||
import (
|
||||
"net/http"
|
||||
"smoop-api/internal/crypto"
|
||||
"smoop-api/internal/models"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
// UserContext holds structured user information from JWT
|
||||
type UserContext struct {
|
||||
ID uint `json:"id"`
|
||||
Username string `json:"username"`
|
||||
Role models.Role `json:"role"`
|
||||
}
|
||||
|
||||
func Auth(jwtMgr *crypto.JWTManager) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
h := c.GetHeader("Authorization")
|
||||
@@ -23,6 +31,12 @@ func Auth(jwtMgr *crypto.JWTManager) gin.HandlerFunc {
|
||||
return
|
||||
}
|
||||
claims, _ := token.Claims.(jwt.MapClaims)
|
||||
userContext := UserContext{
|
||||
ID: uint(claims["sub"].(float64)),
|
||||
Username: claims["name"].(string),
|
||||
Role: models.Role(claims["role"].(string)),
|
||||
}
|
||||
c.Set("user", userContext)
|
||||
c.Set("claims", claims)
|
||||
c.Next()
|
||||
}
|
||||
@@ -30,8 +44,16 @@ func Auth(jwtMgr *crypto.JWTManager) gin.HandlerFunc {
|
||||
|
||||
func RequireRole(role string) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
claims := MustClaims(c)
|
||||
if ClaimRole(claims) != role {
|
||||
userContext, exists := c.Get("user")
|
||||
if !exists {
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
|
||||
}
|
||||
user, ok := userContext.(UserContext)
|
||||
if !ok {
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "invalid user data"})
|
||||
return
|
||||
}
|
||||
if string(user.Role) != role {
|
||||
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "forbidden"})
|
||||
return
|
||||
}
|
||||
@@ -76,3 +98,14 @@ func ClaimRole(claims map[string]interface{}) string {
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// New helper to get UserContext from context
|
||||
func GetUserContext(c *gin.Context) (UserContext, bool) {
|
||||
userContext, exists := c.Get("user")
|
||||
if !exists {
|
||||
return UserContext{}, false
|
||||
}
|
||||
|
||||
user, ok := userContext.(UserContext)
|
||||
return user, ok
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user