Compare commits

...

7 Commits

Author SHA1 Message Date
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
13 changed files with 550 additions and 21 deletions

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")

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

@ -0,0 +1,61 @@
package admin
import (
"encoding/json"
"log"
"net/http"
"gitea.local/admin/hspguard/internal/repository"
"gitea.local/admin/hspguard/internal/web"
)
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)
}
}

View File

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

View File

@ -51,6 +51,7 @@ type Permission struct {
type Role struct {
ID uuid.UUID `json:"id"`
Name string `json:"name"`
Scope string `json:"scope"`
Description *string `json:"description"`
}

View File

@ -0,0 +1,152 @@
// 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 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 getRolesGroupedWithPermissions = `-- name: GetRolesGroupedWithPermissions :many
SELECT
r.scope,
json_agg (
json_build_object (
'id',
r.id,
'name',
r.name,
'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
}

View File

@ -2,6 +2,7 @@ package user
import (
"context"
"fmt"
"log"
"gitea.local/admin/hspguard/internal/repository"
@ -11,6 +12,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 +52,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: "family_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 +178,35 @@ func EnsureSystemPermissions(ctx context.Context, repo *repository.Queries) {
}
}
}
for _, role := range SYSTEM_ROLES {
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)
}
}
var mappedPerms []string
for _, perm := range role.Permissions {
mappedPerms = append(mappedPerms, fmt.Sprintf("%s_%s", SYSTEM_SCOPE, perm))
}
if err := repo.AddPermissionsToRoleByKey(ctx, repository.AddPermissionsToRoleByKeyParams{
RoleID: found.ID,
PermissionKeys: mappedPerms,
}); err != nil {
log.Fatalf("ERR: Failed to assign required permissions to SYSTEM role %s: %v\n", found.Name, err)
}
}
}

View File

@ -10,8 +10,10 @@ CREATE TABLE groups (
-- 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
@ -68,22 +70,22 @@ CREATE TABLE group_permissions (
-- +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_roles;
DROP TABLE IF EXISTS group_permissions;
DROP TABLE IF EXISTS user_permissions;
DROP TABLE IF EXISTS group_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

65
queries/roles.sql Normal file
View File

@ -0,0 +1,65 @@
-- 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,
'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: 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;

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,20 @@
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;
};

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

@ -0,0 +1,66 @@
import { useEffect, type FC } from "react";
import Breadcrumbs from "@/components/ui/breadcrumbs";
import { getRolesApi } from "@/api/admin/roles";
interface DisplayRole {
name: string;
description: string;
}
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">
{scope}
</h2>
{(roles?.length ?? 0) > 0 && (
<ol className="grid gap-4 gap-y-3 grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 text-gray-800 dark:text-gray-300 font-medium">
{roles!.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>
)}
</div>
);
};
const AdminRolesGroupsPage: FC = () => {
useEffect(() => {
getRolesApi().then((res) => console.log("roles:", res));
}, []);
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"></div>
</div>
);
};
export default AdminRolesGroupsPage;

View File

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