Compare commits

...

13 Commits

Author SHA1 Message Date
d35e5813b5 feat: beta version of role management for single user 2025-07-20 17:59:54 +02:00
533e6ea6af fix: no avatar handling 2025-06-30 00:08:25 +02:00
0c24ed9382 feat: check role assignment 2025-06-30 00:08:14 +02:00
f5c61bb6a0 feat: show roles 2025-06-29 23:20:59 +02:00
eb05f830fe feat: roles & group state 2025-06-29 23:20:50 +02:00
d86a9de388 feat: assign system roles 2025-06-29 23:19:05 +02:00
d80caac81b feat: roles API + type def 2025-06-25 11:56:06 +02:00
5d49a661ed feat: add roles & groups page 2025-06-25 11:55:52 +02:00
635a2d6058 feat: roles & groups page 2025-06-25 11:55:41 +02:00
1eb96e906d feat: create system roles 2025-06-25 11:55:27 +02:00
58974d9789 feat: add scope to the role 2025-06-25 11:55:04 +02:00
329fac415f feat: get all roles endpoint 2025-06-25 11:54:45 +02:00
a83ec61fae fix: avoid null value 2025-06-25 11:54:19 +02:00
27 changed files with 1347 additions and 194 deletions

View File

@ -6,6 +6,8 @@ services:
environment:
POSTGRES_USER: guard
POSTGRES_PASSWORD: guard
volumes:
- postgres-data:/var/lib/postgresql/data
ports:
- "5432:5432"
@ -23,3 +25,5 @@ services:
volumes:
redis-data:
driver: local
postgres-data:
driver: local

View File

@ -39,17 +39,16 @@ func (h *AdminHandler) GetAllPermissions(w http.ResponseWriter, r *http.Request)
return
}
log.Println("DEBUG: Appending row dto:", RowDTO{
Scope: row.Scope,
Permissions: permissions,
})
mapped = append(mapped, RowDTO{
Scope: row.Scope,
Permissions: permissions,
})
}
if len(mapped) == 0 {
mapped = make([]RowDTO, 0)
}
encoder := json.NewEncoder(w)
w.Header().Set("Content-Type", "application/json")

156
internal/admin/roles.go Normal file
View File

@ -0,0 +1,156 @@
package admin
import (
"encoding/json"
"log"
"net/http"
"gitea.local/admin/hspguard/internal/repository"
"gitea.local/admin/hspguard/internal/web"
"github.com/go-chi/chi/v5"
"github.com/google/uuid"
)
func (h *AdminHandler) GetAllRoles(w http.ResponseWriter, r *http.Request) {
rows, err := h.repo.GetRolesGroupedWithPermissions(r.Context())
if err != nil {
log.Println("ERR: Failed to list roles from db:", err)
web.Error(w, "failed to get all roles", http.StatusInternalServerError)
return
}
type RolePermissions struct {
Permissions []repository.Permission `json:"permissions"`
repository.Role
}
type RowDTO struct {
Scope string `json:"scope"`
Roles []RolePermissions `json:"roles"`
}
if len(rows) == 0 {
rows = make([]repository.GetRolesGroupedWithPermissionsRow, 0)
}
var mapped []RowDTO
for _, row := range rows {
var mappedRow RowDTO
mappedRow.Scope = row.Scope
if err := json.Unmarshal(row.Roles, &mappedRow.Roles); err != nil {
log.Println("ERR: Failed to extract roles from byte array:", err)
web.Error(w, "failed to get roles", http.StatusInternalServerError)
return
}
mapped = append(mapped, mappedRow)
}
if len(mapped) == 0 {
mapped = make([]RowDTO, 0)
}
encoder := json.NewEncoder(w)
w.Header().Set("Content-Type", "application/json")
if err := encoder.Encode(mapped); err != nil {
web.Error(w, "failed to encode response", http.StatusInternalServerError)
}
}
func (h *AdminHandler) GetUserRoles(w http.ResponseWriter, r *http.Request) {
userId := chi.URLParam(r, "user_id")
parsed, err := uuid.Parse(userId)
if err != nil {
log.Printf("ERR: Received invalid UUID on get user roles '%s': %v\n", userId, err)
web.Error(w, "invalid user id", http.StatusBadRequest)
return
}
rows, err := h.repo.GetUserRoles(r.Context(), parsed)
if err != nil {
log.Println("ERR: Failed to list roles from db:", err)
web.Error(w, "failed to get user roles", http.StatusInternalServerError)
return
}
if len(rows) == 0 {
rows = make([]repository.Role, 0)
}
encoder := json.NewEncoder(w)
w.Header().Set("Content-Type", "application/json")
if err := encoder.Encode(rows); err != nil {
web.Error(w, "failed to encode response", http.StatusInternalServerError)
}
}
type AssignRoleRequest struct {
RoleKey string `json:"role_key"`
}
func (h *AdminHandler) AssignUserRole(w http.ResponseWriter, r *http.Request) {
userId := chi.URLParam(r, "user_id")
var req AssignRoleRequest
decoder := json.NewDecoder(r.Body)
if err := decoder.Decode(&req); err != nil {
web.Error(w, "failed to parse request body", http.StatusBadRequest)
return
}
if req.RoleKey == "" {
web.Error(w, "role key is required for assign", http.StatusBadRequest)
return
}
parsed, err := uuid.Parse(userId)
if err != nil {
log.Printf("ERR: Failed to parse provided user ID '%s': %v\n", userId, err)
web.Error(w, "invalid user id provided", http.StatusBadRequest)
return
}
user, err := h.repo.FindUserId(r.Context(), parsed)
if err != nil {
web.Error(w, "no user found under provided id", http.StatusBadRequest)
return
}
if _, err := h.repo.FindUserRole(r.Context(), repository.FindUserRoleParams{
UserID: user.ID,
Key: req.RoleKey,
}); err == nil {
log.Printf("INFO: Unassigning role '%s' for user with '%s' id", req.RoleKey, user.ID.String())
// Unassign Role
if err := h.repo.UnassignUserRole(r.Context(), repository.UnassignUserRoleParams{
UserID: user.ID,
Key: req.RoleKey,
}); err != nil {
log.Printf("ERR: Failed to unassign role '%s' from user with '%s' id: %v\n", req.RoleKey, user.ID.String(), err)
web.Error(w, "failed to unassign role to user", http.StatusInternalServerError)
return
}
} else {
log.Printf("INFO: Assigning role '%s' for user with '%s' id", req.RoleKey, user.ID.String())
if err := h.repo.AssignUserRole(r.Context(), repository.AssignUserRoleParams{
UserID: user.ID,
Key: req.RoleKey,
}); err != nil {
log.Printf("ERR: Failed to assign role '%s' to user with '%s' id: %v\n", req.RoleKey, user.ID.String(), err)
web.Error(w, "failed to assign role to user", http.StatusInternalServerError)
return
}
}
w.WriteHeader(http.StatusOK)
}

View File

@ -44,6 +44,10 @@ func (h *AdminHandler) RegisterRoutes(router chi.Router) {
r.Get("/permissions", h.GetAllPermissions)
r.Get("/permissions/{user_id}", h.GetUserPermissions)
r.Get("/roles", h.GetAllRoles)
r.Get("/roles/{user_id}", h.GetUserRoles)
r.Patch("/roles/{user_id}", h.AssignUserRole)
})
router.Get("/api-services/client/{client_id}", h.GetApiServiceCID)

View File

@ -25,22 +25,6 @@ type ApiService struct {
IconUrl *string `json:"icon_url"`
}
type Group struct {
ID uuid.UUID `json:"id"`
Name string `json:"name"`
Description *string `json:"description"`
}
type GroupPermission struct {
GroupID uuid.UUID `json:"group_id"`
PermissionID uuid.UUID `json:"permission_id"`
}
type GroupRole struct {
GroupID uuid.UUID `json:"group_id"`
RoleID uuid.UUID `json:"role_id"`
}
type Permission struct {
ID uuid.UUID `json:"id"`
Name string `json:"name"`
@ -51,6 +35,7 @@ type Permission struct {
type Role struct {
ID uuid.UUID `json:"id"`
Name string `json:"name"`
Scope string `json:"scope"`
Description *string `json:"description"`
}
@ -94,11 +79,6 @@ type User struct {
Verified bool `json:"verified"`
}
type UserGroup struct {
UserID uuid.UUID `json:"user_id"`
GroupID uuid.UUID `json:"group_id"`
}
type UserPermission struct {
UserID uuid.UUID `json:"user_id"`
PermissionID uuid.UUID `json:"permission_id"`

View File

@ -123,32 +123,13 @@ func (q *Queries) GetGroupedPermissions(ctx context.Context) ([]GetGroupedPermis
const getUserPermissions = `-- name: GetUserPermissions :many
SELECT DISTINCT p.id,p.name,p.scope,p.description
FROM permissions p
LEFT JOIN role_permissions rp_user
ON p.id = rp_user.permission_id
LEFT JOIN user_roles ur
ON rp_user.role_id = ur.role_id AND ur.user_id = $1
LEFT JOIN user_groups ug
ON ug.user_id = $1
LEFT JOIN group_roles gr
ON ug.group_id = gr.group_id
LEFT JOIN role_permissions rp_group
ON gr.role_id = rp_group.role_id AND rp_group.permission_id = p.id
LEFT JOIN user_permissions up
ON up.user_id = $1 AND up.permission_id = p.id
LEFT JOIN group_permissions gp
ON gp.group_id = ug.group_id AND gp.permission_id = p.id
WHERE ur.user_id IS NOT NULL
OR gr.group_id IS NOT NULL
OR up.user_id IS NOT NULL
OR gp.group_id IS NOT NULL
FROM user_roles ur
JOIN role_permissions rp ON ur.role_id = rp.role_id
JOIN permissions p ON rp.permission_id = p.id
WHERE ur.user_id = $1
ORDER BY p.scope
`
// From roles assigned directly to the user
// From roles assigned to user's groups
// Direct permissions to user
// Direct permissions to user's groups
func (q *Queries) GetUserPermissions(ctx context.Context, userID uuid.UUID) ([]Permission, error) {
rows, err := q.db.Query(ctx, getUserPermissions, userID)
if err != nil {

View File

@ -0,0 +1,282 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.29.0
// source: roles.sql
package repository
import (
"context"
"github.com/google/uuid"
)
const addPermissionsToRoleByKey = `-- name: AddPermissionsToRoleByKey :exec
INSERT INTO role_permissions (role_id, permission_id)
SELECT
$1,
p.id
FROM
permissions p
JOIN
unnest($2::text[]) AS key_str
ON key_str = p.scope || '_' || p.name
`
type AddPermissionsToRoleByKeyParams struct {
RoleID uuid.UUID `json:"role_id"`
PermissionKeys []string `json:"permission_keys"`
}
func (q *Queries) AddPermissionsToRoleByKey(ctx context.Context, arg AddPermissionsToRoleByKeyParams) error {
_, err := q.db.Exec(ctx, addPermissionsToRoleByKey, arg.RoleID, arg.PermissionKeys)
return err
}
const assignRolePermission = `-- name: AssignRolePermission :exec
INSERT INTO role_permissions (role_id, permission_id)
VALUES (
$1,
(
SELECT id
FROM permissions p
WHERE p.scope = split_part($2, '_', 1)
AND p.name = right($2, length($2) - position('_' IN $2))
)
)
`
type AssignRolePermissionParams struct {
RoleID uuid.UUID `json:"role_id"`
Key string `json:"key"`
}
func (q *Queries) AssignRolePermission(ctx context.Context, arg AssignRolePermissionParams) error {
_, err := q.db.Exec(ctx, assignRolePermission, arg.RoleID, arg.Key)
return err
}
const assignUserRole = `-- name: AssignUserRole :exec
INSERT INTO user_roles (user_id, role_id)
VALUES ($1, (
SELECT id FROM roles r
WHERE r.scope = split_part($2, '_', 1)
AND r.name = right($2, length($2) - position('_' IN $2))
))
`
type AssignUserRoleParams struct {
UserID uuid.UUID `json:"user_id"`
Key string `json:"key"`
}
func (q *Queries) AssignUserRole(ctx context.Context, arg AssignUserRoleParams) error {
_, err := q.db.Exec(ctx, assignUserRole, arg.UserID, arg.Key)
return err
}
const createRole = `-- name: CreateRole :one
INSERT INTO roles (name, scope, description)
VALUES ($1, $2, $3)
RETURNING id, name, scope, description
`
type CreateRoleParams struct {
Name string `json:"name"`
Scope string `json:"scope"`
Description *string `json:"description"`
}
func (q *Queries) CreateRole(ctx context.Context, arg CreateRoleParams) (Role, error) {
row := q.db.QueryRow(ctx, createRole, arg.Name, arg.Scope, arg.Description)
var i Role
err := row.Scan(
&i.ID,
&i.Name,
&i.Scope,
&i.Description,
)
return i, err
}
const findRole = `-- name: FindRole :one
SELECT id, name, scope, description
FROM roles
WHERE scope = $1 AND name = $2
`
type FindRoleParams struct {
Scope string `json:"scope"`
Name string `json:"name"`
}
func (q *Queries) FindRole(ctx context.Context, arg FindRoleParams) (Role, error) {
row := q.db.QueryRow(ctx, findRole, arg.Scope, arg.Name)
var i Role
err := row.Scan(
&i.ID,
&i.Name,
&i.Scope,
&i.Description,
)
return i, err
}
const findUserRole = `-- name: FindUserRole :one
SELECT user_id, role_id FROM user_roles
WHERE user_id = $1 AND role_id = (SELECT id FROM roles r WHERE r.scope = split_part($2, '_', 1) AND r.name = right($2, length($2) - position('_' IN $2)))
LIMIT 1
`
type FindUserRoleParams struct {
UserID uuid.UUID `json:"user_id"`
Key string `json:"key"`
}
func (q *Queries) FindUserRole(ctx context.Context, arg FindUserRoleParams) (UserRole, error) {
row := q.db.QueryRow(ctx, findUserRole, arg.UserID, arg.Key)
var i UserRole
err := row.Scan(&i.UserID, &i.RoleID)
return i, err
}
const getRoleAssignment = `-- name: GetRoleAssignment :one
SELECT role_id, permission_id FROM role_permissions
WHERE role_id = $1 AND permission_id = (SELECT id FROM permissions p WHERE p.scope = split_part($2, '_', 1) AND p.name = right($2, length($2) - position('_' IN $2)))
LIMIT 1
`
type GetRoleAssignmentParams struct {
RoleID uuid.UUID `json:"role_id"`
Key string `json:"key"`
}
func (q *Queries) GetRoleAssignment(ctx context.Context, arg GetRoleAssignmentParams) (RolePermission, error) {
row := q.db.QueryRow(ctx, getRoleAssignment, arg.RoleID, arg.Key)
var i RolePermission
err := row.Scan(&i.RoleID, &i.PermissionID)
return i, err
}
const getRolesGroupedWithPermissions = `-- name: GetRolesGroupedWithPermissions :many
SELECT
r.scope,
json_agg (
json_build_object (
'id',
r.id,
'name',
r.name,
'scope',
r.scope,
'description',
r.description,
'permissions',
COALESCE(p_list.permissions, '[]')
)
ORDER BY
r.name
) AS roles
FROM
roles r
LEFT JOIN (
SELECT
rp.role_id,
json_agg (
json_build_object (
'id',
p.id,
'name',
p.name,
'scope',
p.scope,
'description',
p.description
)
ORDER BY
p.name
) AS permissions
FROM
role_permissions rp
JOIN permissions p ON p.id = rp.permission_id
GROUP BY
rp.role_id
) p_list ON p_list.role_id = r.id
GROUP BY
r.scope
`
type GetRolesGroupedWithPermissionsRow struct {
Scope string `json:"scope"`
Roles []byte `json:"roles"`
}
func (q *Queries) GetRolesGroupedWithPermissions(ctx context.Context) ([]GetRolesGroupedWithPermissionsRow, error) {
rows, err := q.db.Query(ctx, getRolesGroupedWithPermissions)
if err != nil {
return nil, err
}
defer rows.Close()
var items []GetRolesGroupedWithPermissionsRow
for rows.Next() {
var i GetRolesGroupedWithPermissionsRow
if err := rows.Scan(&i.Scope, &i.Roles); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const getUserRoles = `-- name: GetUserRoles :many
SELECT r.id, r.name, r.scope, r.description FROM roles r
JOIN user_roles ur ON r.id = ur.role_id
WHERE ur.user_id = $1
`
func (q *Queries) GetUserRoles(ctx context.Context, userID uuid.UUID) ([]Role, error) {
rows, err := q.db.Query(ctx, getUserRoles, userID)
if err != nil {
return nil, err
}
defer rows.Close()
var items []Role
for rows.Next() {
var i Role
if err := rows.Scan(
&i.ID,
&i.Name,
&i.Scope,
&i.Description,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const unassignUserRole = `-- name: UnassignUserRole :exec
DELETE FROM user_roles
WHERE user_id = $1 AND role_id = (
SELECT id FROM roles r
WHERE r.scope = split_part($2, '_', 1)
AND r.name = right($2, length($2) - position('_' IN $2))
)
`
type UnassignUserRoleParams struct {
UserID uuid.UUID `json:"user_id"`
Key string `json:"key"`
}
func (q *Queries) UnassignUserRole(ctx context.Context, arg UnassignUserRoleParams) error {
_, err := q.db.Exec(ctx, unassignUserRole, arg.UserID, arg.Key)
return err
}

View File

@ -11,6 +11,11 @@ func String(s string) *string {
return &s
}
type RolePermissions struct {
Permissions []string `json:"permissions"`
repository.Role
}
var (
SYSTEM_SCOPE string = "system"
SYSTEM_PERMISSIONS []repository.Permission = []repository.Permission{
@ -46,6 +51,111 @@ var (
Name: "revoke_sessions",
Description: String("Allow users to revoke their active sessions"),
},
{
Name: "view_api_services",
Description: String("Allow users to view API Services (for admin)"),
},
{
Name: "add_api_services",
Description: String("Allow users to register new API Services (for admin)"),
},
{
Name: "edit_api_services",
Description: String("Allow users to edit API Services (for admin)"),
},
{
Name: "remove_api_services",
Description: String("Allow users to remove API Services (for admin)"),
},
{
Name: "view_users",
Description: String("Allow users to view other users (for admin)"),
},
{
Name: "add_users",
Description: String("Allow users to create new users (for admin)"),
},
// TODO: block, delete users
{
Name: "view_user_sessions",
Description: String("Allow users to view user sessions (for admin)"),
},
{
Name: "revoke_user_sessions",
Description: String("Allow users to revoke user sessions (for admin)"),
},
{
Name: "view_service_sessions",
Description: String("Allow users to view service sessions (for admin)"),
},
{
Name: "revoke_service_sessions",
Description: String("Allow users to revoke service sessions (for admin)"),
},
{
Name: "view_permissions",
Description: String("Allow users to view all permissions (for admin)"),
},
{
Name: "view_roles_groups",
Description: String("Allow users to view roles & groups (for admin)"),
},
}
SYSTEM_ROLES []RolePermissions = []RolePermissions{
{
Permissions: []string{
"system_log_into_guard",
"system_register",
"system_edit_profile",
"system_recover_credentials",
"system_verify_profile",
"system_access_home_services",
"system_view_sessions",
"system_revoke_sessions",
"system_view_api_services",
"system_add_api_services",
"system_edit_api_services",
"system_remove_api_services",
"system_view_users",
"system_add_users",
"system_view_user_sessions",
"system_revoke_user_sessions",
"system_view_service_sessions",
"system_revoke_service_sessions",
"system_view_permissions",
"system_view_roles_groups",
},
Role: repository.Role{
Name: "admin",
Description: String("User with full power"),
},
},
{
Permissions: []string{
"system_log_into_guard",
"system_register",
"system_edit_profile",
"system_recover_credentials",
"system_verify_profile",
"system_access_home_services",
"system_view_sessions",
"system_revoke_sessions",
},
Role: repository.Role{
Name: "member",
Description: String("User that is able to use home services"),
},
},
{
Permissions: []string{
"system_log_into_guard",
"system_register",
},
Role: repository.Role{
Name: "guest",
Description: String("New user that needs approve for everything from admin"),
},
},
}
)
@ -67,4 +177,39 @@ func EnsureSystemPermissions(ctx context.Context, repo *repository.Queries) {
}
}
}
for _, role := range SYSTEM_ROLES {
var found repository.Role
var err error
found, err = repo.FindRole(ctx, repository.FindRoleParams{
Scope: SYSTEM_SCOPE,
Name: role.Name,
})
if err != nil {
log.Printf("INFO: Create new SYSTEM role '%s'\n", role.Name)
found, err = repo.CreateRole(ctx, repository.CreateRoleParams{
Name: role.Name,
Scope: SYSTEM_SCOPE,
Description: role.Description,
})
if err != nil {
log.Fatalf("ERR: Failed to create SYSTEM role '%s': %v\n", role.Name, err)
}
}
for _, perm := range role.Permissions {
if _, exists := repo.GetRoleAssignment(ctx, repository.GetRoleAssignmentParams{
RoleID: found.ID,
Key: perm,
}); exists != nil {
if err := repo.AssignRolePermission(ctx, repository.AssignRolePermissionParams{
RoleID: found.ID,
Key: perm,
}); err != nil {
log.Fatalf("ERR: Failed to assign permission '%s' to SYSTEM role %s: %v\n", perm, found.Name, err)
}
}
}
}
}

View File

@ -1,17 +1,12 @@
-- +goose Up
-- +goose StatementBegin
-- GROUPS
CREATE TABLE groups (
id UUID PRIMARY KEY DEFAULT gen_random_uuid (),
name TEXT NOT NULL UNIQUE,
description TEXT
);
-- ROLES
CREATE TABLE roles (
id UUID PRIMARY KEY DEFAULT gen_random_uuid (),
name TEXT NOT NULL UNIQUE,
description TEXT
name TEXT NOT NULL,
scope TEXT NOT NULL,
description TEXT,
UNIQUE (name, scope)
);
-- PERMISSIONS
@ -23,20 +18,6 @@ CREATE TABLE permissions (
UNIQUE (name, scope)
);
-- USER-GROUPS (many-to-many)
CREATE TABLE user_groups (
user_id UUID REFERENCES users (id) ON DELETE CASCADE,
group_id UUID REFERENCES groups (id) ON DELETE CASCADE,
PRIMARY KEY (user_id, group_id)
);
-- GROUP-ROLES (many-to-many)
CREATE TABLE group_roles (
group_id UUID REFERENCES groups (id) ON DELETE CASCADE,
role_id UUID REFERENCES roles (id) ON DELETE CASCADE,
PRIMARY KEY (group_id, role_id)
);
-- ROLE-PERMISSIONS (many-to-many)
CREATE TABLE role_permissions (
role_id UUID REFERENCES roles (id) ON DELETE CASCADE,
@ -58,32 +39,17 @@ CREATE TABLE user_permissions (
PRIMARY KEY (user_id, permission_id)
);
-- GROUP-PERMISSIONS (direct on group, optional)
CREATE TABLE group_permissions (
group_id UUID REFERENCES groups (id) ON DELETE CASCADE,
permission_id UUID REFERENCES permissions (id) ON DELETE CASCADE,
PRIMARY KEY (group_id, permission_id)
);
-- +goose StatementEnd
-- +goose Down
-- +goose StatementBegin
DROP TABLE IF EXISTS groups;
DROP TABLE IF EXISTS roles;
DROP TABLE IF EXISTS permissions;
DROP TABLE IF EXISTS user_groups;
DROP TABLE IF EXISTS group_roles;
DROP TABLE IF EXISTS role_permissions;
DROP TABLE IF EXISTS user_permissions;
DROP TABLE IF EXISTS user_roles;
DROP TABLE IF EXISTS user_permissions;
DROP TABLE IF EXISTS role_permissions;
DROP TABLE IF EXISTS group_permissions;
DROP TABLE IF EXISTS permissions;
DROP TABLE IF EXISTS roles;
-- +goose StatementEnd

View File

@ -22,27 +22,8 @@ WHERE name = $1 AND scope = $2;
-- name: GetUserPermissions :many
SELECT DISTINCT p.id,p.name,p.scope,p.description
FROM permissions p
-- From roles assigned directly to the user
LEFT JOIN role_permissions rp_user
ON p.id = rp_user.permission_id
LEFT JOIN user_roles ur
ON rp_user.role_id = ur.role_id AND ur.user_id = $1
-- From roles assigned to user's groups
LEFT JOIN user_groups ug
ON ug.user_id = $1
LEFT JOIN group_roles gr
ON ug.group_id = gr.group_id
LEFT JOIN role_permissions rp_group
ON gr.role_id = rp_group.role_id AND rp_group.permission_id = p.id
-- Direct permissions to user
LEFT JOIN user_permissions up
ON up.user_id = $1 AND up.permission_id = p.id
-- Direct permissions to user's groups
LEFT JOIN group_permissions gp
ON gp.group_id = ug.group_id AND gp.permission_id = p.id
WHERE ur.user_id IS NOT NULL
OR gr.group_id IS NOT NULL
OR up.user_id IS NOT NULL
OR gp.group_id IS NOT NULL
FROM user_roles ur
JOIN role_permissions rp ON ur.role_id = rp.role_id
JOIN permissions p ON rp.permission_id = p.id
WHERE ur.user_id = $1
ORDER BY p.scope;

109
queries/roles.sql Normal file
View File

@ -0,0 +1,109 @@
-- name: FindRole :one
SELECT *
FROM roles
WHERE scope = $1 AND name = $2;
-- name: GetRolesGroupedWithPermissions :many
SELECT
r.scope,
json_agg (
json_build_object (
'id',
r.id,
'name',
r.name,
'scope',
r.scope,
'description',
r.description,
'permissions',
COALESCE(p_list.permissions, '[]')
)
ORDER BY
r.name
) AS roles
FROM
roles r
LEFT JOIN (
SELECT
rp.role_id,
json_agg (
json_build_object (
'id',
p.id,
'name',
p.name,
'scope',
p.scope,
'description',
p.description
)
ORDER BY
p.name
) AS permissions
FROM
role_permissions rp
JOIN permissions p ON p.id = rp.permission_id
GROUP BY
rp.role_id
) p_list ON p_list.role_id = r.id
GROUP BY
r.scope;
-- name: CreateRole :one
INSERT INTO roles (name, scope, description)
VALUES ($1, $2, $3)
RETURNING *;
-- name: GetRoleAssignment :one
SELECT * FROM role_permissions
WHERE role_id = $1 AND permission_id = (SELECT id FROM permissions p WHERE p.scope = split_part(sqlc.arg('key'), '_', 1) AND p.name = right(sqlc.arg('key'), length(sqlc.arg('key')) - position('_' IN sqlc.arg('key'))))
LIMIT 1;
-- name: AssignRolePermission :exec
INSERT INTO role_permissions (role_id, permission_id)
VALUES (
$1,
(
SELECT id
FROM permissions p
WHERE p.scope = split_part(sqlc.arg('key'), '_', 1)
AND p.name = right(sqlc.arg('key'), length(sqlc.arg('key')) - position('_' IN sqlc.arg('key')))
)
);
-- name: AddPermissionsToRoleByKey :exec
INSERT INTO role_permissions (role_id, permission_id)
SELECT
sqlc.arg(role_id),
p.id
FROM
permissions p
JOIN
unnest(sqlc.arg(permission_keys)::text[]) AS key_str
ON key_str = p.scope || '_' || p.name;
-- name: GetUserRoles :many
SELECT r.* FROM roles r
JOIN user_roles ur ON r.id = ur.role_id
WHERE ur.user_id = $1;
-- name: AssignUserRole :exec
INSERT INTO user_roles (user_id, role_id)
VALUES ($1, (
SELECT id FROM roles r
WHERE r.scope = split_part(sqlc.arg('key'), '_', 1)
AND r.name = right(sqlc.arg('key'), length(sqlc.arg('key')) - position('_' IN sqlc.arg('key')))
));
-- name: UnassignUserRole :exec
DELETE FROM user_roles
WHERE user_id = $1 AND role_id = (
SELECT id FROM roles r
WHERE r.scope = split_part(sqlc.arg('key'), '_', 1)
AND r.name = right(sqlc.arg('key'), length(sqlc.arg('key')) - position('_' IN sqlc.arg('key')))
);
-- name: FindUserRole :one
SELECT * FROM user_roles
WHERE user_id = $1 AND role_id = (SELECT id FROM roles r WHERE r.scope = split_part(sqlc.arg('key'), '_', 1) AND r.name = right(sqlc.arg('key'), length(sqlc.arg('key')) - position('_' IN sqlc.arg('key'))))
LIMIT 1;

View File

@ -28,6 +28,7 @@ import VerifyReviewPage from "./pages/Verify/Review";
import AdminUserSessionsPage from "./pages/Admin/UserSessions";
import AdminServiceSessionsPage from "./pages/Admin/ServiceSessions";
import AdminAppPermissionsPage from "./pages/Admin/AppPermissions";
import AdminRolesGroupsPage from "./pages/Admin/RolesGroups";
const router = createBrowserRouter([
{
@ -100,6 +101,10 @@ const router = createBrowserRouter([
{ index: true, element: <AdminAppPermissionsPage /> },
],
},
{
path: "roles-groups",
children: [{ index: true, element: <AdminRolesGroupsPage /> }],
},
],
},
],

View File

@ -0,0 +1,51 @@
import type { AppPermission, AppRole } from "@/types";
import { axios, handleApiError } from "..";
export type FetchGroupedRolesResponse = {
scope: string;
roles: (AppRole & {
permissions: AppPermission[];
})[];
}[];
export const getRolesApi = async (): Promise<FetchGroupedRolesResponse> => {
const response = await axios.get<FetchGroupedRolesResponse>(
"/api/v1/admin/roles",
);
if (response.status !== 200 && response.status !== 201)
throw await handleApiError(response);
return response.data;
};
export type FetchUserRolesResponse = AppRole[];
export const getUserRolesApi = async (
userId: string,
): Promise<FetchUserRolesResponse> => {
const response = await axios.get<FetchUserRolesResponse>(
`/api/v1/admin/roles/${userId}`,
);
if (response.status !== 200 && response.status !== 201)
throw await handleApiError(response);
return response.data;
};
export interface AssignUserRoleRequest {
role_key: string;
}
export const assignUserRoleApi = async (
userId: string,
params: AssignUserRoleRequest,
) => {
const response = await axios.patch(`/api/v1/admin/roles/${userId}`, params);
if (response.status !== 200 && response.status !== 201)
throw await handleApiError(response);
return response.data;
};

View File

@ -5,7 +5,7 @@ import { useMemo, type FC } from "react";
export interface AvatarProps {
iconSize?: number;
className?: string;
avatarId?: string;
avatarId?: string | null;
}
const Avatar: FC<AvatarProps> = ({ iconSize = 32, className, avatarId }) => {

View File

@ -0,0 +1,115 @@
import { Button } from "@/components/ui/button";
import { useRoles } from "@/store/admin/rolesGroups";
import { useUsers } from "@/store/admin/users";
import type { AppRole } from "@/types";
import { ChevronDown, LoaderCircle, Plus } from "lucide-react";
import React, { useCallback, useEffect, useState } from "react";
type Props = {
userRoles: AppRole[];
onToggleRole?: (scope: string, role: string, isAssigned: boolean) => void;
};
const FoldableRolesTable: React.FC<Props> = ({ userRoles, onToggleRole }) => {
const [openScopes, setOpenScopes] = useState<Record<string, boolean>>({});
const roleMap = useRoles((s) => s.roles);
const loadRoles = useRoles((s) => s.fetch);
const loadUserRoles = useUsers((state) => state.fetchUserRoles);
const user = useUsers((s) => s.current);
const togglingRole = useRoles((s) => s.toggling);
const toggleRole = useRoles((s) => s.assign);
const toggleUserRole = useCallback(
async (role: AppRole) => {
if (togglingRole === role.id) return;
if (user) {
await toggleRole(user.id, role);
loadRoles();
loadUserRoles();
}
},
[loadRoles, loadUserRoles, toggleRole, togglingRole, user],
);
const toggleScope = (scope: string) => {
setOpenScopes((prev) => ({
...prev,
[scope]: !prev[scope],
}));
};
useEffect(() => {
loadRoles();
}, [loadRoles]);
return (
<div className="w-full mx-auto shadow-md overflow-hidden">
<div className="divide-y divide-gray-200 dark:divide-gray-700">
{Object.entries(roleMap).map(([scope, roles]) => (
<div key={`${scope}`}>
<div
className="w-full text-left px-4 py-3 flex items-center justify-between cursor-pointer"
onClick={() => toggleScope(scope)}
>
<div className="flex items-center">
<span className="font-semibold text-gray-800 dark:text-gray-200">
{scope.toUpperCase()}{" "}
<span className="text-sm opacity-50 font-light">
(
{
roles.filter((r) =>
userRoles.some((ur) => ur.id === r.id),
).length
}
/{roles.length})
</span>
</span>
</div>
<span className="text-sm text-gray-500">
<ChevronDown
className={`${openScopes[scope] ? "rotate-180" : ""} transition`}
/>
</span>
</div>
<ul
className={`px-5 py-1 pb-4 transition-height ${openScopes[scope] ? "h-auto" : "h-0 py-0!"} overflow-hidden flex items-center flex-wrap gap-2`}
>
{roles.length === 0 ? (
<li className="text-gray-500 italic">No roles found</li>
) : (
roles.map((role) => (
<li
key={role.id}
className="flex items-center justify-between"
onClick={() => toggleUserRole(role)}
>
<span
className={`px-2 py-1 flex items-center gap-1 cursor-pointer select-none rounded text-xs ${
userRoles.some((ur) => ur.id === role.id)
? "bg-green-200 text-green-800 dark:bg-green-700/20 dark:text-green-300"
: "bg-red-200 text-red-800 dark:bg-red-700/20 dark:text-red-300"
} ${togglingRole === role.id ? "opacity-50" : ""}`}
>
{togglingRole === role.id && (
<LoaderCircle className="animate-spin" size={12} />
)}
{role.name.toUpperCase()}
</span>
</li>
))
)}
</ul>
</div>
))}
</div>
</div>
);
};
export default FoldableRolesTable;

View File

@ -0,0 +1,67 @@
import React from "react";
type RoleMatrixProps = {
scopes: string[];
roles: string[];
userRoles: Record<string, string[]>; // e.g. { "Project Alpha": ["admin", "viewer"] }
onToggle?: (scope: string, role: string, isAssigned: boolean) => void;
};
const RoleMatrix: React.FC<RoleMatrixProps> = ({
scopes,
roles,
userRoles,
onToggle,
}) => {
const isChecked = (scope: string, role: string) =>
userRoles[scope]?.includes(role) ?? false;
return (
<div className="overflow-x-auto">
<table className="min-w-full table-auto border border-gray-300">
<thead className="bg-gray-100">
<tr>
<th className="border border-gray-300 px-4 py-2 text-left">
Scope / Role
</th>
{roles.map((role) => (
<th
key={role}
className="border border-gray-300 px-4 py-2 text-center capitalize"
>
{role}
</th>
))}
</tr>
</thead>
<tbody>
{scopes.map((scope) => (
<tr key={scope} className="hover:bg-gray-50">
<td className="border border-gray-300 px-4 py-2 font-medium">
{scope}
</td>
{roles.map((role) => {
const checked = isChecked(scope, role);
return (
<td
key={`${scope}-${role}`}
className="border border-gray-300 px-4 py-2 text-center"
>
<input
type="checkbox"
className="form-checkbox h-4 w-4 text-indigo-600 transition duration-150"
checked={checked}
onChange={() => onToggle?.(scope, role, !checked)}
/>
</td>
);
})}
</tr>
))}
</tbody>
</table>
</div>
);
};
export default RoleMatrix;

View File

@ -1,6 +1,7 @@
import { useAuth } from "@/store/auth";
import {
Blocks,
ContactRound,
EarthLock,
Home,
KeyRound,
@ -107,6 +108,12 @@ export const useBarItems = (): [Item[], (item: Item) => boolean] => {
tab: "admin.app-permissions",
pathname: "/admin/app-permissions",
},
{
icon: <ContactRound />,
title: "Roles & Groups",
tab: "admin.roles-groups",
pathname: "/admin/roles-groups",
},
]
: []),
],

View File

@ -9,6 +9,11 @@
-ms-overflow-style: none;
scrollbar-width: none;
}
.transition-height {
transition-property: height;
transition-duration: 300ms;
transition-timing-function: ease;
}
}
html,

View File

@ -0,0 +1,91 @@
import { useEffect, type FC } from "react";
import Breadcrumbs from "@/components/ui/breadcrumbs";
import { useRoles } from "@/store/admin/rolesGroups";
import type { AppPermission } from "@/types";
interface DisplayRole {
name: string;
description: string;
permissions: AppPermission[];
}
interface IPermissionGroupProps {
scope: string;
roles?: DisplayRole[] | null | undefined;
}
const RolesGroup: FC<IPermissionGroupProps> = ({ scope, roles }) => {
return (
<div className="border dark:border-gray-800 border-gray-300 p-4 rounded mb-4">
<h2 className="dark:text-gray-300 text-gray-800 text-lg font-semibold mb-4">
{scope.toUpperCase()} <span className="opacity-45">(scope)</span>
</h2>
{roles?.map((role, index) => (
<div>
<h2 className="dark:text-gray-300 text-gray-800 text-md font-semibold">
{role.name.toUpperCase()} <span className="opacity-45">(role)</span>
</h2>
<p className="text-sm text-gray-400 dark:text-gray-500">
{role.description}
</p>
<ol className="grid gap-4 gap-y-3 grid-cols-1 my-4 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 text-gray-800 dark:text-gray-300 font-medium">
{role.permissions.map(({ name, description }) => (
<li className="before:w-2 before:h-2 before:block before:translate-y-2 before:bg-gray-400 dark:before:bg-gray-700 before:rounded-xs flex flex-row items-start gap-2">
<div className="flex flex-col gap-1">
<label>{name}</label>
<p className="text-xs text-gray-400 dark:text-gray-500">
{description}
</p>
</div>
</li>
))}
</ol>
{index + 1 < roles.length && (
<div className="h-[1px] bg-gray-700 w-full rounded my-6"></div>
)}
</div>
))}
</div>
);
};
const AdminRolesGroupsPage: FC = () => {
const roles = useRoles((s) => s.roles);
const fetch = useRoles((s) => s.fetch);
useEffect(() => {
fetch();
}, [fetch]);
console.log("roles:", roles);
return (
<div className="relative flex flex-col items-stretch w-full">
<div className="p-4">
<Breadcrumbs
className="pb-2"
items={[
{
href: "/admin",
label: "Admin",
},
{
label: "Roles & Groups",
},
]}
/>
</div>
<div className="px-7">
{Object.keys(roles).map((scope) => (
<RolesGroup scope={scope} roles={roles[scope]} />
))}
</div>
</div>
);
};
export default AdminRolesGroupsPage;

View File

@ -113,7 +113,7 @@ const AdminServiceSessionsPage: FC = () => {
{/* <SessionSource deviceInfo={session.} /> */}
{typeof session.api_service?.icon_url === "string" && (
<Avatar
avatarId={session.api_service.icon_url}
avatarId={session.api_service.icon_url ?? null}
className="w-7 h-7 min-w-7"
/>
)}
@ -129,7 +129,7 @@ const AdminServiceSessionsPage: FC = () => {
<div className="flex flex-row items-center gap-2 justify-start">
{typeof session.user?.profile_picture === "string" && (
<Avatar
avatarId={session.user.profile_picture}
avatarId={session.user.profile_picture ?? null}
className="w-7 h-7 min-w-7"
/>
)}

View File

@ -127,7 +127,7 @@ const AdminUserSessionsPage: FC = () => {
<div className="flex flex-row items-center gap-2 justify-start">
{typeof session.user?.profile_picture === "string" && (
<Avatar
avatarId={session.user.profile_picture}
avatarId={session.user.profile_picture ?? null}
className="w-7 h-7 min-w-7"
/>
)}

View File

@ -1,39 +1,65 @@
import Breadcrumbs from "@/components/ui/breadcrumbs";
import { Button } from "@/components/ui/button";
import Avatar from "@/feature/Avatar";
import FoldableRolesTable from "@/feature/FoldableRolesTable";
import RoleMatrix from "@/feature/RoleMatrix";
import { useRoles } from "@/store/admin/rolesGroups";
import { useUsers } from "@/store/admin/users";
import { useEffect, type FC } from "react";
import type { UserProfile } from "@/types";
import { Check, Mail, Phone } from "lucide-react";
import moment from "moment";
import { useEffect, type FC, type HTMLAttributes } from "react";
import { Link, useParams } from "react-router";
const InfoCard = ({
title,
children,
}: {
interface InfoCardProps extends HTMLAttributes<HTMLDivElement> {
title: string;
children: React.ReactNode;
}) => (
<div className="border dark:border-gray-800 border-gray-300 rounded mb-4">
<div className="p-4 border-b dark:border-gray-800 border-gray-300">
<h2 className="text-gray-800 dark:text-gray-200 font-semibold text-lg">
{title}
</h2>
hasSpacing?: boolean | undefined;
}
const InfoCard = ({
children,
hasSpacing = true,
title,
...props
}: InfoCardProps) => (
<div className="mb-6">
<h2 className="mb-4 text-xl">{title}</h2>
<div
{...props}
className={`border dark:border-gray-800 border-gray-300 rounded mb-4 ${props.className}`}
>
{/* <div className="p-4 border-b dark:border-gray-800 border-gray-300">
<h2 className="text-gray-800 dark:text-gray-200 font-semibold text-lg">
{title}
</h2>
</div> */}
<div className={hasSpacing ? "p-4" : ""}>{children}</div>
</div>
<div className="p-4">{children}</div>
</div>
);
const AdminViewUserPage: FC = () => {
const { userId } = useParams();
const user = useUsers((state) => state.current);
const userPermissions = useUsers((s) => s.userPermissions);
const userRoles = useUsers((s) => s.userRoles);
// const loading = useApiServices((state) => state.fetchingApiService);
const loadUser = useUsers((state) => state.fetchUser);
const loadUserRoles = useUsers((state) => state.fetchUserRoles);
useEffect(() => {
if (typeof userId === "string") loadUser(userId);
}, [loadUser, userId]);
useEffect(() => {
if (user) loadUserRoles();
}, [loadUserRoles, user]);
console.log({ userRoles });
if (!user) {
return (
<div className="p-4 flex items-center justify-center h-[60vh]">
@ -56,74 +82,138 @@ const AdminViewUserPage: FC = () => {
/>
<div className="sm:p-4 pt-4">
{/* 📋 Main Details */}
<InfoCard title="Personal Info">
<InfoCard title="Profile" hasSpacing={false}>
<div className="flex flex-col gap-4 text-sm">
<div className="flex flex-col gap-4">
<span className="font-medium text-gray-900 dark:text-white">
Avatar:
</span>
<Avatar
avatarId={user.profile_picture ?? undefined}
className="w-16 h-16"
iconSize={28}
/>
<div className="bg-black/15 shadow/20">
{/* Header */}
<div className="flex flex-row gap-4 items-center p-4">
<Avatar
avatarId={user.profile_picture ?? null}
className="w-28 h-28"
iconSize={48}
/>
<div className="flex flex-col gap-1">
<h2 className="text-lg font-medium">{user.full_name}</h2>
<div className="flex flex-row items-center gap-2">
<h3 className="text-base opacity-50 flex flex-row items-center gap-2">
<span>
<Mail size={18} />
</span>
{user.email}
</h3>
<div className="w-1 h-1 rounded-full bg-gray-600" />
<h3 className="text-base opacity-50 flex flex-row items-center gap-2">
<span>
<Phone size={18} />
</span>
{user.phone_number || "No Phone Number"}
</h3>
</div>
</div>
</div>
{/* TODO: */}
{/* Top Bars */}
{/* <div className="w-full border-b border-b-gray-600 p-4">
somethign
</div> */}
</div>
<div>
<span className="font-medium text-gray-900 dark:text-white">
Full Name:
</span>{" "}
{user.full_name}
</div>
<div>
<span className="font-medium text-gray-900 dark:text-white">
Email:
</span>{" "}
{user.email}
</div>
<div>
<span className="font-medium text-gray-900 dark:text-white">
Phone Number:
</span>{" "}
{user.phone_number || "-"}{" "}
</div>
<div>
<span className="font-medium text-gray-900 dark:text-white">
Is Admin:
</span>{" "}
<span
className={`font-semibold px-2 py-1 rounded ${
user.is_admin
? "bg-green-200 text-green-800 dark:bg-green-700/20 dark:text-green-300"
: "bg-red-200 text-red-800 dark:bg-red-700/20 dark:text-red-300"
}`}
>
{user.is_admin ? "Yes" : "No"}
</span>
</div>
<div>
<span className="font-medium text-gray-900 dark:text-white">
Created At:
</span>{" "}
{new Date(user.created_at).toLocaleString()}
</div>
<div>
<span className="font-medium text-gray-900 dark:text-white">
Last Login At:
</span>{" "}
{user.last_login
? new Date(user.last_login).toLocaleString()
: "never"}
<div className="grid grid-cols-2 gap-2 gap-y-4 p-4">
<div className="flex flex-col gap-2 items-start">
<span className="font-medium text-gray-400 dark:text-gray-500">
Verification
</span>{" "}
<div className="flex items-center gap-2">
{[
["avatar_verified", "Avatar"],
["email_verified", "Email"],
].map(([key, label]) => (
<span
key={key}
className={`px-2 py-1 rounded ${
user[key as keyof UserProfile] === true
? "bg-green-200 text-green-800 dark:bg-green-700/20 dark:text-green-300"
: "bg-red-200 text-red-800 dark:bg-red-700/20 dark:text-red-300"
}`}
>
{label}
</span>
))}
</div>
</div>
<div className="flex flex-col gap-2 items-start">
<span className="font-medium text-gray-400 dark:text-gray-500">
Roles
</span>{" "}
<span className={`font-semibold py-1 rounded`}>
{userRoles.length === 0 && <p>No Roles</p>}
{userRoles.map((role) => (
<span
key={role.id}
className="px-2 py-1 rounded bg-blue-200 text-blue-800 dark:bg-blue-700/20 dark:text-blue-300"
>
{role.name}
</span>
))}
</span>
</div>
<div className="flex flex-col gap-2 items-start">
<span className="font-medium text-gray-400 dark:text-gray-500">
Created At
</span>{" "}
<span className={`font-semibold py-1 rounded`}>
{moment(user.created_at).format("LLLL")}
</span>
</div>
<div className="flex flex-col gap-2 items-start">
<span className="font-medium text-gray-400 dark:text-gray-500">
Last Login
</span>{" "}
<span className={`font-semibold py-1 rounded`}>
{user.last_login
? moment(user.last_login).format("LLLL")
: "never"}
</span>
</div>
</div>
</div>
</InfoCard>
<InfoCard title="Roles & Permissions">
<pre>{JSON.stringify(userPermissions, null, 2)}</pre>
<InfoCard title="Roles Management" hasSpacing={false}>
<FoldableRolesTable userRoles={userRoles} />
</InfoCard>
{/* <InfoCard title="Roles" hasSpacing={false}>
{Object.entries(roles).map(([scope, roles]) => (
<div className="w-full">
<h4 className="bg-black/40 p-3 text-xs opacity-50">
{scope.toUpperCase()}
</h4>
<ul className="bg-black/20">
{roles.map((r, index) => (
<div key={r.id}>
<li
key={r.id}
className="p-2 px-4 flex flex-row items-center gap-2"
>
<span
className={`opacity-${userRoles.some((ur) => ur.id === r.id) ? "100" : "0"}`}
>
<Check size={16} />
</span>
{r.name.toUpperCase()}
</li>
{index + 1 < roles.length && (
<div className="h-[1px] bg-gray-800 w-[95%] mx-auto"></div>
)}
</div>
))}
</ul>
</div>
))}
</InfoCard> */}
{/* 🚀 Actions */}
<div className="flex flex-wrap gap-4 mt-6 justify-between items-center">
<div className="flex flex-wrap gap-4 mt-6 justify-between items-center col-span-3">
<Link to="/admin/users">
<Button variant="outlined">Back</Button>
</Link>

View File

@ -94,7 +94,7 @@ const AdminUsersPage: FC = () => {
<Avatar
iconSize={21}
className="w-8 h-8"
avatarId={user.profile_picture ?? undefined}
avatarId={user.profile_picture ?? null}
/>
<p>{user.full_name}</p>
</div>

View File

@ -21,7 +21,7 @@ const VerifyReviewPage: FC = () => {
</p>
<Avatar
avatarId={profile?.profile_picture ?? undefined}
avatarId={profile?.profile_picture ?? null}
iconSize={64}
className="w-48 h-48 min-w-48 mx-auto mt-4"
/>

View File

@ -0,0 +1,57 @@
import {
assignUserRoleApi,
getRolesApi,
type AssignUserRoleRequest,
} from "@/api/admin/roles";
import type { AppPermission, AppRole } from "@/types";
import { create } from "zustand";
export type RolesMap = Record<
string,
(AppRole & { permissions: AppPermission[] })[]
>;
export interface IRolesGroups {
roles: RolesMap;
fetching: boolean;
toggling: string | null;
fetch: () => Promise<void>;
assign: (userId: string, role: AppRole) => Promise<void>;
}
export const useRoles = create<IRolesGroups>((set) => ({
roles: {},
fetching: false,
toggling: null,
fetch: async () => {
set({ fetching: true });
try {
const response = await getRolesApi();
set({
roles: Object.fromEntries(response.map((r) => [r.scope, r.roles])),
});
} catch (err) {
console.log("ERR: Failed to fetch admin roles:", err);
} finally {
set({ fetching: false });
}
},
assign: async (userId, role) => {
set({ toggling: role.id });
try {
await assignUserRoleApi(userId, {
role_key: `${role.scope}_${role.name}`,
});
} catch (err) {
console.log("ERR: Failed to assign user role:", err);
} finally {
set({ toggling: null });
}
},
}));

View File

@ -1,11 +1,12 @@
import { getUserPermissionsApi } from "@/api/admin/permissions";
import { assignUserRoleApi, getUserRolesApi } from "@/api/admin/roles";
import {
adminGetUserApi,
adminGetUsersApi,
postUser,
type CreateUserRequest,
} from "@/api/admin/users";
import type { AppPermission, UserProfile } from "@/types";
import type { AppPermission, AppRole, UserProfile } from "@/types";
import { create } from "zustand";
export interface IUsersState {
@ -18,12 +19,20 @@ export interface IUsersState {
userPermissions: AppPermission[];
fetchingPermissions: boolean;
userRoles: AppRole[];
fetchingRoles: boolean;
creating: boolean;
createUser: (req: CreateUserRequest) => Promise<boolean>;
assigningRole: boolean;
fetchUsers: () => Promise<void>;
fetchUser: (id: string) => Promise<void>;
fetchUserPermissions: () => Promise<void>;
fetchUserRoles: () => Promise<void>;
assignUserRole: (roleKey: string) => Promise<void>;
}
export const useUsers = create<IUsersState>((set, get) => ({
@ -35,9 +44,14 @@ export const useUsers = create<IUsersState>((set, get) => ({
current: null,
fetchingCurrent: false,
userRoles: [],
fetchingRoles: false,
userPermissions: [],
fetchingPermissions: false,
assigningRole: false,
createUser: async (req: CreateUserRequest) => {
set({ creating: true });
@ -97,4 +111,41 @@ export const useUsers = create<IUsersState>((set, get) => ({
set({ fetchingPermissions: false });
}
},
fetchUserRoles: async () => {
const user = get().current;
if (!user) {
console.warn("Trying to fetch user permissions without selected user");
return;
}
set({ fetchingRoles: true });
try {
const response = await getUserRolesApi(user.id);
set({ userRoles: response ?? [] });
} catch (err) {
console.log("ERR: Failed to fetch single user for admin:", err);
} finally {
set({ fetchingRoles: false });
}
},
assignUserRole: async (roleKey: string) => {
const user = get().current;
if (!user) {
console.warn("Trying to fetch user permissions without selected user");
return;
}
set({ assigningRole: true });
try {
await assignUserRoleApi(user.id, { roleKey });
} catch (err) {
console.log("ERR: Failed to assign user role:", err);
} finally {
set({ assigningRole: false });
}
},
}));

View File

@ -85,3 +85,10 @@ export interface AppPermission {
scope: string;
description: string;
}
export interface AppRole {
id: string;
name: string;
scope: string;
description: string;
}