UNPKG

@dbs-portal/module-identity

Version:

Identity management module for user and role management

383 lines (310 loc) โ€ข 10.9 kB
# @dbs-portal/module-identity A comprehensive identity management module for the DBS Portal, providing user and role management capabilities with advanced security features. ## ๐Ÿš€ Features ### User Management - **Complete CRUD Operations**: Create, read, update, and delete users - **User Authentication**: Login/logout, password management, account verification - **Profile Management**: User profiles with customizable fields and avatar support - **Account Security**: Two-factor authentication, account lockout, password policies - **User Status Management**: Active/inactive users, email/phone verification ### Role-Based Access Control (RBAC) - **Role Management**: Create and manage custom roles with specific permissions - **Permission System**: Granular permission control for different system features - **Default Roles**: System-defined roles that are automatically assigned - **Static Roles**: Protected system roles that cannot be deleted - **Role Assignment**: Assign multiple roles to users with inheritance ### Security & Compliance - **Audit Logging**: Comprehensive audit trail for all identity-related activities - **Risk Assessment**: Automatic risk level calculation for security events - **Account Lockout**: Configurable lockout policies for failed login attempts - **Password Policies**: Enforced password complexity and rotation policies - **Session Management**: Control user sessions and concurrent logins ### Administration - **System Overview**: Real-time statistics and monitoring dashboards - **Bulk Operations**: Mass user operations and data export capabilities - **Security Settings**: Configurable security policies and system settings - **Alert System**: Automated alerts for security events and policy violations ## ๐Ÿ“ฆ Installation ```bash # Install the module yarn add @dbs-portal/module-identity # Install peer dependencies yarn add @dbs-portal/core-api @dbs-portal/core-auth @dbs-portal/core-shared @dbs-portal/core-store @dbs-portal/core-ui ``` ## ๐Ÿ—๏ธ Architecture ### Package Structure ``` packages/modules/identity/ โ”œโ”€โ”€ src/ โ”‚ โ”œโ”€โ”€ components/ # React components โ”‚ โ”‚ โ”œโ”€โ”€ UserList.tsx # User listing with filters โ”‚ โ”‚ โ”œโ”€โ”€ UserCreate.tsx # User creation form โ”‚ โ”‚ โ”œโ”€โ”€ UserEdit.tsx # User editing form โ”‚ โ”‚ โ”œโ”€โ”€ UserDetails.tsx # User detail view โ”‚ โ”‚ โ”œโ”€โ”€ RoleList.tsx # Role listing โ”‚ โ”‚ โ”œโ”€โ”€ RoleCreate.tsx # Role creation form โ”‚ โ”‚ โ”œโ”€โ”€ RoleEdit.tsx # Role editing form โ”‚ โ”‚ โ”œโ”€โ”€ RoleDetails.tsx # Role detail view โ”‚ โ”‚ โ”œโ”€โ”€ IdentityAdmin.tsx # Admin dashboard โ”‚ โ”‚ โ””โ”€โ”€ IdentityAudit.tsx # Audit log viewer โ”‚ โ”œโ”€โ”€ hooks/ # React Query hooks โ”‚ โ”‚ โ”œโ”€โ”€ use-users.ts # User management hooks โ”‚ โ”‚ โ””โ”€โ”€ use-roles.ts # Role management hooks โ”‚ โ”œโ”€โ”€ services/ # API services โ”‚ โ”‚ โ”œโ”€โ”€ user-service.ts # User API operations โ”‚ โ”‚ โ””โ”€โ”€ role-service.ts # Role API operations โ”‚ โ”œโ”€โ”€ types.ts # TypeScript definitions โ”‚ โ””โ”€โ”€ index.ts # Main exports โ”œโ”€โ”€ package.json โ”œโ”€โ”€ tsconfig.json โ”œโ”€โ”€ vite.config.ts โ””โ”€โ”€ README.md ``` ### Dependencies - **Core Dependencies**: React 18, TypeScript 5, Ant Design 5 - **State Management**: Zustand with React Query for server state - **Routing**: TanStack Router for navigation - **Validation**: Zod for runtime type validation - **Date Handling**: date-fns for date formatting and manipulation - **Utilities**: lodash-es for utility functions ## ๐ŸŽฏ Quick Start ### 1. Basic User Management ```tsx import { UserList, UserCreate, UserEdit } from '@dbs-portal/module-identity' function UserManagementPage() { return ( <div> <UserList onEdit={(user) => console.log('Edit user:', user)} onDelete={(user) => console.log('Delete user:', user)} onLock={(user) => console.log('Lock user:', user)} onUnlock={(user) => console.log('Unlock user:', user)} /> </div> ) } ``` ### 2. Role Management ```tsx import { RoleList, RoleCreate, useRoles } from '@dbs-portal/module-identity' function RoleManagementPage() { const { data: roles, isLoading } = useRoles() return ( <div> <RoleList roles={roles?.data || []} loading={isLoading} onEdit={(role) => console.log('Edit role:', role)} onDelete={(role) => console.log('Delete role:', role)} /> </div> ) } ``` ### 3. Using Hooks for Data Management ```tsx import { useUsers, useCreateUser, useUpdateUser, useDeleteUser } from '@dbs-portal/module-identity' function UserHookExample() { const { data: users, isLoading } = useUsers({ isActive: true }) const createUser = useCreateUser() const updateUser = useUpdateUser() const deleteUser = useDeleteUser() const handleCreateUser = async (userData) => { try { await createUser.mutateAsync(userData) console.log('User created successfully') } catch (error) { console.error('Failed to create user:', error) } } return ( <div> {/* Your component JSX */} </div> ) } ``` ## ๐Ÿ”ง API Reference ### User Service #### Methods - `getUsers(filters)` - Get paginated list of users - `getUser(id)` - Get single user by ID - `createUser(userData)` - Create new user - `updateUser(userData)` - Update existing user - `deleteUser(id)` - Delete user - `changePassword(request)` - Change user password - `lockUser(request)` - Lock user account - `unlockUser(userId)` - Unlock user account - `setupTwoFactor(userId)` - Setup 2FA for user - `verifyTwoFactor(request)` - Verify 2FA setup - `disableTwoFactor(userId)` - Disable 2FA - `getUserRoles(userId)` - Get user's assigned roles - `assignRoles(userId, roleNames)` - Assign roles to user - `getUserPermissions(userId)` - Get user's permissions ### Role Service #### Methods - `getRoles(filters)` - Get paginated list of roles - `getRole(id)` - Get single role by ID - `createRole(roleData)` - Create new role - `updateRole(roleData)` - Update existing role - `deleteRole(id)` - Delete role - `getRolePermissions(roleId)` - Get role permissions - `grantPermission(roleId, permission)` - Grant permission to role - `revokePermission(roleId, permission)` - Revoke permission from role - `setPermissions(roleId, permissions)` - Set all role permissions - `getRoleUsers(roleId)` - Get users with specific role ## ๐ŸŽจ Component Props ### UserList Props ```typescript interface UserListProps { users: User[] loading?: boolean onEdit?: (user: User) => void onDelete?: (user: User) => void onLock?: (user: User) => void onUnlock?: (user: User) => void } ``` ### UserCreate Props ```typescript interface UserCreateProps { onSubmit?: (data: CreateUserFormData) => void loading?: boolean error?: string className?: string } ``` ### RoleList Props ```typescript interface RoleListProps { roles: Role[] loading?: boolean onEdit?: (role: Role) => void onDelete?: (role: Role) => void } ``` ## ๐Ÿ” Security Features ### Password Policy - Configurable minimum length (default: 8 characters) - Character requirements (uppercase, lowercase, numbers, special chars) - Password strength validation - Password history prevention - Automatic password expiration ### Account Lockout - Failed login attempt tracking - Configurable lockout thresholds - Automatic unlock after specified duration - Manual unlock capabilities for administrators ### Two-Factor Authentication - TOTP (Time-based One-Time Password) support - QR code generation for authenticator apps - Recovery codes for account recovery - Backup authentication methods ### Audit Logging - Comprehensive activity tracking - Risk level assessment - IP address and user agent logging - Exportable audit reports - Real-time security alerts ## ๐Ÿš€ Advanced Usage ### Custom Permission System ```tsx import { useUserPermissions, useRolePermissions } from '@dbs-portal/module-identity' function PermissionGuard({ permission, children }) { const { data: userPermissions } = useUserPermissions(currentUserId) if (!userPermissions?.includes(permission)) { return <div>Access Denied</div> } return children } ``` ### Bulk User Operations ```tsx import { useBulkUserOperation } from '@dbs-portal/module-identity' function BulkUserActions() { const bulkOperation = useBulkUserOperation() const handleBulkActivate = async (userIds: string[]) => { await bulkOperation.mutateAsync({ operation: 'activate', userIds }) } return ( <Button onClick={() => handleBulkActivate(selectedUserIds)}> Activate Selected Users </Button> ) } ``` ## ๐Ÿ“Š Monitoring & Analytics ### User Statistics - Total user count and growth trends - Active vs inactive user ratios - Email and phone verification rates - Two-factor authentication adoption - Geographic distribution of users ### Security Metrics - Failed login attempt patterns - Account lockout frequency - Password change frequency - High-risk activity detection - Compliance audit reports ## ๐Ÿ”„ Integration ### With Authentication System ```tsx import { useAuthStore } from '@dbs-portal/core-auth' import { useUser } from '@dbs-portal/module-identity' function UserProfile() { const { user: authUser } = useAuthStore() const { data: userDetails } = useUser(authUser?.id) return ( <UserDetails user={userDetails} onEdit={() => navigate('/profile/edit')} /> ) } ``` ### With Permission System ```tsx import { useUserPermissions } from '@dbs-portal/module-identity' function ProtectedComponent() { const { data: permissions } = useUserPermissions(userId) const canEdit = permissions?.includes('Users.Update') const canDelete = permissions?.includes('Users.Delete') return ( <div> {canEdit && <EditButton />} {canDelete && <DeleteButton />} </div> ) } ``` ## ๐Ÿงช Testing The module includes comprehensive test coverage: ```bash # Run tests yarn test # Run tests with coverage yarn test:coverage # Run tests in watch mode yarn test:watch ``` ## ๐Ÿ“ Contributing 1. Follow the established code patterns and TypeScript conventions 2. Ensure all components have proper prop types and documentation 3. Add tests for new functionality 4. Update this README for any new features or breaking changes 5. Follow the monorepo's linting and formatting standards ## ๐Ÿ“„ License MIT License - see the [LICENSE](../../LICENSE) file for details. ## ๐Ÿ”— Related Packages - [`@dbs-portal/core-auth`](../core/auth) - Authentication and authorization - [`@dbs-portal/core-api`](../core/api) - HTTP client and API utilities - [`@dbs-portal/core-ui`](../core/ui) - Shared UI components - [`@dbs-portal/core-shared`](../core/shared) - Common types and utilities