npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@dbs-portal/module-identity

v1.0.0

Published

Identity management module for user and role management

Readme

@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

# 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

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

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

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

interface UserListProps {
  users: User[]
  loading?: boolean
  onEdit?: (user: User) => void
  onDelete?: (user: User) => void
  onLock?: (user: User) => void
  onUnlock?: (user: User) => void
}

UserCreate Props

interface UserCreateProps {
  onSubmit?: (data: CreateUserFormData) => void
  loading?: boolean
  error?: string
  className?: string
}

RoleList Props

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

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

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

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

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:

# 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 file for details.

🔗 Related Packages