feat: beta version of role management for single user
This commit is contained in:
@ -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
|
||||
|
@ -7,6 +7,8 @@ import (
|
||||
|
||||
"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) {
|
||||
@ -59,3 +61,96 @@ func (h *AdminHandler) GetAllRoles(w http.ResponseWriter, r *http.Request) {
|
||||
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)
|
||||
}
|
||||
|
@ -46,6 +46,8 @@ func (h *AdminHandler) RegisterRoutes(router chi.Router) {
|
||||
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)
|
||||
|
@ -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"`
|
||||
@ -95,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"`
|
||||
|
@ -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 {
|
||||
|
@ -56,6 +56,25 @@ func (q *Queries) AssignRolePermission(ctx context.Context, arg AssignRolePermis
|
||||
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)
|
||||
@ -103,6 +122,24 @@ func (q *Queries) FindRole(ctx context.Context, arg FindRoleParams) (Role, error
|
||||
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)))
|
||||
@ -130,6 +167,8 @@ SELECT
|
||||
r.id,
|
||||
'name',
|
||||
r.name,
|
||||
'scope',
|
||||
r.scope,
|
||||
'description',
|
||||
r.description,
|
||||
'permissions',
|
||||
@ -191,3 +230,53 @@ func (q *Queries) GetRolesGroupedWithPermissions(ctx context.Context) ([]GetRole
|
||||
}
|
||||
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
|
||||
}
|
||||
|
@ -1,12 +1,5 @@
|
||||
-- +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 (),
|
||||
@ -25,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,
|
||||
@ -60,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 group_permissions;
|
||||
|
||||
DROP TABLE IF EXISTS user_permissions;
|
||||
|
||||
DROP TABLE IF EXISTS user_roles;
|
||||
|
||||
DROP TABLE IF EXISTS role_permissions;
|
||||
|
||||
DROP TABLE IF EXISTS group_roles;
|
||||
|
||||
DROP TABLE IF EXISTS user_groups;
|
||||
|
||||
DROP TABLE IF EXISTS permissions;
|
||||
|
||||
DROP TABLE IF EXISTS roles;
|
||||
|
||||
DROP TABLE IF EXISTS groups;
|
||||
|
||||
-- +goose StatementEnd
|
||||
|
@ -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;
|
||||
|
@ -12,6 +12,8 @@ SELECT
|
||||
r.id,
|
||||
'name',
|
||||
r.name,
|
||||
'scope',
|
||||
r.scope,
|
||||
'description',
|
||||
r.description,
|
||||
'permissions',
|
||||
@ -79,3 +81,29 @@ FROM
|
||||
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;
|
||||
|
@ -18,3 +18,34 @@ export const getRolesApi = async (): Promise<FetchGroupedRolesResponse> => {
|
||||
|
||||
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;
|
||||
};
|
||||
|
115
web/src/feature/FoldableRolesTable/index.tsx
Normal file
115
web/src/feature/FoldableRolesTable/index.tsx
Normal 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;
|
67
web/src/feature/RoleMatrix/index.tsx
Normal file
67
web/src/feature/RoleMatrix/index.tsx
Normal 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;
|
@ -9,6 +9,11 @@
|
||||
-ms-overflow-style: none;
|
||||
scrollbar-width: none;
|
||||
}
|
||||
.transition-height {
|
||||
transition-property: height;
|
||||
transition-duration: 300ms;
|
||||
transition-timing-function: ease;
|
||||
}
|
||||
}
|
||||
|
||||
html,
|
||||
|
@ -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">
|
||||
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>
|
||||
<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-16 h-16"
|
||||
iconSize={28}
|
||||
className="w-28 h-28"
|
||||
iconSize={48}
|
||||
/>
|
||||
</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>{" "}
|
||||
<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>
|
||||
<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:
|
||||
</div>
|
||||
{/* TODO: */}
|
||||
{/* Top Bars */}
|
||||
{/* <div className="w-full border-b border-b-gray-600 p-4">
|
||||
somethign
|
||||
</div> */}
|
||||
</div>
|
||||
<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
|
||||
className={`font-semibold px-2 py-1 rounded ${
|
||||
user.is_admin
|
||||
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"
|
||||
}`}
|
||||
>
|
||||
{user.is_admin ? "Yes" : "No"}
|
||||
{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>
|
||||
<span className="font-medium text-gray-900 dark:text-white">
|
||||
Created At:
|
||||
<div className="flex flex-col gap-2 items-start">
|
||||
<span className="font-medium text-gray-400 dark:text-gray-500">
|
||||
Created At
|
||||
</span>{" "}
|
||||
{new Date(user.created_at).toLocaleString()}
|
||||
<span className={`font-semibold py-1 rounded`}>
|
||||
{moment(user.created_at).format("LLLL")}
|
||||
</span>
|
||||
</div>
|
||||
<div>
|
||||
<span className="font-medium text-gray-900 dark:text-white">
|
||||
Last Login At:
|
||||
<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
|
||||
? new Date(user.last_login).toLocaleString()
|
||||
? 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>
|
||||
|
@ -1,4 +1,8 @@
|
||||
import { getRolesApi } from "@/api/admin/roles";
|
||||
import {
|
||||
assignUserRoleApi,
|
||||
getRolesApi,
|
||||
type AssignUserRoleRequest,
|
||||
} from "@/api/admin/roles";
|
||||
import type { AppPermission, AppRole } from "@/types";
|
||||
import { create } from "zustand";
|
||||
|
||||
@ -11,13 +15,16 @@ 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 });
|
||||
@ -33,4 +40,18 @@ export const useRoles = create<IRolesGroups>((set) => ({
|
||||
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 });
|
||||
}
|
||||
},
|
||||
}));
|
||||
|
@ -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 });
|
||||
}
|
||||
},
|
||||
}));
|
||||
|
Reference in New Issue
Block a user