feat: Implement admin user management page with create/delete functionality, add a super-admin-only sidebar link, and expose isSuperAdmin in AuthContext.

This commit is contained in:
pradeepkumar
2026-03-20 17:04:59 +05:30
parent 82ed2ef987
commit 237f9166f4
3 changed files with 240 additions and 1 deletions

View File

@@ -0,0 +1,211 @@
'use client';
import { useState, useEffect } from 'react';
import { useAuth } from '@/context/AuthContext';
import { useRouter } from 'next/navigation';
import api, { ApiResponse, getErrorMessage } from '@/services/api';
interface AdminUser {
id: string;
email: string;
role: string;
status: string;
createdAt: string;
lastLoginAt: string | null;
}
export default function AdminUsersPage() {
const { user, isSuperAdmin } = useAuth();
const router = useRouter();
const [admins, setAdmins] = useState<AdminUser[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState('');
const [showCreate, setShowCreate] = useState(false);
const [newEmail, setNewEmail] = useState('');
const [newPassword, setNewPassword] = useState('');
const [creating, setCreating] = useState(false);
const [deletingId, setDeletingId] = useState<string | null>(null);
// Redirect non-super-admins
useEffect(() => {
if (!isSuperAdmin) {
router.push('/dashboard');
}
}, [isSuperAdmin, router]);
const fetchAdmins = async () => {
try {
setLoading(true);
const response = await api.get<ApiResponse<AdminUser[]>>('/users/admin/admins');
setAdmins(response.data.data);
} catch (err) {
setError(getErrorMessage(err));
} finally {
setLoading(false);
}
};
useEffect(() => { if (isSuperAdmin) fetchAdmins(); }, [isSuperAdmin]);
const handleCreate = async (e: React.FormEvent) => {
e.preventDefault();
if (!newEmail.trim() || !newPassword.trim()) return;
setCreating(true);
setError('');
try {
await api.put('/users/admin/admins', { email: newEmail.trim(), password: newPassword });
setShowCreate(false);
setNewEmail('');
setNewPassword('');
fetchAdmins();
} catch (err) {
setError(getErrorMessage(err));
} finally {
setCreating(false);
}
};
const handleDelete = async (id: string) => {
if (!confirm('Are you sure you want to delete this admin?')) return;
setDeletingId(id);
try {
await api.delete(`/users/admin/admins/${id}`);
setAdmins(prev => prev.filter(a => a.id !== id));
} catch (err) {
setError(getErrorMessage(err));
} finally {
setDeletingId(null);
}
};
if (!isSuperAdmin) return null;
return (
<div>
<div className="flex items-center justify-between mb-6">
<h1 className="text-2xl font-bold text-gray-900">Admin Users</h1>
<button
onClick={() => setShowCreate(true)}
className="px-4 py-2 bg-[#f5a623] text-white text-sm font-medium rounded-lg hover:bg-[#e09520] transition-colors"
>
+ Create Admin
</button>
</div>
{error && (
<div className="p-3 bg-red-50 border border-red-200 rounded-lg mb-4">
<p className="text-red-700 text-sm">{error}</p>
</div>
)}
{loading ? (
<div className="flex justify-center py-12">
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-[#f5a623]"></div>
</div>
) : (
<div className="bg-white rounded-lg shadow overflow-hidden">
<table className="min-w-full divide-y divide-gray-200">
<thead className="bg-gray-50">
<tr>
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Email</th>
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Role</th>
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Status</th>
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Created</th>
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Actions</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-200">
{admins.map(admin => (
<tr key={admin.id} className="hover:bg-gray-50">
<td className="px-4 py-3 text-sm text-gray-900">{admin.email}</td>
<td className="px-4 py-3">
<span className={`px-2 py-1 text-xs font-semibold rounded-full ${
admin.role === 'SUPER_ADMIN' ? 'bg-purple-100 text-purple-800' : 'bg-blue-100 text-blue-800'
}`}>
{admin.role === 'SUPER_ADMIN' ? 'Super Admin' : 'Admin'}
</span>
</td>
<td className="px-4 py-3">
<span className="px-2 py-1 text-xs font-semibold rounded-full bg-green-100 text-green-800">
{admin.status}
</span>
</td>
<td className="px-4 py-3 text-sm text-gray-500">
{new Date(admin.createdAt).toLocaleDateString()}
</td>
<td className="px-4 py-3">
{admin.role === 'ADMIN' && admin.id !== user?.id ? (
<button
onClick={() => handleDelete(admin.id)}
disabled={deletingId === admin.id}
className="text-sm text-red-600 hover:text-red-800 disabled:opacity-50"
>
{deletingId === admin.id ? 'Deleting...' : 'Delete'}
</button>
) : (
<span className="text-sm text-gray-400"></span>
)}
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
{/* Create Admin Modal */}
{showCreate && (
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
<div className="bg-white rounded-lg shadow-xl max-w-md w-full mx-4">
<div className="px-6 py-4 border-b border-gray-200">
<h3 className="text-lg font-semibold text-gray-900">Create Admin User</h3>
</div>
<form onSubmit={handleCreate}>
<div className="px-6 py-4 space-y-4">
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Email</label>
<input
type="email"
value={newEmail}
onChange={e => setNewEmail(e.target.value)}
required
className="w-full px-3 py-2 border border-gray-300 rounded-lg text-gray-900 bg-white placeholder:text-gray-500"
placeholder="admin@example.com"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Password</label>
<input
type="password"
value={newPassword}
onChange={e => setNewPassword(e.target.value)}
required
minLength={8}
className="w-full px-3 py-2 border border-gray-300 rounded-lg text-gray-900 bg-white placeholder:text-gray-500"
placeholder="Min 8 characters"
/>
</div>
</div>
<div className="px-6 py-4 border-t border-gray-200 flex justify-end gap-3">
<button
type="button"
onClick={() => { setShowCreate(false); setNewEmail(''); setNewPassword(''); }}
className="px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 text-sm"
>
Cancel
</button>
<button
type="submit"
disabled={creating}
className="px-4 py-2 bg-[#f5a623] text-white rounded-lg hover:bg-[#e09520] text-sm disabled:opacity-50"
>
{creating ? 'Creating...' : 'Create Admin'}
</button>
</div>
</form>
</div>
</div>
)}
</div>
);
}

View File

@@ -5,6 +5,7 @@ import { usePathname } from 'next/navigation';
import { useState, useEffect, useCallback } from 'react';
import { supportChatService } from '@/services/support-chat.service';
import { adminSocketService } from '@/services/socket.service';
import { useAuth } from '@/context/AuthContext';
const menuItems = [
{
@@ -137,6 +138,7 @@ const menuItems = [
export default function Sidebar() {
const pathname = usePathname();
const { isSuperAdmin } = useAuth();
const [unreadCount, setUnreadCount] = useState(0);
const fetchUnreadCount = useCallback(async () => {
@@ -229,6 +231,23 @@ export default function Sidebar() {
</li>
);
})}
{isSuperAdmin && (
<li>
<Link
href="/dashboard/admin-users"
className={`flex items-center px-4 py-3 rounded-lg transition-all duration-200 ${
pathname === '/dashboard/admin-users'
? 'bg-[#f5a623] text-white shadow-sm'
: 'text-[#c4d9d4] hover:bg-[#003a57] hover:text-white'
}`}
>
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
</svg>
<span className="ml-3 font-medium font-serif text-sm">Admin Users</span>
</Link>
</li>
)}
</ul>
</nav>
</aside>

View File

@@ -8,6 +8,7 @@ interface AuthContextType {
user: AuthUser | null;
isLoading: boolean;
isAuthenticated: boolean;
isSuperAdmin: boolean;
login: (email: string, password: string) => Promise<void>;
logout: () => Promise<void>;
error: string | null;
@@ -25,7 +26,7 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
try {
const storedUser = authService.getStoredUser();
if (storedUser && storedUser.role === 'ADMIN') {
if (storedUser && (storedUser.role === 'ADMIN' || storedUser.role === 'SUPER_ADMIN')) {
setUser(storedUser);
} else if (storedUser) {
// Not admin, clear storage
@@ -47,6 +48,13 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
setError(null);
try {
const response = await authService.login({ email, password });
// Block non-admin users from admin panel
if (response.user.role !== 'ADMIN' && response.user.role !== 'SUPER_ADMIN') {
authService.clearAuth();
throw new Error('Access denied. Only admin users can login here.');
}
setUser(response.user);
router.push('/dashboard');
} catch (err) {
@@ -71,6 +79,7 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
user,
isLoading,
isAuthenticated: !!user,
isSuperAdmin: user?.role === 'SUPER_ADMIN',
login,
logout,
error,