79 lines
1.7 KiB
Go
79 lines
1.7 KiB
Go
package auth
|
|
|
|
import (
|
|
"server/internal/tokens"
|
|
|
|
"github.com/gofiber/fiber/v3"
|
|
)
|
|
|
|
type Role struct {
|
|
Name string `json:"name"`
|
|
Permission uint `json:"permission"`
|
|
}
|
|
|
|
var Roles = []Role{
|
|
{"superadmin", SuperAdminPermission},
|
|
{"admin", AdminPermission},
|
|
{"manager", ManagerPermission},
|
|
{"content_creator", ContentCreatorPermission},
|
|
{"user", UserPermission},
|
|
{"guest", GuestPermission},
|
|
}
|
|
|
|
// RolesData represents permissions of a user.
|
|
type RolesData string
|
|
|
|
// Typescript: enum=UserRole
|
|
const (
|
|
SuperAdminRole RolesData = "superadmin"
|
|
AdminRole RolesData = "admin"
|
|
ManagerRole RolesData = "manager"
|
|
ContentCreatorRole RolesData = "content_creator"
|
|
UserRole RolesData = "user"
|
|
GuestRole RolesData = "guest"
|
|
)
|
|
|
|
const (
|
|
SuperAdminPermission uint = 0b1111111111111111
|
|
AdminPermission uint = 0b0111111111111111
|
|
ManagerPermission uint = 0b0010111111111111
|
|
ContentCreatorPermission uint = 0b0001111111111111
|
|
UserPermission uint = 0b0000000000000011
|
|
GuestPermission uint = 0b0000000000000001
|
|
)
|
|
|
|
func PermissionToString(p uint) string {
|
|
for _, role := range Roles {
|
|
if role.Permission == p {
|
|
return role.Name
|
|
}
|
|
}
|
|
return "unknown"
|
|
}
|
|
|
|
func RoleToPermission(s string) uint {
|
|
for _, role := range Roles {
|
|
if role.Name == s {
|
|
return role.Permission
|
|
}
|
|
}
|
|
return 0
|
|
}
|
|
|
|
func IsPermitted(c fiber.Ctx, permission uint) error {
|
|
claims := c.Locals("authClaims")
|
|
if claims == nil {
|
|
return c.Status(fiber.StatusForbidden).JSON(fiber.Map{
|
|
"authenticated": false,
|
|
})
|
|
}
|
|
p := claims.(*tokens.Claims).Permission
|
|
if p&permission == 0 {
|
|
return c.Status(fiber.StatusForbidden).JSON(fiber.Map{
|
|
"authenticated": true,
|
|
"authorized": false,
|
|
})
|
|
}
|
|
return c.Next()
|
|
}
|