49 lines
761 B
Go
49 lines
761 B
Go
|
|
package middleware
|
||
|
|
|
||
|
|
import (
|
||
|
|
"github.com/gin-gonic/gin"
|
||
|
|
)
|
||
|
|
|
||
|
|
func AuthMiddleware() gin.HandlerFunc {
|
||
|
|
return func(c *gin.Context) {
|
||
|
|
token := c.GetHeader("Authorization")
|
||
|
|
if token == "" {
|
||
|
|
c.JSON(401, gin.H{
|
||
|
|
"success": false,
|
||
|
|
"message": "missing authorization token",
|
||
|
|
})
|
||
|
|
c.Abort()
|
||
|
|
return
|
||
|
|
}
|
||
|
|
|
||
|
|
// TODO: verify token and set user context
|
||
|
|
|
||
|
|
c.Next()
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
func RoleMiddleware(required []string) gin.HandlerFunc {
|
||
|
|
return func(c *gin.Context) {
|
||
|
|
role := c.GetString("user_role")
|
||
|
|
|
||
|
|
allowed := false
|
||
|
|
for _, r := range required {
|
||
|
|
if r == role {
|
||
|
|
allowed = true
|
||
|
|
break
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
if !allowed {
|
||
|
|
c.JSON(403, gin.H{
|
||
|
|
"success": false,
|
||
|
|
"message": "insufficient permissions",
|
||
|
|
})
|
||
|
|
c.Abort()
|
||
|
|
return
|
||
|
|
}
|
||
|
|
|
||
|
|
c.Next()
|
||
|
|
}
|
||
|
|
}
|