Skip to main content

User Management Overview

The Akako LMS user management system provides comprehensive functionality for managing users, roles, and permissions. Built with Clerk.js authentication and PostgreSQL-based role management, it offers flexible and secure user administration.

User Roles

Role Hierarchy

The system implements a three-tier role structure:

ADMIN (Full System Access)
├── User Management
├── Content Management
├── System Configuration
└── Analytics & Reports

MENTOR (Educational Content Management)
├── Subject Management
├── Student Guidance
├── Content Creation
└── Progress Monitoring

LEARNER (Learning & Course Access)
├── Course Enrollment
├── Progress Tracking
├── Note-taking
└── Resource Access

Role Capabilities

ADMIN Role

  • User Management: Create, update, delete users
  • Role Assignment: Assign/remove roles with effective dates
  • Content Oversight: Manage all educational content
  • System Configuration: Configure education levels, grades, subjects
  • Analytics: Access system-wide reports and statistics
  • Mentor Management: Approve/reject mentor applications
  • Enrollment Management: Approve/reject course enrollments

MENTOR Role

  • Subject Management: Create and manage subjects assigned to them
  • Content Creation: Upload videos, documents, and educational materials
  • Student Interaction: Monitor student progress and provide guidance
  • Topic Management: Create and organize topics within their subjects
  • Student Notes: View and respond to student notes

LEARNER Role

  • Course Access: Enroll in subjects and access educational content
  • Progress Tracking: Monitor learning progress and completion
  • Note-taking: Create personal notes for topics
  • Resource Downloads: Download study materials and documents
  • Profile Management: Update personal information and preferences

User Lifecycle

Registration Process

  1. User Registration: Users register through Clerk.js authentication
  2. Automatic Role Assignment: New users automatically receive LEARNER role
  3. Profile Completion: Users complete onboarding profile (optional but recommended)
  4. Role Upgrades: Users can apply for MENTOR role through application process

Profile Management

Required Profile Fields

  • First Name
  • Last Name
  • Email Address
  • Address
  • City
  • Country
  • Timezone
  • Education Level
  • Learning Goals
  • Preferred Learning Style

Optional Profile Fields

  • Bio
  • Phone Number
  • Current Role
  • Experience Level
  • Interests

Role Assignment Process

Automatic Assignment

  • New Users: Automatically assigned LEARNER role
  • Effective Date: Role becomes active immediately
  • Audit Trail: All assignments are logged with timestamps

Manual Assignment (Admin Only)

// Assign role to user
const roleAssignment = await prisma.userRole.create({
data: {
userId: user.id,
role: Role.MENTOR,
effectiveStartDate: new Date(),
assignedBy: adminClerkId,
assignedByEmail: adminEmail,
reason: "Promoted to mentor based on expertise",
adminNotes: "Subject matter expert in mathematics",
},
});

Database Schema

User Model

model User {
id String @id @default(cuid())
clerkId String @unique // Clerk user ID
email String @unique
firstName String?
lastName String?
displayName String?
avatar String?
bio String?
dateOfBirth DateTime?
phoneNumber String?
address String?
city String?
country String?
timezone String?
language String @default("en")

// User status and profile completion
status UserStatus @default(ACTIVE)
emailVerified Boolean @default(false)
profileComplete Boolean @default(false)
profileSkipped Boolean @default(false)
profileCompletionPercentage Int @default(0)

// Effective date management
effectiveStartDate DateTime @default(now())
effectiveEndDate DateTime?

createdAt DateTime @default(now())
updatedAt DateTime @updatedAt

// Relationships
userRoles UserRole[]
profile Profile?
learnerProfile LearnerProfile?
mentorApplications MentorApplication[]
notifications Notification[]
progress UserProgress[]
notes UserNote[]
subjectEnrollments SubjectEnrollment[]
}

Role Assignment Model

model UserRole {
id String @id @default(cuid())
userId String
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
role Role

// Effective date management
effectiveStartDate DateTime @default(now())
effectiveEndDate DateTime? // NULL means role is still active

// Assignment metadata
assignedBy String? // Clerk user ID of admin who assigned the role
assignedByEmail String? // Email of admin for display
reason String? // Reason for assignment/removal
adminNotes String? // Admin notes

// Status
isActive Boolean @default(true)

createdAt DateTime @default(now())
updatedAt DateTime @updatedAt

@@unique([userId, role, effectiveStartDate])
@@index([userId])
@@index([role])
@@index([effectiveStartDate])
@@index([effectiveEndDate])
}

API Endpoints

User Management

MethodEndpointDescriptionAuth RequiredRoles
GET/usersList all users with paginationYesAdmin
GET/users/[id]Get user by IDYesAdmin
PUT/users/[id]Update user profileYesAdmin
DELETE/users/[id]Delete user (soft delete)YesAdmin
GET/users/searchSearch users by name/emailYesAdmin

Role Management

MethodEndpointDescriptionAuth RequiredRoles
GET/users/[id]/rolesGet user rolesYesAdmin
POST/users/[id]/rolesAssign role to userYesAdmin
PUT/users/[id]/roles/[roleId]Update role assignmentYesAdmin
DELETE/users/[id]/roles/[roleId]Remove role from userYesAdmin
GET/roles/assignmentsGet all role assignmentsYesAdmin

Profile Management

MethodEndpointDescriptionAuth RequiredRoles
GET/profileGet current user profileYesAll
PUT/profileUpdate current user profileYesAll
POST/profile/completeMark profile as completeYesAll
POST/profile/skipSkip profile completionYesAll

User Interface Components

Admin User Management

User List Component

// Features:
- Paginated user list
- Search by name/email
- Filter by role and status
- Bulk actions
- Export functionality
- Real-time updates

User Edit Modal

// Features:
- Edit user profile information
- Role assignment interface
- Status management
- Effective date controls
- Audit trail display

Learner Profile Management

Onboarding Flow

// Features:
- Multi-step form (4 steps)
- Progress tracking
- Validation at each step
- Save and continue later
- Completion percentage
- Skip functionality

Profile Dashboard

// Features:
- Profile completion status
- Learning progress overview
- Enrolled subjects
- Recent activity
- Settings and preferences

Security Features

Access Control

Role-based Access Control (RBAC)

  • Server-side Validation: All role checks performed on the server
  • JWT Token Integration: Role information embedded in tokens
  • Middleware Protection: API endpoints protected with role guards
  • Client-side Hooks: React hooks for role-based UI rendering

Permission Matrix

ActionLEARNERMENTORADMIN
View own profile
Edit own profile
View other users
Edit other users
Assign roles
Create content
Manage subjects✅ (assigned)
System configuration

Data Protection

Personal Data Handling

  • GDPR Compliance: User data handling follows GDPR guidelines
  • Data Retention: Configurable data retention policies
  • Data Export: Users can export their data
  • Data Deletion: Soft delete with recovery options

Audit Trail

  • Role Changes: Complete history of role assignments
  • Profile Updates: Track all profile modifications
  • Login History: Monitor user access patterns
  • Admin Actions: Log all administrative actions

Performance Optimizations

Database Optimization

Indexing Strategy

-- User table indexes
CREATE INDEX idx_users_clerk_id ON users("clerkId");
CREATE INDEX idx_users_email ON users(email);
CREATE INDEX idx_users_status ON users(status);
CREATE INDEX idx_users_created_at ON users("createdAt");

-- User roles indexes
CREATE INDEX idx_user_roles_user_id ON user_roles("userId");
CREATE INDEX idx_user_roles_role ON user_roles(role);
CREATE INDEX idx_user_roles_effective_start ON user_roles("effectiveStartDate");
CREATE INDEX idx_user_roles_effective_end ON user_roles("effectiveEndDate");

Query Optimization

  • Selective Fields: Use select to fetch only needed data
  • Pagination: Implement cursor-based pagination for large datasets
  • Caching: Use TanStack Query for client-side caching
  • Connection Pooling: Optimize database connections

Client-side Optimization

State Management

  • Jotai Atoms: Lightweight state management
  • Optimistic Updates: Immediate UI feedback
  • Background Sync: Sync data in background
  • Error Boundaries: Graceful error handling

Monitoring and Analytics

User Metrics

Registration Analytics

  • Daily/Weekly/Monthly registrations
  • Registration source tracking
  • Profile completion rates
  • Role distribution

Activity Monitoring

  • User engagement metrics
  • Login frequency
  • Feature usage statistics
  • Performance monitoring

Admin Dashboard

User Statistics

// Key metrics displayed:
- Total users
- Active users
- New registrations (period)
- Profile completion rate
- Role distribution
- Pending applications

User Management Tools

// Admin tools:
- Bulk user operations
- Role assignment interface
- User search and filtering
- Export user data
- System health monitoring

Integration Points

Clerk.js Integration

User Synchronization

// Automatic sync on user events
export async function syncUserFromClerk(clerkUser: ClerkUser) {
const user = await prisma.user.upsert({
where: { clerkId: clerkUser.id },
update: {
email: clerkUser.emailAddresses[0].emailAddress,
firstName: clerkUser.firstName,
lastName: clerkUser.lastName,
},
create: {
clerkId: clerkUser.id,
email: clerkUser.emailAddresses[0].emailAddress,
firstName: clerkUser.firstName,
lastName: clerkUser.lastName,
userRoles: {
create: {
role: Role.LEARNER,
effectiveStartDate: new Date(),
},
},
},
});

return user;
}

Email Notifications

  • Welcome emails for new users
  • Role assignment notifications
  • Profile completion reminders
  • Account status changes

Best Practices

User Experience

Profile Completion

  • Progressive disclosure: Show fields gradually
  • Smart defaults: Pre-fill information when possible
  • Validation feedback: Clear error messages
  • Save progress: Allow users to save and continue later

Role Management

  • Clear permissions: Users understand their capabilities
  • Effective dates: Time-bound role assignments
  • Audit trail: Transparent role changes
  • Notification system: Keep users informed

Security

Access Control

  • Principle of least privilege: Users get minimum required access
  • Regular audits: Review role assignments periodically
  • Secure defaults: Safe default configurations
  • Input validation: Validate all user inputs

Troubleshooting

Common Issues

Profile Completion Problems

  • Validation errors: Check Zod schema validation
  • Form state: Ensure proper form state management
  • Database constraints: Verify field requirements

Role Assignment Issues

  • Permission errors: Check role guard middleware
  • Effective dates: Verify date logic
  • Database sync: Ensure proper user synchronization

Debug Tools

Development Tools

// Debug user roles
console.log('User roles:', user.roles);
console.log('Effective dates:', user.userRoles);

// Debug permissions
const hasPermission = await checkUserPermission(userId, action);
console.log('Permission check:', hasPermission);

Next Steps