Add roles and users admin UI with role management API
Backend: - GET /v1/users (list company users) - GET/POST/PATCH/DELETE /v1/roles (role CRUD with permissions) - GET/POST/DELETE /v1/users/:userId/roles (role assignment) - GET /v1/me/permissions (current user's effective permissions) Frontend: - Roles list page with kebab menu (edit permissions, delete custom) - Role detail page with grouped permission checkboxes and inheritance note - New role page with auto-generated slug - Users list page showing assigned roles per user - Manage Roles dialog for adding/removing roles per user - Sidebar: Admin section with Users, Roles, Help links
This commit is contained in:
@@ -12,9 +12,13 @@ import { Route as rootRouteImport } from './routes/__root'
|
||||
import { Route as LoginRouteImport } from './routes/login'
|
||||
import { Route as AuthenticatedRouteImport } from './routes/_authenticated'
|
||||
import { Route as AuthenticatedIndexRouteImport } from './routes/_authenticated/index'
|
||||
import { Route as AuthenticatedUsersRouteImport } from './routes/_authenticated/users'
|
||||
import { Route as AuthenticatedHelpRouteImport } from './routes/_authenticated/help'
|
||||
import { Route as AuthenticatedRolesIndexRouteImport } from './routes/_authenticated/roles/index'
|
||||
import { Route as AuthenticatedMembersIndexRouteImport } from './routes/_authenticated/members/index'
|
||||
import { Route as AuthenticatedAccountsIndexRouteImport } from './routes/_authenticated/accounts/index'
|
||||
import { Route as AuthenticatedRolesNewRouteImport } from './routes/_authenticated/roles/new'
|
||||
import { Route as AuthenticatedRolesRoleIdRouteImport } from './routes/_authenticated/roles/$roleId'
|
||||
import { Route as AuthenticatedMembersMemberIdRouteImport } from './routes/_authenticated/members/$memberId'
|
||||
import { Route as AuthenticatedAccountsNewRouteImport } from './routes/_authenticated/accounts/new'
|
||||
import { Route as AuthenticatedAccountsAccountIdRouteImport } from './routes/_authenticated/accounts/$accountId'
|
||||
@@ -38,11 +42,21 @@ const AuthenticatedIndexRoute = AuthenticatedIndexRouteImport.update({
|
||||
path: '/',
|
||||
getParentRoute: () => AuthenticatedRoute,
|
||||
} as any)
|
||||
const AuthenticatedUsersRoute = AuthenticatedUsersRouteImport.update({
|
||||
id: '/users',
|
||||
path: '/users',
|
||||
getParentRoute: () => AuthenticatedRoute,
|
||||
} as any)
|
||||
const AuthenticatedHelpRoute = AuthenticatedHelpRouteImport.update({
|
||||
id: '/help',
|
||||
path: '/help',
|
||||
getParentRoute: () => AuthenticatedRoute,
|
||||
} as any)
|
||||
const AuthenticatedRolesIndexRoute = AuthenticatedRolesIndexRouteImport.update({
|
||||
id: '/roles/',
|
||||
path: '/roles/',
|
||||
getParentRoute: () => AuthenticatedRoute,
|
||||
} as any)
|
||||
const AuthenticatedMembersIndexRoute =
|
||||
AuthenticatedMembersIndexRouteImport.update({
|
||||
id: '/members/',
|
||||
@@ -55,6 +69,17 @@ const AuthenticatedAccountsIndexRoute =
|
||||
path: '/accounts/',
|
||||
getParentRoute: () => AuthenticatedRoute,
|
||||
} as any)
|
||||
const AuthenticatedRolesNewRoute = AuthenticatedRolesNewRouteImport.update({
|
||||
id: '/roles/new',
|
||||
path: '/roles/new',
|
||||
getParentRoute: () => AuthenticatedRoute,
|
||||
} as any)
|
||||
const AuthenticatedRolesRoleIdRoute =
|
||||
AuthenticatedRolesRoleIdRouteImport.update({
|
||||
id: '/roles/$roleId',
|
||||
path: '/roles/$roleId',
|
||||
getParentRoute: () => AuthenticatedRoute,
|
||||
} as any)
|
||||
const AuthenticatedMembersMemberIdRoute =
|
||||
AuthenticatedMembersMemberIdRouteImport.update({
|
||||
id: '/members/$memberId',
|
||||
@@ -108,11 +133,15 @@ export interface FileRoutesByFullPath {
|
||||
'/': typeof AuthenticatedIndexRoute
|
||||
'/login': typeof LoginRoute
|
||||
'/help': typeof AuthenticatedHelpRoute
|
||||
'/users': typeof AuthenticatedUsersRoute
|
||||
'/accounts/$accountId': typeof AuthenticatedAccountsAccountIdRouteWithChildren
|
||||
'/accounts/new': typeof AuthenticatedAccountsNewRoute
|
||||
'/members/$memberId': typeof AuthenticatedMembersMemberIdRoute
|
||||
'/roles/$roleId': typeof AuthenticatedRolesRoleIdRoute
|
||||
'/roles/new': typeof AuthenticatedRolesNewRoute
|
||||
'/accounts/': typeof AuthenticatedAccountsIndexRoute
|
||||
'/members/': typeof AuthenticatedMembersIndexRoute
|
||||
'/roles/': typeof AuthenticatedRolesIndexRoute
|
||||
'/accounts/$accountId/members': typeof AuthenticatedAccountsAccountIdMembersRoute
|
||||
'/accounts/$accountId/payment-methods': typeof AuthenticatedAccountsAccountIdPaymentMethodsRoute
|
||||
'/accounts/$accountId/processor-links': typeof AuthenticatedAccountsAccountIdProcessorLinksRoute
|
||||
@@ -122,11 +151,15 @@ export interface FileRoutesByFullPath {
|
||||
export interface FileRoutesByTo {
|
||||
'/login': typeof LoginRoute
|
||||
'/help': typeof AuthenticatedHelpRoute
|
||||
'/users': typeof AuthenticatedUsersRoute
|
||||
'/': typeof AuthenticatedIndexRoute
|
||||
'/accounts/new': typeof AuthenticatedAccountsNewRoute
|
||||
'/members/$memberId': typeof AuthenticatedMembersMemberIdRoute
|
||||
'/roles/$roleId': typeof AuthenticatedRolesRoleIdRoute
|
||||
'/roles/new': typeof AuthenticatedRolesNewRoute
|
||||
'/accounts': typeof AuthenticatedAccountsIndexRoute
|
||||
'/members': typeof AuthenticatedMembersIndexRoute
|
||||
'/roles': typeof AuthenticatedRolesIndexRoute
|
||||
'/accounts/$accountId/members': typeof AuthenticatedAccountsAccountIdMembersRoute
|
||||
'/accounts/$accountId/payment-methods': typeof AuthenticatedAccountsAccountIdPaymentMethodsRoute
|
||||
'/accounts/$accountId/processor-links': typeof AuthenticatedAccountsAccountIdProcessorLinksRoute
|
||||
@@ -138,12 +171,16 @@ export interface FileRoutesById {
|
||||
'/_authenticated': typeof AuthenticatedRouteWithChildren
|
||||
'/login': typeof LoginRoute
|
||||
'/_authenticated/help': typeof AuthenticatedHelpRoute
|
||||
'/_authenticated/users': typeof AuthenticatedUsersRoute
|
||||
'/_authenticated/': typeof AuthenticatedIndexRoute
|
||||
'/_authenticated/accounts/$accountId': typeof AuthenticatedAccountsAccountIdRouteWithChildren
|
||||
'/_authenticated/accounts/new': typeof AuthenticatedAccountsNewRoute
|
||||
'/_authenticated/members/$memberId': typeof AuthenticatedMembersMemberIdRoute
|
||||
'/_authenticated/roles/$roleId': typeof AuthenticatedRolesRoleIdRoute
|
||||
'/_authenticated/roles/new': typeof AuthenticatedRolesNewRoute
|
||||
'/_authenticated/accounts/': typeof AuthenticatedAccountsIndexRoute
|
||||
'/_authenticated/members/': typeof AuthenticatedMembersIndexRoute
|
||||
'/_authenticated/roles/': typeof AuthenticatedRolesIndexRoute
|
||||
'/_authenticated/accounts/$accountId/members': typeof AuthenticatedAccountsAccountIdMembersRoute
|
||||
'/_authenticated/accounts/$accountId/payment-methods': typeof AuthenticatedAccountsAccountIdPaymentMethodsRoute
|
||||
'/_authenticated/accounts/$accountId/processor-links': typeof AuthenticatedAccountsAccountIdProcessorLinksRoute
|
||||
@@ -156,11 +193,15 @@ export interface FileRouteTypes {
|
||||
| '/'
|
||||
| '/login'
|
||||
| '/help'
|
||||
| '/users'
|
||||
| '/accounts/$accountId'
|
||||
| '/accounts/new'
|
||||
| '/members/$memberId'
|
||||
| '/roles/$roleId'
|
||||
| '/roles/new'
|
||||
| '/accounts/'
|
||||
| '/members/'
|
||||
| '/roles/'
|
||||
| '/accounts/$accountId/members'
|
||||
| '/accounts/$accountId/payment-methods'
|
||||
| '/accounts/$accountId/processor-links'
|
||||
@@ -170,11 +211,15 @@ export interface FileRouteTypes {
|
||||
to:
|
||||
| '/login'
|
||||
| '/help'
|
||||
| '/users'
|
||||
| '/'
|
||||
| '/accounts/new'
|
||||
| '/members/$memberId'
|
||||
| '/roles/$roleId'
|
||||
| '/roles/new'
|
||||
| '/accounts'
|
||||
| '/members'
|
||||
| '/roles'
|
||||
| '/accounts/$accountId/members'
|
||||
| '/accounts/$accountId/payment-methods'
|
||||
| '/accounts/$accountId/processor-links'
|
||||
@@ -185,12 +230,16 @@ export interface FileRouteTypes {
|
||||
| '/_authenticated'
|
||||
| '/login'
|
||||
| '/_authenticated/help'
|
||||
| '/_authenticated/users'
|
||||
| '/_authenticated/'
|
||||
| '/_authenticated/accounts/$accountId'
|
||||
| '/_authenticated/accounts/new'
|
||||
| '/_authenticated/members/$memberId'
|
||||
| '/_authenticated/roles/$roleId'
|
||||
| '/_authenticated/roles/new'
|
||||
| '/_authenticated/accounts/'
|
||||
| '/_authenticated/members/'
|
||||
| '/_authenticated/roles/'
|
||||
| '/_authenticated/accounts/$accountId/members'
|
||||
| '/_authenticated/accounts/$accountId/payment-methods'
|
||||
| '/_authenticated/accounts/$accountId/processor-links'
|
||||
@@ -226,6 +275,13 @@ declare module '@tanstack/react-router' {
|
||||
preLoaderRoute: typeof AuthenticatedIndexRouteImport
|
||||
parentRoute: typeof AuthenticatedRoute
|
||||
}
|
||||
'/_authenticated/users': {
|
||||
id: '/_authenticated/users'
|
||||
path: '/users'
|
||||
fullPath: '/users'
|
||||
preLoaderRoute: typeof AuthenticatedUsersRouteImport
|
||||
parentRoute: typeof AuthenticatedRoute
|
||||
}
|
||||
'/_authenticated/help': {
|
||||
id: '/_authenticated/help'
|
||||
path: '/help'
|
||||
@@ -233,6 +289,13 @@ declare module '@tanstack/react-router' {
|
||||
preLoaderRoute: typeof AuthenticatedHelpRouteImport
|
||||
parentRoute: typeof AuthenticatedRoute
|
||||
}
|
||||
'/_authenticated/roles/': {
|
||||
id: '/_authenticated/roles/'
|
||||
path: '/roles'
|
||||
fullPath: '/roles/'
|
||||
preLoaderRoute: typeof AuthenticatedRolesIndexRouteImport
|
||||
parentRoute: typeof AuthenticatedRoute
|
||||
}
|
||||
'/_authenticated/members/': {
|
||||
id: '/_authenticated/members/'
|
||||
path: '/members'
|
||||
@@ -247,6 +310,20 @@ declare module '@tanstack/react-router' {
|
||||
preLoaderRoute: typeof AuthenticatedAccountsIndexRouteImport
|
||||
parentRoute: typeof AuthenticatedRoute
|
||||
}
|
||||
'/_authenticated/roles/new': {
|
||||
id: '/_authenticated/roles/new'
|
||||
path: '/roles/new'
|
||||
fullPath: '/roles/new'
|
||||
preLoaderRoute: typeof AuthenticatedRolesNewRouteImport
|
||||
parentRoute: typeof AuthenticatedRoute
|
||||
}
|
||||
'/_authenticated/roles/$roleId': {
|
||||
id: '/_authenticated/roles/$roleId'
|
||||
path: '/roles/$roleId'
|
||||
fullPath: '/roles/$roleId'
|
||||
preLoaderRoute: typeof AuthenticatedRolesRoleIdRouteImport
|
||||
parentRoute: typeof AuthenticatedRoute
|
||||
}
|
||||
'/_authenticated/members/$memberId': {
|
||||
id: '/_authenticated/members/$memberId'
|
||||
path: '/members/$memberId'
|
||||
@@ -335,23 +412,31 @@ const AuthenticatedAccountsAccountIdRouteWithChildren =
|
||||
|
||||
interface AuthenticatedRouteChildren {
|
||||
AuthenticatedHelpRoute: typeof AuthenticatedHelpRoute
|
||||
AuthenticatedUsersRoute: typeof AuthenticatedUsersRoute
|
||||
AuthenticatedIndexRoute: typeof AuthenticatedIndexRoute
|
||||
AuthenticatedAccountsAccountIdRoute: typeof AuthenticatedAccountsAccountIdRouteWithChildren
|
||||
AuthenticatedAccountsNewRoute: typeof AuthenticatedAccountsNewRoute
|
||||
AuthenticatedMembersMemberIdRoute: typeof AuthenticatedMembersMemberIdRoute
|
||||
AuthenticatedRolesRoleIdRoute: typeof AuthenticatedRolesRoleIdRoute
|
||||
AuthenticatedRolesNewRoute: typeof AuthenticatedRolesNewRoute
|
||||
AuthenticatedAccountsIndexRoute: typeof AuthenticatedAccountsIndexRoute
|
||||
AuthenticatedMembersIndexRoute: typeof AuthenticatedMembersIndexRoute
|
||||
AuthenticatedRolesIndexRoute: typeof AuthenticatedRolesIndexRoute
|
||||
}
|
||||
|
||||
const AuthenticatedRouteChildren: AuthenticatedRouteChildren = {
|
||||
AuthenticatedHelpRoute: AuthenticatedHelpRoute,
|
||||
AuthenticatedUsersRoute: AuthenticatedUsersRoute,
|
||||
AuthenticatedIndexRoute: AuthenticatedIndexRoute,
|
||||
AuthenticatedAccountsAccountIdRoute:
|
||||
AuthenticatedAccountsAccountIdRouteWithChildren,
|
||||
AuthenticatedAccountsNewRoute: AuthenticatedAccountsNewRoute,
|
||||
AuthenticatedMembersMemberIdRoute: AuthenticatedMembersMemberIdRoute,
|
||||
AuthenticatedRolesRoleIdRoute: AuthenticatedRolesRoleIdRoute,
|
||||
AuthenticatedRolesNewRoute: AuthenticatedRolesNewRoute,
|
||||
AuthenticatedAccountsIndexRoute: AuthenticatedAccountsIndexRoute,
|
||||
AuthenticatedMembersIndexRoute: AuthenticatedMembersIndexRoute,
|
||||
AuthenticatedRolesIndexRoute: AuthenticatedRolesIndexRoute,
|
||||
}
|
||||
|
||||
const AuthenticatedRouteWithChildren = AuthenticatedRoute._addFileChildren(
|
||||
56
packages/admin/src/api/rbac.ts
Normal file
56
packages/admin/src/api/rbac.ts
Normal file
@@ -0,0 +1,56 @@
|
||||
import { queryOptions } from '@tanstack/react-query'
|
||||
import { api } from '@/lib/api-client'
|
||||
import type { Permission, Role } from '@/types/rbac'
|
||||
|
||||
export const rbacKeys = {
|
||||
permissions: ['permissions'] as const,
|
||||
roles: ['roles'] as const,
|
||||
role: (id: string) => ['roles', id] as const,
|
||||
userRoles: (userId: string) => ['users', userId, 'roles'] as const,
|
||||
myPermissions: ['me', 'permissions'] as const,
|
||||
}
|
||||
|
||||
export function permissionListOptions() {
|
||||
return queryOptions({
|
||||
queryKey: rbacKeys.permissions,
|
||||
queryFn: () => api.get<{ data: Permission[] }>('/v1/permissions'),
|
||||
})
|
||||
}
|
||||
|
||||
export function roleListOptions() {
|
||||
return queryOptions({
|
||||
queryKey: rbacKeys.roles,
|
||||
queryFn: () => api.get<{ data: Role[] }>('/v1/roles'),
|
||||
})
|
||||
}
|
||||
|
||||
export function roleDetailOptions(id: string) {
|
||||
return queryOptions({
|
||||
queryKey: rbacKeys.role(id),
|
||||
queryFn: () => api.get<Role & { permissions: string[] }>(`/v1/roles/${id}`),
|
||||
})
|
||||
}
|
||||
|
||||
export function myPermissionsOptions() {
|
||||
return queryOptions({
|
||||
queryKey: rbacKeys.myPermissions,
|
||||
queryFn: () => api.get<{ permissions: string[]; roles: { id: string; name: string; slug: string }[] }>('/v1/me/permissions'),
|
||||
})
|
||||
}
|
||||
|
||||
export const rbacMutations = {
|
||||
createRole: (data: Record<string, unknown>) =>
|
||||
api.post<Role>('/v1/roles', data),
|
||||
|
||||
updateRole: (id: string, data: Record<string, unknown>) =>
|
||||
api.patch<Role>(`/v1/roles/${id}`, data),
|
||||
|
||||
deleteRole: (id: string) =>
|
||||
api.del<Role>(`/v1/roles/${id}`),
|
||||
|
||||
assignRole: (userId: string, roleId: string) =>
|
||||
api.post(`/v1/users/${userId}/roles`, { roleId }),
|
||||
|
||||
removeRole: (userId: string, roleId: string) =>
|
||||
api.del(`/v1/users/${userId}/roles/${roleId}`),
|
||||
}
|
||||
22
packages/admin/src/api/users.ts
Normal file
22
packages/admin/src/api/users.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
import { queryOptions } from '@tanstack/react-query'
|
||||
import { api } from '@/lib/api-client'
|
||||
|
||||
export interface UserRecord {
|
||||
id: string
|
||||
email: string
|
||||
firstName: string
|
||||
lastName: string
|
||||
role: string
|
||||
createdAt: string
|
||||
}
|
||||
|
||||
export const userKeys = {
|
||||
roles: (userId: string) => ['users', userId, 'roles'] as const,
|
||||
}
|
||||
|
||||
export function userRolesOptions(userId: string) {
|
||||
return queryOptions({
|
||||
queryKey: userKeys.roles(userId),
|
||||
queryFn: () => api.get<{ data: { id: string; name: string; slug: string; isSystem: boolean }[] }>(`/v1/users/${userId}/roles`),
|
||||
})
|
||||
}
|
||||
@@ -12,9 +12,13 @@ import { Route as rootRouteImport } from './routes/__root'
|
||||
import { Route as LoginRouteImport } from './routes/login'
|
||||
import { Route as AuthenticatedRouteImport } from './routes/_authenticated'
|
||||
import { Route as AuthenticatedIndexRouteImport } from './routes/_authenticated/index'
|
||||
import { Route as AuthenticatedUsersRouteImport } from './routes/_authenticated/users'
|
||||
import { Route as AuthenticatedHelpRouteImport } from './routes/_authenticated/help'
|
||||
import { Route as AuthenticatedRolesIndexRouteImport } from './routes/_authenticated/roles/index'
|
||||
import { Route as AuthenticatedMembersIndexRouteImport } from './routes/_authenticated/members/index'
|
||||
import { Route as AuthenticatedAccountsIndexRouteImport } from './routes/_authenticated/accounts/index'
|
||||
import { Route as AuthenticatedRolesNewRouteImport } from './routes/_authenticated/roles/new'
|
||||
import { Route as AuthenticatedRolesRoleIdRouteImport } from './routes/_authenticated/roles/$roleId'
|
||||
import { Route as AuthenticatedMembersMemberIdRouteImport } from './routes/_authenticated/members/$memberId'
|
||||
import { Route as AuthenticatedAccountsNewRouteImport } from './routes/_authenticated/accounts/new'
|
||||
import { Route as AuthenticatedAccountsAccountIdRouteImport } from './routes/_authenticated/accounts/$accountId'
|
||||
@@ -38,11 +42,21 @@ const AuthenticatedIndexRoute = AuthenticatedIndexRouteImport.update({
|
||||
path: '/',
|
||||
getParentRoute: () => AuthenticatedRoute,
|
||||
} as any)
|
||||
const AuthenticatedUsersRoute = AuthenticatedUsersRouteImport.update({
|
||||
id: '/users',
|
||||
path: '/users',
|
||||
getParentRoute: () => AuthenticatedRoute,
|
||||
} as any)
|
||||
const AuthenticatedHelpRoute = AuthenticatedHelpRouteImport.update({
|
||||
id: '/help',
|
||||
path: '/help',
|
||||
getParentRoute: () => AuthenticatedRoute,
|
||||
} as any)
|
||||
const AuthenticatedRolesIndexRoute = AuthenticatedRolesIndexRouteImport.update({
|
||||
id: '/roles/',
|
||||
path: '/roles/',
|
||||
getParentRoute: () => AuthenticatedRoute,
|
||||
} as any)
|
||||
const AuthenticatedMembersIndexRoute =
|
||||
AuthenticatedMembersIndexRouteImport.update({
|
||||
id: '/members/',
|
||||
@@ -55,6 +69,17 @@ const AuthenticatedAccountsIndexRoute =
|
||||
path: '/accounts/',
|
||||
getParentRoute: () => AuthenticatedRoute,
|
||||
} as any)
|
||||
const AuthenticatedRolesNewRoute = AuthenticatedRolesNewRouteImport.update({
|
||||
id: '/roles/new',
|
||||
path: '/roles/new',
|
||||
getParentRoute: () => AuthenticatedRoute,
|
||||
} as any)
|
||||
const AuthenticatedRolesRoleIdRoute =
|
||||
AuthenticatedRolesRoleIdRouteImport.update({
|
||||
id: '/roles/$roleId',
|
||||
path: '/roles/$roleId',
|
||||
getParentRoute: () => AuthenticatedRoute,
|
||||
} as any)
|
||||
const AuthenticatedMembersMemberIdRoute =
|
||||
AuthenticatedMembersMemberIdRouteImport.update({
|
||||
id: '/members/$memberId',
|
||||
@@ -108,11 +133,15 @@ export interface FileRoutesByFullPath {
|
||||
'/': typeof AuthenticatedIndexRoute
|
||||
'/login': typeof LoginRoute
|
||||
'/help': typeof AuthenticatedHelpRoute
|
||||
'/users': typeof AuthenticatedUsersRoute
|
||||
'/accounts/$accountId': typeof AuthenticatedAccountsAccountIdRouteWithChildren
|
||||
'/accounts/new': typeof AuthenticatedAccountsNewRoute
|
||||
'/members/$memberId': typeof AuthenticatedMembersMemberIdRoute
|
||||
'/roles/$roleId': typeof AuthenticatedRolesRoleIdRoute
|
||||
'/roles/new': typeof AuthenticatedRolesNewRoute
|
||||
'/accounts/': typeof AuthenticatedAccountsIndexRoute
|
||||
'/members/': typeof AuthenticatedMembersIndexRoute
|
||||
'/roles/': typeof AuthenticatedRolesIndexRoute
|
||||
'/accounts/$accountId/members': typeof AuthenticatedAccountsAccountIdMembersRoute
|
||||
'/accounts/$accountId/payment-methods': typeof AuthenticatedAccountsAccountIdPaymentMethodsRoute
|
||||
'/accounts/$accountId/processor-links': typeof AuthenticatedAccountsAccountIdProcessorLinksRoute
|
||||
@@ -122,11 +151,15 @@ export interface FileRoutesByFullPath {
|
||||
export interface FileRoutesByTo {
|
||||
'/login': typeof LoginRoute
|
||||
'/help': typeof AuthenticatedHelpRoute
|
||||
'/users': typeof AuthenticatedUsersRoute
|
||||
'/': typeof AuthenticatedIndexRoute
|
||||
'/accounts/new': typeof AuthenticatedAccountsNewRoute
|
||||
'/members/$memberId': typeof AuthenticatedMembersMemberIdRoute
|
||||
'/roles/$roleId': typeof AuthenticatedRolesRoleIdRoute
|
||||
'/roles/new': typeof AuthenticatedRolesNewRoute
|
||||
'/accounts': typeof AuthenticatedAccountsIndexRoute
|
||||
'/members': typeof AuthenticatedMembersIndexRoute
|
||||
'/roles': typeof AuthenticatedRolesIndexRoute
|
||||
'/accounts/$accountId/members': typeof AuthenticatedAccountsAccountIdMembersRoute
|
||||
'/accounts/$accountId/payment-methods': typeof AuthenticatedAccountsAccountIdPaymentMethodsRoute
|
||||
'/accounts/$accountId/processor-links': typeof AuthenticatedAccountsAccountIdProcessorLinksRoute
|
||||
@@ -138,12 +171,16 @@ export interface FileRoutesById {
|
||||
'/_authenticated': typeof AuthenticatedRouteWithChildren
|
||||
'/login': typeof LoginRoute
|
||||
'/_authenticated/help': typeof AuthenticatedHelpRoute
|
||||
'/_authenticated/users': typeof AuthenticatedUsersRoute
|
||||
'/_authenticated/': typeof AuthenticatedIndexRoute
|
||||
'/_authenticated/accounts/$accountId': typeof AuthenticatedAccountsAccountIdRouteWithChildren
|
||||
'/_authenticated/accounts/new': typeof AuthenticatedAccountsNewRoute
|
||||
'/_authenticated/members/$memberId': typeof AuthenticatedMembersMemberIdRoute
|
||||
'/_authenticated/roles/$roleId': typeof AuthenticatedRolesRoleIdRoute
|
||||
'/_authenticated/roles/new': typeof AuthenticatedRolesNewRoute
|
||||
'/_authenticated/accounts/': typeof AuthenticatedAccountsIndexRoute
|
||||
'/_authenticated/members/': typeof AuthenticatedMembersIndexRoute
|
||||
'/_authenticated/roles/': typeof AuthenticatedRolesIndexRoute
|
||||
'/_authenticated/accounts/$accountId/members': typeof AuthenticatedAccountsAccountIdMembersRoute
|
||||
'/_authenticated/accounts/$accountId/payment-methods': typeof AuthenticatedAccountsAccountIdPaymentMethodsRoute
|
||||
'/_authenticated/accounts/$accountId/processor-links': typeof AuthenticatedAccountsAccountIdProcessorLinksRoute
|
||||
@@ -156,11 +193,15 @@ export interface FileRouteTypes {
|
||||
| '/'
|
||||
| '/login'
|
||||
| '/help'
|
||||
| '/users'
|
||||
| '/accounts/$accountId'
|
||||
| '/accounts/new'
|
||||
| '/members/$memberId'
|
||||
| '/roles/$roleId'
|
||||
| '/roles/new'
|
||||
| '/accounts/'
|
||||
| '/members/'
|
||||
| '/roles/'
|
||||
| '/accounts/$accountId/members'
|
||||
| '/accounts/$accountId/payment-methods'
|
||||
| '/accounts/$accountId/processor-links'
|
||||
@@ -170,11 +211,15 @@ export interface FileRouteTypes {
|
||||
to:
|
||||
| '/login'
|
||||
| '/help'
|
||||
| '/users'
|
||||
| '/'
|
||||
| '/accounts/new'
|
||||
| '/members/$memberId'
|
||||
| '/roles/$roleId'
|
||||
| '/roles/new'
|
||||
| '/accounts'
|
||||
| '/members'
|
||||
| '/roles'
|
||||
| '/accounts/$accountId/members'
|
||||
| '/accounts/$accountId/payment-methods'
|
||||
| '/accounts/$accountId/processor-links'
|
||||
@@ -185,12 +230,16 @@ export interface FileRouteTypes {
|
||||
| '/_authenticated'
|
||||
| '/login'
|
||||
| '/_authenticated/help'
|
||||
| '/_authenticated/users'
|
||||
| '/_authenticated/'
|
||||
| '/_authenticated/accounts/$accountId'
|
||||
| '/_authenticated/accounts/new'
|
||||
| '/_authenticated/members/$memberId'
|
||||
| '/_authenticated/roles/$roleId'
|
||||
| '/_authenticated/roles/new'
|
||||
| '/_authenticated/accounts/'
|
||||
| '/_authenticated/members/'
|
||||
| '/_authenticated/roles/'
|
||||
| '/_authenticated/accounts/$accountId/members'
|
||||
| '/_authenticated/accounts/$accountId/payment-methods'
|
||||
| '/_authenticated/accounts/$accountId/processor-links'
|
||||
@@ -226,6 +275,13 @@ declare module '@tanstack/react-router' {
|
||||
preLoaderRoute: typeof AuthenticatedIndexRouteImport
|
||||
parentRoute: typeof AuthenticatedRoute
|
||||
}
|
||||
'/_authenticated/users': {
|
||||
id: '/_authenticated/users'
|
||||
path: '/users'
|
||||
fullPath: '/users'
|
||||
preLoaderRoute: typeof AuthenticatedUsersRouteImport
|
||||
parentRoute: typeof AuthenticatedRoute
|
||||
}
|
||||
'/_authenticated/help': {
|
||||
id: '/_authenticated/help'
|
||||
path: '/help'
|
||||
@@ -233,6 +289,13 @@ declare module '@tanstack/react-router' {
|
||||
preLoaderRoute: typeof AuthenticatedHelpRouteImport
|
||||
parentRoute: typeof AuthenticatedRoute
|
||||
}
|
||||
'/_authenticated/roles/': {
|
||||
id: '/_authenticated/roles/'
|
||||
path: '/roles'
|
||||
fullPath: '/roles/'
|
||||
preLoaderRoute: typeof AuthenticatedRolesIndexRouteImport
|
||||
parentRoute: typeof AuthenticatedRoute
|
||||
}
|
||||
'/_authenticated/members/': {
|
||||
id: '/_authenticated/members/'
|
||||
path: '/members'
|
||||
@@ -247,6 +310,20 @@ declare module '@tanstack/react-router' {
|
||||
preLoaderRoute: typeof AuthenticatedAccountsIndexRouteImport
|
||||
parentRoute: typeof AuthenticatedRoute
|
||||
}
|
||||
'/_authenticated/roles/new': {
|
||||
id: '/_authenticated/roles/new'
|
||||
path: '/roles/new'
|
||||
fullPath: '/roles/new'
|
||||
preLoaderRoute: typeof AuthenticatedRolesNewRouteImport
|
||||
parentRoute: typeof AuthenticatedRoute
|
||||
}
|
||||
'/_authenticated/roles/$roleId': {
|
||||
id: '/_authenticated/roles/$roleId'
|
||||
path: '/roles/$roleId'
|
||||
fullPath: '/roles/$roleId'
|
||||
preLoaderRoute: typeof AuthenticatedRolesRoleIdRouteImport
|
||||
parentRoute: typeof AuthenticatedRoute
|
||||
}
|
||||
'/_authenticated/members/$memberId': {
|
||||
id: '/_authenticated/members/$memberId'
|
||||
path: '/members/$memberId'
|
||||
@@ -335,23 +412,31 @@ const AuthenticatedAccountsAccountIdRouteWithChildren =
|
||||
|
||||
interface AuthenticatedRouteChildren {
|
||||
AuthenticatedHelpRoute: typeof AuthenticatedHelpRoute
|
||||
AuthenticatedUsersRoute: typeof AuthenticatedUsersRoute
|
||||
AuthenticatedIndexRoute: typeof AuthenticatedIndexRoute
|
||||
AuthenticatedAccountsAccountIdRoute: typeof AuthenticatedAccountsAccountIdRouteWithChildren
|
||||
AuthenticatedAccountsNewRoute: typeof AuthenticatedAccountsNewRoute
|
||||
AuthenticatedMembersMemberIdRoute: typeof AuthenticatedMembersMemberIdRoute
|
||||
AuthenticatedRolesRoleIdRoute: typeof AuthenticatedRolesRoleIdRoute
|
||||
AuthenticatedRolesNewRoute: typeof AuthenticatedRolesNewRoute
|
||||
AuthenticatedAccountsIndexRoute: typeof AuthenticatedAccountsIndexRoute
|
||||
AuthenticatedMembersIndexRoute: typeof AuthenticatedMembersIndexRoute
|
||||
AuthenticatedRolesIndexRoute: typeof AuthenticatedRolesIndexRoute
|
||||
}
|
||||
|
||||
const AuthenticatedRouteChildren: AuthenticatedRouteChildren = {
|
||||
AuthenticatedHelpRoute: AuthenticatedHelpRoute,
|
||||
AuthenticatedUsersRoute: AuthenticatedUsersRoute,
|
||||
AuthenticatedIndexRoute: AuthenticatedIndexRoute,
|
||||
AuthenticatedAccountsAccountIdRoute:
|
||||
AuthenticatedAccountsAccountIdRouteWithChildren,
|
||||
AuthenticatedAccountsNewRoute: AuthenticatedAccountsNewRoute,
|
||||
AuthenticatedMembersMemberIdRoute: AuthenticatedMembersMemberIdRoute,
|
||||
AuthenticatedRolesRoleIdRoute: AuthenticatedRolesRoleIdRoute,
|
||||
AuthenticatedRolesNewRoute: AuthenticatedRolesNewRoute,
|
||||
AuthenticatedAccountsIndexRoute: AuthenticatedAccountsIndexRoute,
|
||||
AuthenticatedMembersIndexRoute: AuthenticatedMembersIndexRoute,
|
||||
AuthenticatedRolesIndexRoute: AuthenticatedRolesIndexRoute,
|
||||
}
|
||||
|
||||
const AuthenticatedRouteWithChildren = AuthenticatedRoute._addFileChildren(
|
||||
|
||||
@@ -14,7 +14,7 @@ import {
|
||||
DropdownMenuSubTrigger,
|
||||
DropdownMenuSubContent,
|
||||
} from '@/components/ui/dropdown-menu'
|
||||
import { Users, UserRound, HelpCircle, Sun, Moon, Monitor, LogOut, User, Palette } from 'lucide-react'
|
||||
import { Users, UserRound, HelpCircle, Shield, UserCog, Sun, Moon, Monitor, LogOut, User, Palette } from 'lucide-react'
|
||||
|
||||
export const Route = createFileRoute('/_authenticated')({
|
||||
beforeLoad: () => {
|
||||
@@ -69,6 +69,25 @@ function AuthenticatedLayout() {
|
||||
<UserRound className="h-4 w-4" />
|
||||
Members
|
||||
</Link>
|
||||
<div className="mt-4 mb-1 px-3">
|
||||
<span className="text-xs font-semibold text-sidebar-foreground/50 uppercase tracking-wide">Admin</span>
|
||||
</div>
|
||||
<Link
|
||||
to="/users"
|
||||
className="flex items-center gap-2 px-3 py-2 rounded-md text-sm text-sidebar-foreground hover:bg-sidebar-accent"
|
||||
activeProps={{ className: 'flex items-center gap-2 px-3 py-2 rounded-md text-sm bg-sidebar-accent text-sidebar-accent-foreground' }}
|
||||
>
|
||||
<UserCog className="h-4 w-4" />
|
||||
Users
|
||||
</Link>
|
||||
<Link
|
||||
to="/roles"
|
||||
className="flex items-center gap-2 px-3 py-2 rounded-md text-sm text-sidebar-foreground hover:bg-sidebar-accent"
|
||||
activeProps={{ className: 'flex items-center gap-2 px-3 py-2 rounded-md text-sm bg-sidebar-accent text-sidebar-accent-foreground' }}
|
||||
>
|
||||
<Shield className="h-4 w-4" />
|
||||
Roles
|
||||
</Link>
|
||||
<Link
|
||||
to="/help"
|
||||
className="flex items-center gap-2 px-3 py-2 rounded-md text-sm text-sidebar-foreground hover:bg-sidebar-accent"
|
||||
|
||||
186
packages/admin/src/routes/_authenticated/roles/$roleId.tsx
Normal file
186
packages/admin/src/routes/_authenticated/roles/$roleId.tsx
Normal file
@@ -0,0 +1,186 @@
|
||||
import { createFileRoute, useParams, useNavigate } from '@tanstack/react-router'
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { useState, useEffect } from 'react'
|
||||
import { roleDetailOptions, permissionListOptions, rbacKeys, rbacMutations } from '@/api/rbac'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Textarea } from '@/components/ui/textarea'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Separator } from '@/components/ui/separator'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { ArrowLeft } from 'lucide-react'
|
||||
import { toast } from 'sonner'
|
||||
|
||||
export const Route = createFileRoute('/_authenticated/roles/$roleId')({
|
||||
component: RoleDetailPage,
|
||||
})
|
||||
|
||||
function RoleDetailPage() {
|
||||
const { roleId } = useParams({ from: '/_authenticated/roles/$roleId' })
|
||||
const navigate = useNavigate()
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
const { data: role, isLoading: roleLoading } = useQuery(roleDetailOptions(roleId))
|
||||
const { data: permsData } = useQuery(permissionListOptions())
|
||||
|
||||
const [name, setName] = useState('')
|
||||
const [description, setDescription] = useState('')
|
||||
const [selectedPerms, setSelectedPerms] = useState<Set<string>>(new Set())
|
||||
|
||||
useEffect(() => {
|
||||
if (role) {
|
||||
setName(role.name)
|
||||
setDescription(role.description ?? '')
|
||||
setSelectedPerms(new Set(role.permissions ?? []))
|
||||
}
|
||||
}, [role])
|
||||
|
||||
const updateMutation = useMutation({
|
||||
mutationFn: (data: Record<string, unknown>) => rbacMutations.updateRole(roleId, data),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: rbacKeys.role(roleId) })
|
||||
queryClient.invalidateQueries({ queryKey: rbacKeys.roles })
|
||||
toast.success('Role updated')
|
||||
},
|
||||
onError: (err) => toast.error(err.message),
|
||||
})
|
||||
|
||||
function togglePermission(slug: string) {
|
||||
const next = new Set(selectedPerms)
|
||||
if (next.has(slug)) {
|
||||
next.delete(slug)
|
||||
} else {
|
||||
next.add(slug)
|
||||
}
|
||||
setSelectedPerms(next)
|
||||
}
|
||||
|
||||
function toggleDomain(domain: string, allSlugs: string[]) {
|
||||
const allSelected = allSlugs.every((s) => selectedPerms.has(s))
|
||||
const next = new Set(selectedPerms)
|
||||
for (const slug of allSlugs) {
|
||||
if (allSelected) next.delete(slug)
|
||||
else next.add(slug)
|
||||
}
|
||||
setSelectedPerms(next)
|
||||
}
|
||||
|
||||
function handleSave() {
|
||||
updateMutation.mutate({
|
||||
name,
|
||||
description: description || undefined,
|
||||
permissionSlugs: Array.from(selectedPerms),
|
||||
})
|
||||
}
|
||||
|
||||
if (roleLoading) {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<Skeleton className="h-8 w-48" />
|
||||
<Skeleton className="h-64 w-full" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (!role) {
|
||||
return <p className="text-muted-foreground">Role not found</p>
|
||||
}
|
||||
|
||||
// Group permissions by domain
|
||||
const allPerms = permsData?.data ?? []
|
||||
const domains = new Map<string, typeof allPerms>()
|
||||
for (const p of allPerms) {
|
||||
const list = domains.get(p.domain) ?? []
|
||||
list.push(p)
|
||||
domains.set(p.domain, list)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6 max-w-2xl">
|
||||
<div className="flex items-center gap-3">
|
||||
<Button variant="ghost" size="sm" onClick={() => navigate({ to: '/roles' })}>
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
</Button>
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold">{role.name}</h1>
|
||||
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<span className="font-mono">{role.slug}</span>
|
||||
{role.isSystem && <Badge variant="secondary">System</Badge>}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg">Details</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label>Name</Label>
|
||||
<Input value={name} onChange={(e) => setName(e.target.value)} />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Description</Label>
|
||||
<Textarea value={description} onChange={(e) => setDescription(e.target.value)} />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg">Permissions</CardTitle>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Select which permissions this role grants. Admin implies Edit and View.
|
||||
</p>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
{Array.from(domains.entries()).map(([domain, perms]) => {
|
||||
const slugs = perms.map((p) => p.slug)
|
||||
const allChecked = slugs.every((s) => selectedPerms.has(s))
|
||||
const someChecked = slugs.some((s) => selectedPerms.has(s))
|
||||
|
||||
return (
|
||||
<div key={domain}>
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={allChecked}
|
||||
ref={(el) => { if (el) el.indeterminate = someChecked && !allChecked }}
|
||||
onChange={() => toggleDomain(domain, slugs)}
|
||||
className="rounded"
|
||||
/>
|
||||
<span className="text-sm font-semibold capitalize">{domain}</span>
|
||||
</div>
|
||||
<div className="grid grid-cols-3 gap-2 pl-6">
|
||||
{perms.map((p) => (
|
||||
<label key={p.slug} className="flex items-center gap-2 text-sm cursor-pointer">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={selectedPerms.has(p.slug)}
|
||||
onChange={() => togglePermission(p.slug)}
|
||||
className="rounded"
|
||||
/>
|
||||
<span>{p.action}</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
<Separator className="mt-4" />
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<div className="flex gap-2">
|
||||
<Button onClick={handleSave} disabled={updateMutation.isPending}>
|
||||
{updateMutation.isPending ? 'Saving...' : 'Save Changes'}
|
||||
</Button>
|
||||
<Button variant="secondary" onClick={() => navigate({ to: '/roles' })}>
|
||||
Cancel
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
109
packages/admin/src/routes/_authenticated/roles/index.tsx
Normal file
109
packages/admin/src/routes/_authenticated/roles/index.tsx
Normal file
@@ -0,0 +1,109 @@
|
||||
import { createFileRoute, useNavigate } from '@tanstack/react-router'
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { roleListOptions, rbacKeys, rbacMutations } from '@/api/rbac'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu'
|
||||
import { Plus, MoreVertical, Pencil, Trash2, Shield } from 'lucide-react'
|
||||
import { toast } from 'sonner'
|
||||
|
||||
export const Route = createFileRoute('/_authenticated/roles/')({
|
||||
component: RolesListPage,
|
||||
})
|
||||
|
||||
function RolesListPage() {
|
||||
const navigate = useNavigate()
|
||||
const queryClient = useQueryClient()
|
||||
const { data, isLoading } = useQuery(roleListOptions())
|
||||
|
||||
const deleteMutation = useMutation({
|
||||
mutationFn: rbacMutations.deleteRole,
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: rbacKeys.roles })
|
||||
toast.success('Role deleted')
|
||||
},
|
||||
onError: (err) => toast.error(err.message),
|
||||
})
|
||||
|
||||
const roles = data?.data ?? []
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<h1 className="text-2xl font-bold">Roles</h1>
|
||||
<Button onClick={() => navigate({ to: '/roles/new' })}>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
New Role
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{isLoading ? (
|
||||
<p className="text-muted-foreground">Loading...</p>
|
||||
) : roles.length === 0 ? (
|
||||
<p className="text-muted-foreground py-8 text-center">No roles found</p>
|
||||
) : (
|
||||
<div className="rounded-md border">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Name</TableHead>
|
||||
<TableHead>Slug</TableHead>
|
||||
<TableHead>Description</TableHead>
|
||||
<TableHead>Type</TableHead>
|
||||
<TableHead className="w-12"></TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{roles.map((role) => (
|
||||
<TableRow key={role.id}>
|
||||
<TableCell className="font-medium">
|
||||
<div className="flex items-center gap-2">
|
||||
<Shield className="h-4 w-4 text-muted-foreground" />
|
||||
{role.name}
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell className="font-mono text-sm text-muted-foreground">{role.slug}</TableCell>
|
||||
<TableCell className="text-sm text-muted-foreground">{role.description ?? '-'}</TableCell>
|
||||
<TableCell>
|
||||
{role.isSystem ? <Badge variant="secondary">System</Badge> : <Badge>Custom</Badge>}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="sm" className="h-8 w-8 p-0">
|
||||
<MoreVertical className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={() => navigate({ to: '/roles/$roleId', params: { roleId: role.id } })}>
|
||||
<Pencil className="mr-2 h-4 w-4" />
|
||||
Edit Permissions
|
||||
</DropdownMenuItem>
|
||||
{!role.isSystem && (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem className="text-destructive" onClick={() => deleteMutation.mutate(role.id)}>
|
||||
<Trash2 className="mr-2 h-4 w-4" />
|
||||
Delete
|
||||
</DropdownMenuItem>
|
||||
</>
|
||||
)}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
162
packages/admin/src/routes/_authenticated/roles/new.tsx
Normal file
162
packages/admin/src/routes/_authenticated/roles/new.tsx
Normal file
@@ -0,0 +1,162 @@
|
||||
import { createFileRoute, useNavigate } from '@tanstack/react-router'
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { useState } from 'react'
|
||||
import { permissionListOptions, rbacKeys, rbacMutations } from '@/api/rbac'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Textarea } from '@/components/ui/textarea'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Separator } from '@/components/ui/separator'
|
||||
import { toast } from 'sonner'
|
||||
|
||||
export const Route = createFileRoute('/_authenticated/roles/new')({
|
||||
component: NewRolePage,
|
||||
})
|
||||
|
||||
function NewRolePage() {
|
||||
const navigate = useNavigate()
|
||||
const queryClient = useQueryClient()
|
||||
const { data: permsData } = useQuery(permissionListOptions())
|
||||
|
||||
const [name, setName] = useState('')
|
||||
const [slug, setSlug] = useState('')
|
||||
const [description, setDescription] = useState('')
|
||||
const [selectedPerms, setSelectedPerms] = useState<Set<string>>(new Set())
|
||||
|
||||
const mutation = useMutation({
|
||||
mutationFn: rbacMutations.createRole,
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: rbacKeys.roles })
|
||||
toast.success('Role created')
|
||||
navigate({ to: '/roles' })
|
||||
},
|
||||
onError: (err) => toast.error(err.message),
|
||||
})
|
||||
|
||||
function togglePermission(permSlug: string) {
|
||||
const next = new Set(selectedPerms)
|
||||
if (next.has(permSlug)) next.delete(permSlug)
|
||||
else next.add(permSlug)
|
||||
setSelectedPerms(next)
|
||||
}
|
||||
|
||||
function toggleDomain(domain: string, allSlugs: string[]) {
|
||||
const allSelected = allSlugs.every((s) => selectedPerms.has(s))
|
||||
const next = new Set(selectedPerms)
|
||||
for (const s of allSlugs) {
|
||||
if (allSelected) next.delete(s)
|
||||
else next.add(s)
|
||||
}
|
||||
setSelectedPerms(next)
|
||||
}
|
||||
|
||||
function handleNameChange(value: string) {
|
||||
setName(value)
|
||||
if (!slug || slug === nameToSlug(name)) {
|
||||
setSlug(nameToSlug(value))
|
||||
}
|
||||
}
|
||||
|
||||
function nameToSlug(n: string) {
|
||||
return n.toLowerCase().replace(/[^a-z0-9]+/g, '_').replace(/^_|_$/g, '')
|
||||
}
|
||||
|
||||
function handleSubmit() {
|
||||
if (!name || !slug) {
|
||||
toast.error('Name and slug are required')
|
||||
return
|
||||
}
|
||||
mutation.mutate({
|
||||
name,
|
||||
slug,
|
||||
description: description || undefined,
|
||||
permissionSlugs: Array.from(selectedPerms),
|
||||
})
|
||||
}
|
||||
|
||||
const allPerms = permsData?.data ?? []
|
||||
const domains = new Map<string, typeof allPerms>()
|
||||
for (const p of allPerms) {
|
||||
const list = domains.get(p.domain) ?? []
|
||||
list.push(p)
|
||||
domains.set(p.domain, list)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6 max-w-2xl">
|
||||
<h1 className="text-2xl font-bold">New Role</h1>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg">Details</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label>Name *</Label>
|
||||
<Input value={name} onChange={(e) => handleNameChange(e.target.value)} placeholder="e.g. School Sales Rep" />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Slug *</Label>
|
||||
<Input value={slug} onChange={(e) => setSlug(e.target.value)} placeholder="auto-generated" className="font-mono" />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Description</Label>
|
||||
<Textarea value={description} onChange={(e) => setDescription(e.target.value)} />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg">Permissions</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
{Array.from(domains.entries()).map(([domain, perms]) => {
|
||||
const slugs = perms.map((p) => p.slug)
|
||||
const allChecked = slugs.every((s) => selectedPerms.has(s))
|
||||
const someChecked = slugs.some((s) => selectedPerms.has(s))
|
||||
|
||||
return (
|
||||
<div key={domain}>
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={allChecked}
|
||||
ref={(el) => { if (el) el.indeterminate = someChecked && !allChecked }}
|
||||
onChange={() => toggleDomain(domain, slugs)}
|
||||
className="rounded"
|
||||
/>
|
||||
<span className="text-sm font-semibold capitalize">{domain}</span>
|
||||
</div>
|
||||
<div className="grid grid-cols-3 gap-2 pl-6">
|
||||
{perms.map((p) => (
|
||||
<label key={p.slug} className="flex items-center gap-2 text-sm cursor-pointer">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={selectedPerms.has(p.slug)}
|
||||
onChange={() => togglePermission(p.slug)}
|
||||
className="rounded"
|
||||
/>
|
||||
<span>{p.action}</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
<Separator className="mt-4" />
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<div className="flex gap-2">
|
||||
<Button onClick={handleSubmit} disabled={mutation.isPending}>
|
||||
{mutation.isPending ? 'Creating...' : 'Create Role'}
|
||||
</Button>
|
||||
<Button variant="secondary" onClick={() => navigate({ to: '/roles' })}>
|
||||
Cancel
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
195
packages/admin/src/routes/_authenticated/users.tsx
Normal file
195
packages/admin/src/routes/_authenticated/users.tsx
Normal file
@@ -0,0 +1,195 @@
|
||||
import { createFileRoute, useNavigate } from '@tanstack/react-router'
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { useState } from 'react'
|
||||
import { api } from '@/lib/api-client'
|
||||
import { roleListOptions, rbacKeys, rbacMutations } from '@/api/rbac'
|
||||
import { userRolesOptions, type UserRecord } from '@/api/users'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu'
|
||||
import { MoreVertical, Shield, Plus, X } from 'lucide-react'
|
||||
import { toast } from 'sonner'
|
||||
import { queryOptions } from '@tanstack/react-query'
|
||||
|
||||
function userListOptions() {
|
||||
return queryOptions({
|
||||
queryKey: ['users'],
|
||||
queryFn: () => api.get<{ data: UserRecord[] }>('/v1/users'),
|
||||
})
|
||||
}
|
||||
|
||||
export const Route = createFileRoute('/_authenticated/users')({
|
||||
component: UsersPage,
|
||||
})
|
||||
|
||||
function UserRoleBadges({ userId }: { userId: string }) {
|
||||
const { data } = useQuery(userRolesOptions(userId))
|
||||
const roles = data?.data ?? []
|
||||
|
||||
if (roles.length === 0) return <span className="text-sm text-muted-foreground">No roles</span>
|
||||
|
||||
return (
|
||||
<div className="flex flex-wrap gap-1">
|
||||
{roles.map((r) => (
|
||||
<Badge key={r.id} variant={r.isSystem ? 'secondary' : 'default'} className="text-xs">
|
||||
{r.name}
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function ManageRolesDialog({ user, open, onClose }: { user: UserRecord; open: boolean; onClose: () => void }) {
|
||||
const queryClient = useQueryClient()
|
||||
const { data: userRolesData } = useQuery(userRolesOptions(user.id))
|
||||
const { data: allRolesData } = useQuery(roleListOptions())
|
||||
const [selectedRoleId, setSelectedRoleId] = useState('')
|
||||
|
||||
const userRoles = userRolesData?.data ?? []
|
||||
const allRoles = allRolesData?.data ?? []
|
||||
const assignedIds = new Set(userRoles.map((r) => r.id))
|
||||
const availableRoles = allRoles.filter((r) => !assignedIds.has(r.id))
|
||||
|
||||
const assignMutation = useMutation({
|
||||
mutationFn: (roleId: string) => rbacMutations.assignRole(user.id, roleId),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['users', user.id, 'roles'] })
|
||||
setSelectedRoleId('')
|
||||
toast.success('Role assigned')
|
||||
},
|
||||
onError: (err) => toast.error(err.message),
|
||||
})
|
||||
|
||||
const removeMutation = useMutation({
|
||||
mutationFn: (roleId: string) => rbacMutations.removeRole(user.id, roleId),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['users', user.id, 'roles'] })
|
||||
toast.success('Role removed')
|
||||
},
|
||||
onError: (err) => toast.error(err.message),
|
||||
})
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={(o) => !o && onClose()}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Manage Roles — {user.firstName} {user.lastName}</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<p className="text-sm font-medium">Assigned Roles</p>
|
||||
{userRoles.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground">No roles assigned</p>
|
||||
) : (
|
||||
<div className="space-y-1">
|
||||
{userRoles.map((r) => (
|
||||
<div key={r.id} className="flex items-center justify-between p-2 rounded-md border">
|
||||
<div className="flex items-center gap-2">
|
||||
<Shield className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="text-sm font-medium">{r.name}</span>
|
||||
{r.isSystem && <Badge variant="secondary" className="text-xs">System</Badge>}
|
||||
</div>
|
||||
<Button variant="ghost" size="sm" className="h-6 w-6 p-0" onClick={() => removeMutation.mutate(r.id)}>
|
||||
<X className="h-3 w-3 text-destructive" />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{availableRoles.length > 0 && (
|
||||
<div className="flex gap-2">
|
||||
<Select value={selectedRoleId} onValueChange={setSelectedRoleId}>
|
||||
<SelectTrigger className="flex-1">
|
||||
<SelectValue placeholder="Select a role to add" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{availableRoles.map((r) => (
|
||||
<SelectItem key={r.id} value={r.id}>{r.name}</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Button
|
||||
size="sm"
|
||||
disabled={!selectedRoleId || assignMutation.isPending}
|
||||
onClick={() => selectedRoleId && assignMutation.mutate(selectedRoleId)}
|
||||
>
|
||||
<Plus className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
function UsersPage() {
|
||||
const { data, isLoading } = useQuery(userListOptions())
|
||||
const [managingUser, setManagingUser] = useState<UserRecord | null>(null)
|
||||
|
||||
const allUsers = data?.data ?? []
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<h1 className="text-2xl font-bold">Users</h1>
|
||||
|
||||
{managingUser && (
|
||||
<ManageRolesDialog user={managingUser} open={!!managingUser} onClose={() => setManagingUser(null)} />
|
||||
)}
|
||||
|
||||
{isLoading ? (
|
||||
<p className="text-muted-foreground">Loading...</p>
|
||||
) : allUsers.length === 0 ? (
|
||||
<p className="text-muted-foreground py-8 text-center">No users found</p>
|
||||
) : (
|
||||
<div className="rounded-md border">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Name</TableHead>
|
||||
<TableHead>Email</TableHead>
|
||||
<TableHead>Roles</TableHead>
|
||||
<TableHead className="w-12"></TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{allUsers.map((user) => (
|
||||
<TableRow key={user.id}>
|
||||
<TableCell className="font-medium">{user.firstName} {user.lastName}</TableCell>
|
||||
<TableCell>{user.email}</TableCell>
|
||||
<TableCell><UserRoleBadges userId={user.id} /></TableCell>
|
||||
<TableCell>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="sm" className="h-8 w-8 p-0">
|
||||
<MoreVertical className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={() => setManagingUser(user)}>
|
||||
<Shield className="mr-2 h-4 w-4" />
|
||||
Manage Roles
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
25
packages/admin/src/types/rbac.ts
Normal file
25
packages/admin/src/types/rbac.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
export interface Permission {
|
||||
id: string
|
||||
slug: string
|
||||
domain: string
|
||||
action: string
|
||||
description: string
|
||||
}
|
||||
|
||||
export interface Role {
|
||||
id: string
|
||||
companyId: string
|
||||
name: string
|
||||
slug: string
|
||||
description: string | null
|
||||
isSystem: boolean
|
||||
isActive: boolean
|
||||
permissions?: string[]
|
||||
}
|
||||
|
||||
export interface UserRoleAssignment {
|
||||
id: string
|
||||
name: string
|
||||
slug: string
|
||||
isSystem: boolean
|
||||
}
|
||||
@@ -14,6 +14,7 @@ import { inventoryRoutes } from './routes/v1/inventory.js'
|
||||
import { productRoutes } from './routes/v1/products.js'
|
||||
import { lookupRoutes } from './routes/v1/lookups.js'
|
||||
import { fileRoutes } from './routes/v1/files.js'
|
||||
import { rbacRoutes } from './routes/v1/rbac.js'
|
||||
|
||||
export async function buildApp() {
|
||||
const app = Fastify({
|
||||
@@ -62,6 +63,7 @@ export async function buildApp() {
|
||||
await app.register(productRoutes, { prefix: '/v1' })
|
||||
await app.register(lookupRoutes, { prefix: '/v1' })
|
||||
await app.register(fileRoutes, { prefix: '/v1' })
|
||||
await app.register(rbacRoutes, { prefix: '/v1' })
|
||||
|
||||
return app
|
||||
}
|
||||
|
||||
138
packages/backend/src/routes/v1/rbac.ts
Normal file
138
packages/backend/src/routes/v1/rbac.ts
Normal file
@@ -0,0 +1,138 @@
|
||||
import type { FastifyPluginAsync } from 'fastify'
|
||||
import { eq, and } from 'drizzle-orm'
|
||||
import { RbacService } from '../../services/rbac.service.js'
|
||||
import { ValidationError } from '../../lib/errors.js'
|
||||
import { users } from '../../db/schema/users.js'
|
||||
|
||||
export const rbacRoutes: FastifyPluginAsync = async (app) => {
|
||||
// --- Users list ---
|
||||
|
||||
app.get('/users', { preHandler: [app.authenticate, app.requirePermission('users.view')] }, async (request, reply) => {
|
||||
const allUsers = await app.db
|
||||
.select({
|
||||
id: users.id,
|
||||
email: users.email,
|
||||
firstName: users.firstName,
|
||||
lastName: users.lastName,
|
||||
role: users.role,
|
||||
createdAt: users.createdAt,
|
||||
})
|
||||
.from(users)
|
||||
.where(eq(users.companyId, request.companyId))
|
||||
.orderBy(users.lastName)
|
||||
|
||||
return reply.send({ data: allUsers })
|
||||
})
|
||||
// --- Permissions ---
|
||||
|
||||
app.get('/permissions', { preHandler: [app.authenticate, app.requirePermission('users.view')] }, async (request, reply) => {
|
||||
const data = await RbacService.listPermissions(app.db)
|
||||
return reply.send({ data })
|
||||
})
|
||||
|
||||
// --- Roles ---
|
||||
|
||||
app.get('/roles', { preHandler: [app.authenticate, app.requirePermission('users.view')] }, async (request, reply) => {
|
||||
const data = await RbacService.listRoles(app.db, request.companyId)
|
||||
return reply.send({ data })
|
||||
})
|
||||
|
||||
app.get('/roles/:id', { preHandler: [app.authenticate, app.requirePermission('users.view')] }, async (request, reply) => {
|
||||
const { id } = request.params as { id: string }
|
||||
const role = await RbacService.getRoleWithPermissions(app.db, request.companyId, id)
|
||||
if (!role) return reply.status(404).send({ error: { message: 'Role not found', statusCode: 404 } })
|
||||
return reply.send(role)
|
||||
})
|
||||
|
||||
app.post('/roles', { preHandler: [app.authenticate, app.requirePermission('users.admin')] }, async (request, reply) => {
|
||||
const { name, slug, description, permissionSlugs } = request.body as {
|
||||
name?: string
|
||||
slug?: string
|
||||
description?: string
|
||||
permissionSlugs?: string[]
|
||||
}
|
||||
|
||||
if (!name || !slug || !permissionSlugs) {
|
||||
throw new ValidationError('name, slug, and permissionSlugs are required')
|
||||
}
|
||||
|
||||
if (!/^[a-z0-9_]+$/.test(slug)) {
|
||||
throw new ValidationError('slug must be lowercase alphanumeric with underscores')
|
||||
}
|
||||
|
||||
const role = await RbacService.createRole(app.db, request.companyId, {
|
||||
name,
|
||||
slug,
|
||||
description,
|
||||
permissionSlugs,
|
||||
})
|
||||
|
||||
request.log.info({ roleId: role?.id, roleName: name, userId: request.user.id }, 'Role created')
|
||||
return reply.status(201).send(role)
|
||||
})
|
||||
|
||||
app.patch('/roles/:id', { preHandler: [app.authenticate, app.requirePermission('users.admin')] }, async (request, reply) => {
|
||||
const { id } = request.params as { id: string }
|
||||
const { name, description, permissionSlugs } = request.body as {
|
||||
name?: string
|
||||
description?: string
|
||||
permissionSlugs?: string[]
|
||||
}
|
||||
|
||||
const role = await RbacService.updateRole(app.db, request.companyId, id, {
|
||||
name,
|
||||
description,
|
||||
permissionSlugs,
|
||||
})
|
||||
|
||||
if (!role) return reply.status(404).send({ error: { message: 'Role not found', statusCode: 404 } })
|
||||
request.log.info({ roleId: id, userId: request.user.id }, 'Role updated')
|
||||
return reply.send(role)
|
||||
})
|
||||
|
||||
app.delete('/roles/:id', { preHandler: [app.authenticate, app.requirePermission('users.admin')] }, async (request, reply) => {
|
||||
const { id } = request.params as { id: string }
|
||||
const role = await RbacService.deleteRole(app.db, request.companyId, id)
|
||||
if (!role) return reply.status(404).send({ error: { message: 'Role not found', statusCode: 404 } })
|
||||
request.log.info({ roleId: id, roleName: role.name, userId: request.user.id }, 'Role deleted')
|
||||
return reply.send(role)
|
||||
})
|
||||
|
||||
// --- User Role Assignments ---
|
||||
|
||||
app.get('/users/:userId/roles', { preHandler: [app.authenticate, app.requirePermission('users.view')] }, async (request, reply) => {
|
||||
const { userId } = request.params as { userId: string }
|
||||
const data = await RbacService.getUserRoles(app.db, userId)
|
||||
return reply.send({ data })
|
||||
})
|
||||
|
||||
app.post('/users/:userId/roles', { preHandler: [app.authenticate, app.requirePermission('users.edit')] }, async (request, reply) => {
|
||||
const { userId } = request.params as { userId: string }
|
||||
const { roleId } = request.body as { roleId?: string }
|
||||
|
||||
if (!roleId) throw new ValidationError('roleId is required')
|
||||
|
||||
const assignment = await RbacService.assignRole(app.db, userId, roleId, request.user.id)
|
||||
request.log.info({ userId, roleId, assignedBy: request.user.id }, 'Role assigned to user')
|
||||
return reply.status(201).send(assignment)
|
||||
})
|
||||
|
||||
app.delete('/users/:userId/roles/:roleId', { preHandler: [app.authenticate, app.requirePermission('users.edit')] }, async (request, reply) => {
|
||||
const { userId, roleId } = request.params as { userId: string; roleId: string }
|
||||
const removed = await RbacService.removeRole(app.db, userId, roleId)
|
||||
if (!removed) return reply.status(404).send({ error: { message: 'Role assignment not found', statusCode: 404 } })
|
||||
request.log.info({ userId, roleId, removedBy: request.user.id }, 'Role removed from user')
|
||||
return reply.send(removed)
|
||||
})
|
||||
|
||||
// --- Current user permissions ---
|
||||
|
||||
app.get('/me/permissions', { preHandler: [app.authenticate] }, async (request, reply) => {
|
||||
const permSlugs = await RbacService.getUserPermissions(app.db, request.user.id)
|
||||
const userRoles = await RbacService.getUserRoles(app.db, request.user.id)
|
||||
return reply.send({
|
||||
permissions: permSlugs,
|
||||
roles: userRoles,
|
||||
})
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user