#### __1. Role-Based Security Architecture__
All checks were successful
Build And Push Image / docker (push) Successful in 2m58s
All checks were successful
Build And Push Image / docker (push) Successful in 2m58s
- Replaces group-based tiers with proper Keycloak realm roles - `monaco-user`, `monaco-board`, `monaco-admin` roles - Backward compatibility with existing group system #### __2. Advanced User Management__ - Comprehensive user profile synchronization - Membership data stored in Keycloak user attributes - Bidirectional sync between NocoDB and Keycloak #### __3. Session Security & Monitoring__ - Real-time session tracking and management - Administrative session control capabilities - Enhanced security analytics foundation #### __4. Email Workflow System__ - Multiple email types: DUES_REMINDER, MEMBERSHIP_RENEWAL, WELCOME, VERIFICATION - Customizable email parameters and lifespans - Advanced email template support #### __5. Seamless Migration Path__ - All existing functionality continues to work - New users automatically get realm roles - Gradual migration from groups to roles - Zero breaking changes ### 🔧 __What You Can Do Now__ #### __For New Users:__ - Public registrations automatically assign `monaco-user` role - Portal account creation syncs member data to Keycloak attributes - Enhanced email verification and welcome workflows #### __For Administrators:__ - Session management and monitoring capabilities - Advanced user profile management with member data sync - Comprehensive role assignment and management - Enhanced email communication workflows #### __For Developers:__ - Use `hasRole('monaco-admin')` for role-based checks - Access `getAllRoles()` for debugging and analytics - Enhanced `useAuth()` composable with backward compatibility - Comprehensive TypeScript support throughout ### 🛡️ __Security & Reliability__ - __Backward Compatibility__: Existing users continue to work seamlessly - __Enhanced Security__: Proper realm role-based authorization - __Error Handling__: Comprehensive error handling and fallbacks - __Type Safety__: Full TypeScript support throughout the system
This commit is contained in:
@@ -6,6 +6,15 @@ import type { NocoDBSettings } from '~/utils/types';
|
||||
|
||||
interface AdminConfiguration {
|
||||
nocodb: NocoDBSettings;
|
||||
recaptcha?: {
|
||||
siteKey: string;
|
||||
secretKey: string; // Will be encrypted
|
||||
};
|
||||
registration?: {
|
||||
membershipFee: number;
|
||||
iban: string;
|
||||
accountHolder: string;
|
||||
};
|
||||
lastUpdated: string;
|
||||
updatedBy: string;
|
||||
}
|
||||
@@ -177,6 +186,9 @@ export async function loadAdminConfig(): Promise<AdminConfiguration | null> {
|
||||
if (config.nocodb.apiKey) {
|
||||
config.nocodb.apiKey = decryptSensitiveData(config.nocodb.apiKey);
|
||||
}
|
||||
if (config.recaptcha?.secretKey) {
|
||||
config.recaptcha.secretKey = decryptSensitiveData(config.recaptcha.secretKey);
|
||||
}
|
||||
|
||||
console.log('[admin-config] Configuration loaded from file');
|
||||
configCache = config;
|
||||
@@ -295,6 +307,108 @@ export async function getCurrentConfig(): Promise<NocoDBSettings> {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Save reCAPTCHA configuration
|
||||
*/
|
||||
export async function saveRecaptchaConfig(config: { siteKey: string; secretKey: string }, updatedBy: string): Promise<void> {
|
||||
try {
|
||||
await ensureConfigDir();
|
||||
await createBackup();
|
||||
|
||||
const currentConfig = configCache || await loadAdminConfig() || {
|
||||
nocodb: { url: '', apiKey: '', baseId: '', tables: {} },
|
||||
lastUpdated: new Date().toISOString(),
|
||||
updatedBy: 'system'
|
||||
};
|
||||
|
||||
const updatedConfig: AdminConfiguration = {
|
||||
...currentConfig,
|
||||
recaptcha: {
|
||||
siteKey: config.siteKey,
|
||||
secretKey: encryptSensitiveData(config.secretKey)
|
||||
},
|
||||
lastUpdated: new Date().toISOString(),
|
||||
updatedBy
|
||||
};
|
||||
|
||||
const configJson = JSON.stringify(updatedConfig, null, 2);
|
||||
await writeFile(CONFIG_FILE, configJson, 'utf-8');
|
||||
|
||||
// Update cache with unencrypted data
|
||||
configCache = {
|
||||
...updatedConfig,
|
||||
recaptcha: {
|
||||
siteKey: config.siteKey,
|
||||
secretKey: config.secretKey
|
||||
}
|
||||
};
|
||||
|
||||
console.log('[admin-config] reCAPTCHA configuration saved');
|
||||
await logConfigChange('RECAPTCHA_CONFIG_SAVED', updatedBy, { siteKey: config.siteKey });
|
||||
|
||||
} catch (error) {
|
||||
console.error('[admin-config] Failed to save reCAPTCHA configuration:', error);
|
||||
await logConfigChange('RECAPTCHA_CONFIG_SAVE_FAILED', updatedBy, { error: error instanceof Error ? error.message : String(error) });
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Save registration configuration
|
||||
*/
|
||||
export async function saveRegistrationConfig(config: { membershipFee: number; iban: string; accountHolder: string }, updatedBy: string): Promise<void> {
|
||||
try {
|
||||
await ensureConfigDir();
|
||||
await createBackup();
|
||||
|
||||
const currentConfig = configCache || await loadAdminConfig() || {
|
||||
nocodb: { url: '', apiKey: '', baseId: '', tables: {} },
|
||||
lastUpdated: new Date().toISOString(),
|
||||
updatedBy: 'system'
|
||||
};
|
||||
|
||||
const updatedConfig: AdminConfiguration = {
|
||||
...currentConfig,
|
||||
registration: config,
|
||||
lastUpdated: new Date().toISOString(),
|
||||
updatedBy
|
||||
};
|
||||
|
||||
const configJson = JSON.stringify(updatedConfig, null, 2);
|
||||
await writeFile(CONFIG_FILE, configJson, 'utf-8');
|
||||
|
||||
configCache = updatedConfig;
|
||||
|
||||
console.log('[admin-config] Registration configuration saved');
|
||||
await logConfigChange('REGISTRATION_CONFIG_SAVED', updatedBy, { membershipFee: config.membershipFee });
|
||||
|
||||
} catch (error) {
|
||||
console.error('[admin-config] Failed to save registration configuration:', error);
|
||||
await logConfigChange('REGISTRATION_CONFIG_SAVE_FAILED', updatedBy, { error: error instanceof Error ? error.message : String(error) });
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get reCAPTCHA configuration
|
||||
*/
|
||||
export function getRecaptchaConfig(): { siteKey: string; secretKey: string } {
|
||||
const config = configCache?.recaptcha || { siteKey: '', secretKey: '' };
|
||||
return config;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get registration configuration
|
||||
*/
|
||||
export function getRegistrationConfig(): { membershipFee: number; iban: string; accountHolder: string } {
|
||||
const config = configCache?.registration || {
|
||||
membershipFee: 50,
|
||||
iban: '',
|
||||
accountHolder: ''
|
||||
};
|
||||
return config;
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize configuration system on server startup
|
||||
*/
|
||||
|
||||
@@ -1,4 +1,12 @@
|
||||
import type { KeycloakAdminConfig } from '~/utils/types';
|
||||
import type {
|
||||
KeycloakAdminConfig,
|
||||
KeycloakUserRepresentation,
|
||||
KeycloakRoleRepresentation,
|
||||
KeycloakGroupRepresentation,
|
||||
UserSessionRepresentation,
|
||||
EmailWorkflowData,
|
||||
MembershipProfileData
|
||||
} from '~/utils/types';
|
||||
|
||||
export class KeycloakAdminClient {
|
||||
private config: KeycloakAdminConfig;
|
||||
@@ -36,12 +44,13 @@ export class KeycloakAdminClient {
|
||||
/**
|
||||
* Find a user by email address
|
||||
*/
|
||||
async findUserByEmail(email: string, adminToken: string): Promise<any[]> {
|
||||
async findUserByEmail(email: string, adminToken?: string): Promise<any[]> {
|
||||
const token = adminToken || await this.getAdminToken();
|
||||
const adminBaseUrl = this.config.issuer.replace('/realms/', '/admin/realms/');
|
||||
|
||||
const response = await fetch(`${adminBaseUrl}/users?email=${encodeURIComponent(email)}&exact=true`, {
|
||||
headers: {
|
||||
'Authorization': `Bearer ${adminToken}`,
|
||||
'Authorization': `Bearer ${token}`,
|
||||
'User-Agent': 'MonacoUSA-Portal/1.0'
|
||||
}
|
||||
});
|
||||
@@ -54,6 +63,675 @@ export class KeycloakAdminClient {
|
||||
return response.json();
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new user with temporary password and email verification
|
||||
*/
|
||||
async createUserWithRegistration(userData: {
|
||||
email: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
username?: string;
|
||||
}): Promise<string> {
|
||||
const adminToken = await this.getAdminToken();
|
||||
const adminBaseUrl = this.config.issuer.replace('/realms/', '/admin/realms/');
|
||||
|
||||
// Check if user already exists
|
||||
const existingUsers = await this.findUserByEmail(userData.email, adminToken);
|
||||
if (existingUsers.length > 0) {
|
||||
throw new Error('User with this email already exists');
|
||||
}
|
||||
|
||||
const response = await fetch(`${adminBaseUrl}/users`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Authorization': `Bearer ${adminToken}`,
|
||||
'Content-Type': 'application/json',
|
||||
'User-Agent': 'MonacoUSA-Portal/1.0'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
email: userData.email,
|
||||
username: userData.username || userData.email,
|
||||
firstName: userData.firstName,
|
||||
lastName: userData.lastName,
|
||||
enabled: true,
|
||||
emailVerified: false,
|
||||
groups: ['/users'], // Default to 'user' tier group
|
||||
attributes: {
|
||||
tier: ['user']
|
||||
},
|
||||
requiredActions: ['VERIFY_EMAIL', 'UPDATE_PASSWORD']
|
||||
})
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text().catch(() => 'Unknown error');
|
||||
throw new Error(`Failed to create user: ${response.status} - ${errorText}`);
|
||||
}
|
||||
|
||||
// Extract user ID from Location header
|
||||
const locationHeader = response.headers.get('location');
|
||||
if (!locationHeader) {
|
||||
throw new Error('User created but failed to get user ID');
|
||||
}
|
||||
|
||||
const userId = locationHeader.split('/').pop();
|
||||
if (!userId) {
|
||||
throw new Error('Failed to extract user ID from response');
|
||||
}
|
||||
|
||||
console.log(`[keycloak-admin] Created user ${userData.email} with ID: ${userId}`);
|
||||
return userId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a user by ID
|
||||
*/
|
||||
async deleteUser(userId: string): Promise<void> {
|
||||
const adminToken = await this.getAdminToken();
|
||||
const adminBaseUrl = this.config.issuer.replace('/realms/', '/admin/realms/');
|
||||
|
||||
const response = await fetch(`${adminBaseUrl}/users/${userId}`, {
|
||||
method: 'DELETE',
|
||||
headers: {
|
||||
'Authorization': `Bearer ${adminToken}`,
|
||||
'User-Agent': 'MonacoUSA-Portal/1.0'
|
||||
}
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text().catch(() => 'Unknown error');
|
||||
throw new Error(`Failed to delete user: ${response.status} - ${errorText}`);
|
||||
}
|
||||
|
||||
console.log(`[keycloak-admin] Deleted user with ID: ${userId}`);
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// ROLE MANAGEMENT METHODS
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* Create a new realm role
|
||||
*/
|
||||
async createRealmRole(roleName: string, description: string): Promise<void> {
|
||||
const adminToken = await this.getAdminToken();
|
||||
const adminBaseUrl = this.config.issuer.replace('/realms/', '/admin/realms/');
|
||||
|
||||
const response = await fetch(`${adminBaseUrl}/roles`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Authorization': `Bearer ${adminToken}`,
|
||||
'Content-Type': 'application/json',
|
||||
'User-Agent': 'MonacoUSA-Portal/1.0'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
name: roleName,
|
||||
description: description,
|
||||
composite: false,
|
||||
clientRole: false
|
||||
})
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text().catch(() => 'Unknown error');
|
||||
throw new Error(`Failed to create realm role: ${response.status} - ${errorText}`);
|
||||
}
|
||||
|
||||
console.log(`[keycloak-admin] Created realm role: ${roleName}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a realm role by name
|
||||
*/
|
||||
async getRealmRole(roleName: string, adminToken?: string): Promise<KeycloakRoleRepresentation> {
|
||||
const token = adminToken || await this.getAdminToken();
|
||||
const adminBaseUrl = this.config.issuer.replace('/realms/', '/admin/realms/');
|
||||
|
||||
const response = await fetch(`${adminBaseUrl}/roles/${roleName}`, {
|
||||
headers: {
|
||||
'Authorization': `Bearer ${token}`,
|
||||
'User-Agent': 'MonacoUSA-Portal/1.0'
|
||||
}
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text().catch(() => 'Unknown error');
|
||||
throw new Error(`Failed to get realm role: ${response.status} - ${errorText}`);
|
||||
}
|
||||
|
||||
return response.json();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all realm roles
|
||||
*/
|
||||
async getAllRealmRoles(adminToken?: string): Promise<KeycloakRoleRepresentation[]> {
|
||||
const token = adminToken || await this.getAdminToken();
|
||||
const adminBaseUrl = this.config.issuer.replace('/realms/', '/admin/realms/');
|
||||
|
||||
const response = await fetch(`${adminBaseUrl}/roles`, {
|
||||
headers: {
|
||||
'Authorization': `Bearer ${token}`,
|
||||
'User-Agent': 'MonacoUSA-Portal/1.0'
|
||||
}
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text().catch(() => 'Unknown error');
|
||||
throw new Error(`Failed to get realm roles: ${response.status} - ${errorText}`);
|
||||
}
|
||||
|
||||
return response.json();
|
||||
}
|
||||
|
||||
/**
|
||||
* Assign a realm role to a user
|
||||
*/
|
||||
async assignRealmRoleToUser(userId: string, roleName: string): Promise<void> {
|
||||
const adminToken = await this.getAdminToken();
|
||||
const adminBaseUrl = this.config.issuer.replace('/realms/', '/admin/realms/');
|
||||
|
||||
// First get the role
|
||||
const role = await this.getRealmRole(roleName, adminToken);
|
||||
|
||||
// Then assign it to user
|
||||
const response = await fetch(`${adminBaseUrl}/users/${userId}/role-mappings/realm`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Authorization': `Bearer ${adminToken}`,
|
||||
'Content-Type': 'application/json',
|
||||
'User-Agent': 'MonacoUSA-Portal/1.0'
|
||||
},
|
||||
body: JSON.stringify([role])
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text().catch(() => 'Unknown error');
|
||||
throw new Error(`Failed to assign role to user: ${response.status} - ${errorText}`);
|
||||
}
|
||||
|
||||
console.log(`[keycloak-admin] Assigned role ${roleName} to user ${userId}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a realm role from a user
|
||||
*/
|
||||
async removeRealmRoleFromUser(userId: string, roleName: string): Promise<void> {
|
||||
const adminToken = await this.getAdminToken();
|
||||
const adminBaseUrl = this.config.issuer.replace('/realms/', '/admin/realms/');
|
||||
|
||||
// First get the role
|
||||
const role = await this.getRealmRole(roleName, adminToken);
|
||||
|
||||
// Then remove it from user
|
||||
const response = await fetch(`${adminBaseUrl}/users/${userId}/role-mappings/realm`, {
|
||||
method: 'DELETE',
|
||||
headers: {
|
||||
'Authorization': `Bearer ${adminToken}`,
|
||||
'Content-Type': 'application/json',
|
||||
'User-Agent': 'MonacoUSA-Portal/1.0'
|
||||
},
|
||||
body: JSON.stringify([role])
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text().catch(() => 'Unknown error');
|
||||
throw new Error(`Failed to remove role from user: ${response.status} - ${errorText}`);
|
||||
}
|
||||
|
||||
console.log(`[keycloak-admin] Removed role ${roleName} from user ${userId}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get user's realm role mappings
|
||||
*/
|
||||
async getUserRealmRoles(userId: string, adminToken?: string): Promise<KeycloakRoleRepresentation[]> {
|
||||
const token = adminToken || await this.getAdminToken();
|
||||
const adminBaseUrl = this.config.issuer.replace('/realms/', '/admin/realms/');
|
||||
|
||||
const response = await fetch(`${adminBaseUrl}/users/${userId}/role-mappings/realm`, {
|
||||
headers: {
|
||||
'Authorization': `Bearer ${token}`,
|
||||
'User-Agent': 'MonacoUSA-Portal/1.0'
|
||||
}
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text().catch(() => 'Unknown error');
|
||||
throw new Error(`Failed to get user roles: ${response.status} - ${errorText}`);
|
||||
}
|
||||
|
||||
return response.json();
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// USER PROFILE MANAGEMENT METHODS
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* Get user by ID with full profile information
|
||||
*/
|
||||
async getUserById(userId: string, adminToken?: string): Promise<KeycloakUserRepresentation> {
|
||||
const token = adminToken || await this.getAdminToken();
|
||||
const adminBaseUrl = this.config.issuer.replace('/realms/', '/admin/realms/');
|
||||
|
||||
const response = await fetch(`${adminBaseUrl}/users/${userId}`, {
|
||||
headers: {
|
||||
'Authorization': `Bearer ${token}`,
|
||||
'User-Agent': 'MonacoUSA-Portal/1.0'
|
||||
}
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text().catch(() => 'Unknown error');
|
||||
throw new Error(`Failed to get user: ${response.status} - ${errorText}`);
|
||||
}
|
||||
|
||||
return response.json();
|
||||
}
|
||||
|
||||
/**
|
||||
* Update user profile with membership data synchronization
|
||||
*/
|
||||
async updateUserProfile(userId: string, profileData: {
|
||||
firstName?: string;
|
||||
lastName?: string;
|
||||
email?: string;
|
||||
enabled?: boolean;
|
||||
emailVerified?: boolean;
|
||||
attributes?: {
|
||||
membershipStatus?: string;
|
||||
duesStatus?: string;
|
||||
memberSince?: string;
|
||||
nationality?: string;
|
||||
phone?: string;
|
||||
address?: string;
|
||||
registrationDate?: string;
|
||||
paymentDueDate?: string;
|
||||
lastLoginDate?: string;
|
||||
membershipTier?: string;
|
||||
nocodbMemberId?: string;
|
||||
};
|
||||
}): Promise<void> {
|
||||
const adminToken = await this.getAdminToken();
|
||||
const adminBaseUrl = this.config.issuer.replace('/realms/', '/admin/realms/');
|
||||
|
||||
// Build user representation
|
||||
const userUpdate: any = {};
|
||||
if (profileData.firstName !== undefined) userUpdate.firstName = profileData.firstName;
|
||||
if (profileData.lastName !== undefined) userUpdate.lastName = profileData.lastName;
|
||||
if (profileData.email !== undefined) userUpdate.email = profileData.email;
|
||||
if (profileData.enabled !== undefined) userUpdate.enabled = profileData.enabled;
|
||||
if (profileData.emailVerified !== undefined) userUpdate.emailVerified = profileData.emailVerified;
|
||||
|
||||
// Handle custom attributes
|
||||
if (profileData.attributes) {
|
||||
userUpdate.attributes = {};
|
||||
Object.entries(profileData.attributes).forEach(([key, value]) => {
|
||||
if (value !== undefined && value !== null) {
|
||||
userUpdate.attributes[key] = [value]; // Keycloak expects arrays for attributes
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const response = await fetch(`${adminBaseUrl}/users/${userId}`, {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
'Authorization': `Bearer ${adminToken}`,
|
||||
'Content-Type': 'application/json',
|
||||
'User-Agent': 'MonacoUSA-Portal/1.0'
|
||||
},
|
||||
body: JSON.stringify(userUpdate)
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text().catch(() => 'Unknown error');
|
||||
throw new Error(`Failed to update user profile: ${response.status} - ${errorText}`);
|
||||
}
|
||||
|
||||
console.log(`[keycloak-admin] Updated profile for user ${userId}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create user with role-based registration (enhanced version)
|
||||
*/
|
||||
async createUserWithRoleRegistration(userData: {
|
||||
email: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
username?: string;
|
||||
membershipTier?: 'user' | 'board' | 'admin';
|
||||
membershipData?: MembershipProfileData;
|
||||
}): Promise<string> {
|
||||
const adminToken = await this.getAdminToken();
|
||||
const adminBaseUrl = this.config.issuer.replace('/realms/', '/admin/realms/');
|
||||
|
||||
// Check if user already exists
|
||||
const existingUsers = await this.findUserByEmail(userData.email, adminToken);
|
||||
if (existingUsers.length > 0) {
|
||||
throw new Error('User with this email already exists');
|
||||
}
|
||||
|
||||
// Build user attributes
|
||||
const attributes: Record<string, string[]> = {
|
||||
membershipTier: [userData.membershipTier || 'user'],
|
||||
registrationDate: [new Date().toISOString()]
|
||||
};
|
||||
|
||||
if (userData.membershipData) {
|
||||
Object.entries(userData.membershipData).forEach(([key, value]) => {
|
||||
if (value !== undefined && value !== null) {
|
||||
attributes[key] = [String(value)];
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const response = await fetch(`${adminBaseUrl}/users`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Authorization': `Bearer ${adminToken}`,
|
||||
'Content-Type': 'application/json',
|
||||
'User-Agent': 'MonacoUSA-Portal/1.0'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
email: userData.email,
|
||||
username: userData.username || userData.email,
|
||||
firstName: userData.firstName,
|
||||
lastName: userData.lastName,
|
||||
enabled: true,
|
||||
emailVerified: false,
|
||||
attributes,
|
||||
requiredActions: ['VERIFY_EMAIL', 'UPDATE_PASSWORD']
|
||||
})
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text().catch(() => 'Unknown error');
|
||||
throw new Error(`Failed to create user: ${response.status} - ${errorText}`);
|
||||
}
|
||||
|
||||
// Extract user ID from Location header
|
||||
const locationHeader = response.headers.get('location');
|
||||
if (!locationHeader) {
|
||||
throw new Error('User created but failed to get user ID');
|
||||
}
|
||||
|
||||
const userId = locationHeader.split('/').pop();
|
||||
if (!userId) {
|
||||
throw new Error('Failed to extract user ID from response');
|
||||
}
|
||||
|
||||
// Assign appropriate realm role
|
||||
const roleName = `monaco-${userData.membershipTier || 'user'}`;
|
||||
try {
|
||||
await this.assignRealmRoleToUser(userId, roleName);
|
||||
} catch (error) {
|
||||
console.warn(`[keycloak-admin] Failed to assign role ${roleName} to user ${userId}:`, error);
|
||||
// Don't fail the entire operation if role assignment fails
|
||||
}
|
||||
|
||||
console.log(`[keycloak-admin] Created user ${userData.email} with ID: ${userId} and role: ${roleName}`);
|
||||
return userId;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// SESSION MANAGEMENT METHODS
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* Get all active sessions for a user
|
||||
*/
|
||||
async getUserSessions(userId: string): Promise<UserSessionRepresentation[]> {
|
||||
const adminToken = await this.getAdminToken();
|
||||
const adminBaseUrl = this.config.issuer.replace('/realms/', '/admin/realms/');
|
||||
|
||||
const response = await fetch(`${adminBaseUrl}/users/${userId}/sessions`, {
|
||||
headers: {
|
||||
'Authorization': `Bearer ${adminToken}`,
|
||||
'Content-Type': 'application/json',
|
||||
'User-Agent': 'MonacoUSA-Portal/1.0'
|
||||
}
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text().catch(() => 'Unknown error');
|
||||
throw new Error(`Failed to get user sessions: ${response.status} - ${errorText}`);
|
||||
}
|
||||
|
||||
return response.json();
|
||||
}
|
||||
|
||||
/**
|
||||
* Logout a specific user session
|
||||
*/
|
||||
async logoutUserSession(sessionId: string): Promise<void> {
|
||||
const adminToken = await this.getAdminToken();
|
||||
const adminBaseUrl = this.config.issuer.replace('/realms/', '/admin/realms/');
|
||||
|
||||
const response = await fetch(`${adminBaseUrl}/sessions/${sessionId}`, {
|
||||
method: 'DELETE',
|
||||
headers: {
|
||||
'Authorization': `Bearer ${adminToken}`,
|
||||
'User-Agent': 'MonacoUSA-Portal/1.0'
|
||||
}
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text().catch(() => 'Unknown error');
|
||||
throw new Error(`Failed to logout session: ${response.status} - ${errorText}`);
|
||||
}
|
||||
|
||||
console.log(`[keycloak-admin] Logged out session: ${sessionId}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Logout all sessions for a user
|
||||
*/
|
||||
async logoutAllUserSessions(userId: string): Promise<void> {
|
||||
const adminToken = await this.getAdminToken();
|
||||
const adminBaseUrl = this.config.issuer.replace('/realms/', '/admin/realms/');
|
||||
|
||||
const response = await fetch(`${adminBaseUrl}/users/${userId}/logout`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Authorization': `Bearer ${adminToken}`,
|
||||
'User-Agent': 'MonacoUSA-Portal/1.0'
|
||||
}
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text().catch(() => 'Unknown error');
|
||||
throw new Error(`Failed to logout all user sessions: ${response.status} - ${errorText}`);
|
||||
}
|
||||
|
||||
console.log(`[keycloak-admin] Logged out all sessions for user: ${userId}`);
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// GROUP MANAGEMENT METHODS
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* Create a new group
|
||||
*/
|
||||
async createGroup(name: string, path: string, parentPath?: string): Promise<string> {
|
||||
const adminToken = await this.getAdminToken();
|
||||
const adminBaseUrl = this.config.issuer.replace('/realms/', '/admin/realms/');
|
||||
|
||||
const groupData = {
|
||||
name: name,
|
||||
path: path
|
||||
};
|
||||
|
||||
let url = `${adminBaseUrl}/groups`;
|
||||
if (parentPath) {
|
||||
// Find parent group ID first
|
||||
const parentId = await this.getGroupByPath(parentPath);
|
||||
url = `${adminBaseUrl}/groups/${parentId}/children`;
|
||||
}
|
||||
|
||||
const response = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Authorization': `Bearer ${adminToken}`,
|
||||
'Content-Type': 'application/json',
|
||||
'User-Agent': 'MonacoUSA-Portal/1.0'
|
||||
},
|
||||
body: JSON.stringify(groupData)
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text().catch(() => 'Unknown error');
|
||||
throw new Error(`Failed to create group: ${response.status} - ${errorText}`);
|
||||
}
|
||||
|
||||
const locationHeader = response.headers.get('location');
|
||||
const groupId = locationHeader?.split('/').pop() || '';
|
||||
|
||||
console.log(`[keycloak-admin] Created group: ${name} with ID: ${groupId}`);
|
||||
return groupId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get group by path
|
||||
*/
|
||||
async getGroupByPath(path: string): Promise<string> {
|
||||
const adminToken = await this.getAdminToken();
|
||||
const adminBaseUrl = this.config.issuer.replace('/realms/', '/admin/realms/');
|
||||
|
||||
const response = await fetch(`${adminBaseUrl}/groups?search=${encodeURIComponent(path)}`, {
|
||||
headers: {
|
||||
'Authorization': `Bearer ${adminToken}`,
|
||||
'User-Agent': 'MonacoUSA-Portal/1.0'
|
||||
}
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text().catch(() => 'Unknown error');
|
||||
throw new Error(`Failed to find group: ${response.status} - ${errorText}`);
|
||||
}
|
||||
|
||||
const groups: KeycloakGroupRepresentation[] = await response.json();
|
||||
const group = groups.find(g => g.path === path);
|
||||
|
||||
if (!group?.id) {
|
||||
throw new Error(`Group not found: ${path}`);
|
||||
}
|
||||
|
||||
return group.id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Assign user to group
|
||||
*/
|
||||
async assignUserToGroup(userId: string, groupId: string): Promise<void> {
|
||||
const adminToken = await this.getAdminToken();
|
||||
const adminBaseUrl = this.config.issuer.replace('/realms/', '/admin/realms/');
|
||||
|
||||
const response = await fetch(`${adminBaseUrl}/users/${userId}/groups/${groupId}`, {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
'Authorization': `Bearer ${adminToken}`,
|
||||
'User-Agent': 'MonacoUSA-Portal/1.0'
|
||||
}
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text().catch(() => 'Unknown error');
|
||||
throw new Error(`Failed to assign user to group: ${response.status} - ${errorText}`);
|
||||
}
|
||||
|
||||
console.log(`[keycloak-admin] Assigned user ${userId} to group ${groupId}`);
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// ADVANCED EMAIL WORKFLOWS
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* Send custom email workflows
|
||||
*/
|
||||
async sendCustomEmail(userId: string, emailData: EmailWorkflowData): Promise<void> {
|
||||
const adminToken = await this.getAdminToken();
|
||||
const adminBaseUrl = this.config.issuer.replace('/realms/', '/admin/realms/');
|
||||
|
||||
const emailUrl = new URL(`${adminBaseUrl}/users/${userId}/execute-actions-email`);
|
||||
|
||||
// Configure email based on type
|
||||
switch (emailData.emailType) {
|
||||
case 'DUES_REMINDER':
|
||||
emailUrl.searchParams.set('lifespan', emailData.lifespan?.toString() || '259200'); // 3 days
|
||||
if (emailData.customData?.dueAmount) {
|
||||
emailUrl.searchParams.set('dueAmount', emailData.customData.dueAmount);
|
||||
}
|
||||
break;
|
||||
case 'MEMBERSHIP_RENEWAL':
|
||||
emailUrl.searchParams.set('lifespan', emailData.lifespan?.toString() || '604800'); // 1 week
|
||||
if (emailData.customData?.renewalDate) {
|
||||
emailUrl.searchParams.set('renewalDate', emailData.customData.renewalDate);
|
||||
}
|
||||
break;
|
||||
case 'WELCOME':
|
||||
emailUrl.searchParams.set('lifespan', emailData.lifespan?.toString() || '43200'); // 12 hours
|
||||
break;
|
||||
case 'VERIFICATION':
|
||||
emailUrl.searchParams.set('lifespan', emailData.lifespan?.toString() || '86400'); // 24 hours
|
||||
break;
|
||||
}
|
||||
|
||||
if (emailData.redirectUri) {
|
||||
emailUrl.searchParams.set('redirect_uri', emailData.redirectUri);
|
||||
}
|
||||
|
||||
emailUrl.searchParams.set('client_id', this.config.clientId);
|
||||
|
||||
const response = await fetch(emailUrl.toString(), {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
'Authorization': `Bearer ${adminToken}`,
|
||||
'Content-Type': 'application/json',
|
||||
'User-Agent': 'MonacoUSA-Portal/1.0'
|
||||
},
|
||||
body: JSON.stringify([emailData.emailType])
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text().catch(() => 'Unknown error');
|
||||
throw new Error(`Failed to send ${emailData.emailType} email: ${response.status} - ${errorText}`);
|
||||
}
|
||||
|
||||
console.log(`[keycloak-admin] Sent ${emailData.emailType} email to user ${userId}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Send enhanced verification email
|
||||
*/
|
||||
async sendVerificationEmail(userId: string, redirectUri?: string): Promise<void> {
|
||||
const adminToken = await this.getAdminToken();
|
||||
const adminBaseUrl = this.config.issuer.replace('/realms/', '/admin/realms/');
|
||||
|
||||
const emailUrl = new URL(`${adminBaseUrl}/users/${userId}/send-verify-email`);
|
||||
if (redirectUri) {
|
||||
emailUrl.searchParams.set('redirect_uri', redirectUri);
|
||||
}
|
||||
emailUrl.searchParams.set('client_id', this.config.clientId);
|
||||
|
||||
const response = await fetch(emailUrl.toString(), {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
'Authorization': `Bearer ${adminToken}`,
|
||||
'User-Agent': 'MonacoUSA-Portal/1.0'
|
||||
}
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text().catch(() => 'Unknown error');
|
||||
throw new Error(`Failed to send verification email: ${response.status} - ${errorText}`);
|
||||
}
|
||||
|
||||
console.log(`[keycloak-admin] Sent verification email to user ${userId}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Send password reset email to a user
|
||||
*/
|
||||
|
||||
Reference in New Issue
Block a user