338 lines
13 KiB
TypeScript
338 lines
13 KiB
TypeScript
import React from 'react';
|
|
import { useForm } from 'react-hook-form';
|
|
import { zodResolver } from '@hookform/resolvers/zod';
|
|
import { z } from 'zod';
|
|
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
|
import { UserPlus, Shield, Hash, Mail, Phone, Lock, Building, CheckCircle2 } from 'lucide-react';
|
|
import { Modal } from '../ui/Modal';
|
|
import { useToast } from '../ui/Toast';
|
|
import { createUser, getSystemRoles, assignUserRole, getTenants } from '../../services/api';
|
|
import { useAuth } from '../../auth/AuthProvider';
|
|
import { useRbac } from '../../auth/rbac';
|
|
import { CreateUserRequest, Role, Tenant } from '../../types';
|
|
|
|
const createUserSchema = z.object({
|
|
tenantId: z.string().min(1, 'Tenant is required'),
|
|
idNumber: z
|
|
.string()
|
|
.min(5, 'Identification Number must be at least 5 characters')
|
|
.max(30, 'Identification Number is too long')
|
|
.regex(/^[a-zA-Z0-9_-]+$/, 'ID Number must be alphanumeric (Hex-encodable)'),
|
|
email: z.string().email('Please enter a valid email address'),
|
|
userName: z.string().optional(),
|
|
phoneNumber: z.string().optional(),
|
|
initialRoleId: z.string().optional(),
|
|
lockoutEnabled: z.boolean().default(false),
|
|
twoFactorEnabled: z.boolean().default(false),
|
|
});
|
|
|
|
type CreateUserFormValues = z.infer<typeof createUserSchema>;
|
|
|
|
interface CreateUserModalProps {
|
|
isOpen: boolean;
|
|
onClose: () => void;
|
|
defaultTenantId?: number | string | null;
|
|
}
|
|
|
|
export const CreateUserModal: React.FC<CreateUserModalProps> = ({
|
|
isOpen,
|
|
onClose,
|
|
defaultTenantId,
|
|
}) => {
|
|
const { tenantId: userTenantId, canManageTenants } = useAuth();
|
|
const { canAdd, canView, isUnrestricted } = useRbac();
|
|
const canCreate = canAdd('settings_users') || canAdd('tenant_self_service') || canAdd('tenant_management') || isUnrestricted;
|
|
const hasTenantSelfHelpAccess = canAdd('tenant_self_service') || canView('tenant_self_service');
|
|
const queryClient = useQueryClient();
|
|
const { success, error: toastError } = useToast();
|
|
|
|
const effectiveDefaultTenant = defaultTenantId
|
|
? String(defaultTenantId)
|
|
: userTenantId
|
|
? String(userTenantId)
|
|
: '1';
|
|
|
|
const {
|
|
register,
|
|
handleSubmit,
|
|
reset,
|
|
watch,
|
|
setValue,
|
|
formState: { errors },
|
|
} = useForm<CreateUserFormValues>({
|
|
resolver: zodResolver(createUserSchema),
|
|
defaultValues: {
|
|
tenantId: effectiveDefaultTenant,
|
|
idNumber: '',
|
|
email: '',
|
|
userName: '',
|
|
phoneNumber: '',
|
|
initialRoleId: '',
|
|
lockoutEnabled: false,
|
|
twoFactorEnabled: false,
|
|
},
|
|
});
|
|
|
|
React.useEffect(() => {
|
|
if (isOpen) {
|
|
reset({
|
|
tenantId: effectiveDefaultTenant,
|
|
idNumber: '',
|
|
email: '',
|
|
userName: '',
|
|
phoneNumber: '',
|
|
initialRoleId: '',
|
|
lockoutEnabled: false,
|
|
twoFactorEnabled: false,
|
|
});
|
|
}
|
|
}, [isOpen, effectiveDefaultTenant, reset]);
|
|
|
|
// System roles for assignment
|
|
const { data: systemRoles = [], isLoading: loadingRoles } = useQuery<Role[]>({
|
|
queryKey: ['system-roles'],
|
|
queryFn: getSystemRoles,
|
|
enabled: isOpen,
|
|
});
|
|
|
|
// Filter out Admin role if user has access to tenant self-help (Requirement 1)
|
|
const assignableRoles = React.useMemo(() => {
|
|
return systemRoles.filter((r) => {
|
|
const isRoleAdmin = r.name.toLowerCase() === 'admin' || r.id === '1';
|
|
if (isRoleAdmin && hasTenantSelfHelpAccess) {
|
|
return false;
|
|
}
|
|
return true;
|
|
});
|
|
}, [systemRoles, hasTenantSelfHelpAccess]);
|
|
|
|
// Tenants list for super-admins
|
|
const { data: tenantsList = [] } = useQuery<Tenant[]>({
|
|
queryKey: ['tenants'],
|
|
queryFn: getTenants,
|
|
enabled: isOpen && canManageTenants,
|
|
});
|
|
|
|
const createUserMutation = useMutation({
|
|
mutationFn: async (values: CreateUserFormValues) => {
|
|
// Security enforcement: Users with tenant self-help access cannot create admin users
|
|
if (values.initialRoleId && hasTenantSelfHelpAccess) {
|
|
const selectedRole = systemRoles.find((r) => r.id === values.initialRoleId);
|
|
if (selectedRole && (selectedRole.name.toLowerCase() === 'admin' || selectedRole.id === '1')) {
|
|
throw new Error('Users who have access to tenant self-help are restricted from creating Admin users.');
|
|
}
|
|
}
|
|
|
|
const payload: CreateUserRequest = {
|
|
email: values.email.trim(),
|
|
userName: values.userName?.trim() || values.email.split('@')[0],
|
|
emailConfirmed: true,
|
|
phoneNumber: values.phoneNumber?.trim() || null,
|
|
phoneNumberConfirmed: false,
|
|
LockoutEnabled: values.lockoutEnabled,
|
|
twoFactorEnabled: values.twoFactorEnabled,
|
|
accessFailedCount: 0,
|
|
};
|
|
|
|
await createUser(values.tenantId, values.idNumber.trim(), payload);
|
|
|
|
// If an initial role was chosen and we have a newly generated user,
|
|
// invalidate query cache to refresh directory
|
|
return values;
|
|
},
|
|
onSuccess: (values) => {
|
|
success('User Created', `User ${values.email} provisioned under Tenant #${values.tenantId}.`);
|
|
queryClient.invalidateQueries({ queryKey: ['users'] });
|
|
queryClient.invalidateQueries({ queryKey: ['users-directory'] });
|
|
onClose();
|
|
},
|
|
onError: (err: any) => {
|
|
toastError('User Creation Failed', err);
|
|
},
|
|
});
|
|
|
|
const onSubmit = (data: CreateUserFormValues) => {
|
|
createUserMutation.mutate(data);
|
|
};
|
|
|
|
return (
|
|
<Modal
|
|
isOpen={isOpen}
|
|
onClose={onClose}
|
|
title="Provision Tenant User"
|
|
subtitle="Creates a new tenant user with Hashids Hex-encoded ID and RBAC capabilities without direct DB intervention."
|
|
>
|
|
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4 text-xs">
|
|
{/* Tenant Scope Selector */}
|
|
<div>
|
|
<label className="block text-slate-300 font-semibold mb-1 flex items-center gap-1.5">
|
|
<Building className="w-3.5 h-3.5 text-blue-400" />
|
|
<span>Tenant Partition Boundary</span>
|
|
</label>
|
|
{canManageTenants && tenantsList.length > 0 ? (
|
|
<select
|
|
{...register('tenantId')}
|
|
className="w-full bg-slate-900 border border-slate-800 rounded-xl px-3 py-2 text-white focus:outline-none focus:border-blue-500"
|
|
>
|
|
{tenantsList.map((t) => (
|
|
<option key={t.id} value={String(t.id)}>
|
|
Tenant #{t.id} — {t.name || 'Enterprise Tenant'}
|
|
</option>
|
|
))}
|
|
</select>
|
|
) : (
|
|
<input
|
|
type="text"
|
|
readOnly
|
|
{...register('tenantId')}
|
|
className="w-full bg-slate-900/60 border border-slate-800 rounded-xl px-3 py-2 text-slate-400 cursor-not-allowed font-mono"
|
|
/>
|
|
)}
|
|
{errors.tenantId && <p className="text-rose-400 text-[11px] mt-1">{errors.tenantId.message}</p>}
|
|
</div>
|
|
|
|
{/* ID Number with Hashids Hex guidance */}
|
|
<div>
|
|
<label className="block text-slate-300 font-semibold mb-1 flex items-center justify-between">
|
|
<span className="flex items-center gap-1.5">
|
|
<Hash className="w-3.5 h-3.5 text-blue-400" />
|
|
<span>National ID / Identification Number</span>
|
|
</span>
|
|
<span className="text-[10px] text-blue-400 font-mono">Hashids Hex Encoded in API</span>
|
|
</label>
|
|
<input
|
|
type="text"
|
|
placeholder="e.g. 9501015800085 or ZA-982341"
|
|
{...register('idNumber')}
|
|
className="w-full bg-slate-900 border border-slate-800 rounded-xl px-3 py-2 text-white placeholder-slate-500 focus:outline-none focus:border-blue-500 font-mono"
|
|
/>
|
|
<p className="text-[11px] text-slate-400 mt-1">
|
|
Standard South African National ID (13 digits) or alphanumeric identifier. The client automatically converts and hashes this via Hashids Hex.
|
|
</p>
|
|
{errors.idNumber && <p className="text-rose-400 text-[11px] mt-1">{errors.idNumber.message}</p>}
|
|
</div>
|
|
|
|
{/* Email & Username */}
|
|
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
|
|
<div>
|
|
<label className="block text-slate-300 font-semibold mb-1 flex items-center gap-1.5">
|
|
<Mail className="w-3.5 h-3.5 text-blue-400" />
|
|
<span>Email Address</span>
|
|
</label>
|
|
<input
|
|
type="email"
|
|
placeholder="user@organisation.gov.za"
|
|
{...register('email')}
|
|
className="w-full bg-slate-900 border border-slate-800 rounded-xl px-3 py-2 text-white placeholder-slate-500 focus:outline-none focus:border-blue-500"
|
|
/>
|
|
{errors.email && <p className="text-rose-400 text-[11px] mt-1">{errors.email.message}</p>}
|
|
</div>
|
|
|
|
<div>
|
|
<label className="block text-slate-300 font-semibold mb-1">
|
|
Username (Optional)
|
|
</label>
|
|
<input
|
|
type="text"
|
|
placeholder="e.g. jsmith"
|
|
{...register('userName')}
|
|
className="w-full bg-slate-900 border border-slate-800 rounded-xl px-3 py-2 text-white placeholder-slate-500 focus:outline-none focus:border-blue-500"
|
|
/>
|
|
</div>
|
|
</div>
|
|
|
|
{/* Phone & Initial Role */}
|
|
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
|
|
<div>
|
|
<label className="block text-slate-300 font-semibold mb-1 flex items-center gap-1.5">
|
|
<Phone className="w-3.5 h-3.5 text-blue-400" />
|
|
<span>Phone Number (Optional)</span>
|
|
</label>
|
|
<input
|
|
type="tel"
|
|
placeholder="+27 82 000 0000"
|
|
{...register('phoneNumber')}
|
|
className="w-full bg-slate-900 border border-slate-800 rounded-xl px-3 py-2 text-white placeholder-slate-500 focus:outline-none focus:border-blue-500"
|
|
/>
|
|
</div>
|
|
|
|
<div>
|
|
<label className="block text-slate-300 font-semibold mb-1 flex items-center gap-1.5">
|
|
<Shield className="w-3.5 h-3.5 text-blue-400" />
|
|
<span>Primary System Role</span>
|
|
</label>
|
|
<select
|
|
{...register('initialRoleId')}
|
|
disabled={loadingRoles}
|
|
className="w-full bg-slate-900 border border-slate-800 rounded-xl px-3 py-2 text-white focus:outline-none focus:border-blue-500 disabled:opacity-50"
|
|
>
|
|
<option value="">Select Initial Role (Optional)</option>
|
|
{assignableRoles.map((r) => (
|
|
<option key={r.id} value={r.id}>
|
|
{r.name}
|
|
</option>
|
|
))}
|
|
</select>
|
|
{hasTenantSelfHelpAccess && (
|
|
<p className="text-[10px] text-amber-400 mt-1">
|
|
Tenant Self-Help Policy: Admin user creation is restricted.
|
|
</p>
|
|
)}
|
|
</div>
|
|
</div>
|
|
|
|
{/* Security Flags */}
|
|
<div className="p-3 bg-slate-900/60 rounded-xl border border-slate-800 space-y-2">
|
|
<div className="text-[11px] font-semibold text-slate-400 uppercase tracking-wider">
|
|
Security & Authentication Flags
|
|
</div>
|
|
<div className="flex items-center gap-6">
|
|
<label className="flex items-center gap-2 cursor-pointer text-slate-300">
|
|
<input
|
|
type="checkbox"
|
|
{...register('lockoutEnabled')}
|
|
className="rounded border-slate-700 text-blue-600 focus:ring-blue-500 w-4 h-4"
|
|
/>
|
|
<span>Enable Account Lockout Protection</span>
|
|
</label>
|
|
|
|
<label className="flex items-center gap-2 cursor-pointer text-slate-300">
|
|
<input
|
|
type="checkbox"
|
|
{...register('twoFactorEnabled')}
|
|
className="rounded border-slate-700 text-blue-600 focus:ring-blue-500 w-4 h-4"
|
|
/>
|
|
<span>Require Two-Factor Auth</span>
|
|
</label>
|
|
</div>
|
|
</div>
|
|
|
|
{!canCreate && (
|
|
<div className="p-3 rounded-xl bg-amber-500/10 border border-amber-500/20 text-amber-300 text-xs flex items-center gap-2">
|
|
<span>User provisioning is restricted by your RBAC claim assignment.</span>
|
|
</div>
|
|
)}
|
|
|
|
{/* Form Actions */}
|
|
<div className="pt-3 border-t border-slate-800 flex justify-end gap-2.5">
|
|
<button
|
|
type="button"
|
|
onClick={onClose}
|
|
className="px-4 py-2 text-xs font-semibold text-slate-400 hover:text-white bg-slate-800 hover:bg-slate-700 rounded-xl transition cursor-pointer"
|
|
>
|
|
Cancel
|
|
</button>
|
|
<button
|
|
type="submit"
|
|
disabled={!canCreate || createUserMutation.isPending}
|
|
className="inline-flex items-center gap-1.5 px-4 py-2 text-xs font-semibold text-white bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-500 hover:to-indigo-500 rounded-xl shadow-md shadow-blue-600/30 transition cursor-pointer disabled:opacity-50"
|
|
>
|
|
<UserPlus className="w-3.5 h-3.5" />
|
|
<span>{createUserMutation.isPending ? 'Provisioning...' : 'Provision User'}</span>
|
|
</button>
|
|
</div>
|
|
</form>
|
|
</Modal>
|
|
);
|
|
};
|