fix: Connect admin dashboard to real backend API with authentication

- Fixed CORS to allow pfadmin.noru1.ro and localhost:3335
- Fixed API client to handle nested token response structure (data.tokens.accessToken)
- Added deviceInfo requirement to login endpoint
- Fixed API endpoint paths to use /api/v1 prefix consistently
- Updated admin user password to 'admin123' for demo@parentflowapp.com
- Fixed Grid deprecation warnings by replacing with CSS Grid
- Added automatic redirect to /login on 401 unauthorized
- Enhanced user management service to include familyCount, childrenCount, deviceCount
- Backend now queries family_members, children, and device_registry tables for counts

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Andrei
2025-10-07 15:44:59 +00:00
parent 5ddb8222bf
commit 3c934c300a
6 changed files with 257 additions and 162 deletions

View File

@@ -44,12 +44,19 @@ interface User {
id: string;
email: string;
name: string;
phone?: string;
photoUrl?: string;
globalRole: 'parent' | 'guest' | 'admin';
isAdmin: boolean;
adminPermissions: string[];
emailVerified: boolean;
createdAt: string;
lastActiveAt: string;
isActive: boolean;
familyCount: number;
childrenCount: number;
deviceCount: number;
updatedAt: string;
lastActiveAt?: string;
isActive?: boolean;
familyCount?: number;
childrenCount?: number;
deviceCount?: number;
}
export default function UsersPage() {
@@ -70,45 +77,16 @@ export default function UsersPage() {
try {
setLoading(true);
const response = await apiClient.get('/admin/users');
setUsers(response.data);
} catch (error) {
// Backend returns paginated response: { users: [], total, page, limit, totalPages }
setUsers(response.users || []);
} catch (error: any) {
console.error('Failed to fetch users:', error);
// Using mock data for development
setUsers([
{
id: '1',
email: 'john.doe@example.com',
name: 'John Doe',
createdAt: '2024-01-15T10:00:00Z',
lastActiveAt: '2024-10-06T08:30:00Z',
isActive: true,
familyCount: 1,
childrenCount: 2,
deviceCount: 3,
},
{
id: '2',
email: 'jane.smith@example.com',
name: 'Jane Smith',
createdAt: '2024-02-20T14:30:00Z',
lastActiveAt: '2024-10-05T18:45:00Z',
isActive: true,
familyCount: 1,
childrenCount: 1,
deviceCount: 2,
},
{
id: '3',
email: 'bob.johnson@example.com',
name: 'Bob Johnson',
createdAt: '2024-03-10T09:15:00Z',
lastActiveAt: '2024-09-30T12:00:00Z',
isActive: false,
familyCount: 1,
childrenCount: 3,
deviceCount: 1,
},
]);
// If unauthorized, redirect to login
if (error?.response?.status === 401) {
window.location.href = '/login';
return;
}
setUsers([]);
} finally {
setLoading(false);
}
@@ -127,7 +105,7 @@ export default function UsersPage() {
const handleToggleUserStatus = async (user: User) => {
try {
await apiClient.patch(`/admin/users/${user.id}`, {
isActive: !user.isActive,
emailVerified: !user.emailVerified,
});
fetchUsers();
} catch (error) {
@@ -174,56 +152,48 @@ export default function UsersPage() {
</Box>
{/* Stats Cards */}
<Grid container spacing={3} sx={{ mb: 4 }}>
<Grid item xs={12} sm={6} md={3}>
<Card>
<CardContent>
<Typography color="text.secondary" gutterBottom>
Total Users
</Typography>
<Typography variant="h3" sx={{ color: 'primary.main' }}>
{users.length}
</Typography>
</CardContent>
</Card>
</Grid>
<Grid item xs={12} sm={6} md={3}>
<Card>
<CardContent>
<Typography color="text.secondary" gutterBottom>
Active Users
</Typography>
<Typography variant="h3" sx={{ color: 'success.main' }}>
{users.filter(u => u.isActive).length}
</Typography>
</CardContent>
</Card>
</Grid>
<Grid item xs={12} sm={6} md={3}>
<Card>
<CardContent>
<Typography color="text.secondary" gutterBottom>
Total Families
</Typography>
<Typography variant="h3" sx={{ color: 'info.main' }}>
{users.reduce((sum, u) => sum + u.familyCount, 0)}
</Typography>
</CardContent>
</Card>
</Grid>
<Grid item xs={12} sm={6} md={3}>
<Card>
<CardContent>
<Typography color="text.secondary" gutterBottom>
Total Children
</Typography>
<Typography variant="h3" sx={{ color: 'secondary.main' }}>
{users.reduce((sum, u) => sum + u.childrenCount, 0)}
</Typography>
</CardContent>
</Card>
</Grid>
</Grid>
<Box sx={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(250px, 1fr))', gap: 3, mb: 4 }}>
<Card>
<CardContent>
<Typography color="text.secondary" gutterBottom>
Total Users
</Typography>
<Typography variant="h3" sx={{ color: 'primary.main' }}>
{users.length}
</Typography>
</CardContent>
</Card>
<Card>
<CardContent>
<Typography color="text.secondary" gutterBottom>
Active Users
</Typography>
<Typography variant="h3" sx={{ color: 'success.main' }}>
{users.filter(u => u.emailVerified).length}
</Typography>
</CardContent>
</Card>
<Card>
<CardContent>
<Typography color="text.secondary" gutterBottom>
Total Families
</Typography>
<Typography variant="h3" sx={{ color: 'info.main' }}>
{users.reduce((sum, u) => sum + (u.familyCount || 0), 0)}
</Typography>
</CardContent>
</Card>
<Card>
<CardContent>
<Typography color="text.secondary" gutterBottom>
Total Children
</Typography>
<Typography variant="h3" sx={{ color: 'secondary.main' }}>
{users.reduce((sum, u) => sum + (u.childrenCount || 0), 0)}
</Typography>
</CardContent>
</Card>
</Box>
{/* Search and Actions */}
<Box sx={{ mb: 3, display: 'flex', gap: 2 }}>
@@ -285,18 +255,18 @@ export default function UsersPage() {
</Box>
</TableCell>
<TableCell>{formatDate(user.createdAt)}</TableCell>
<TableCell>{formatDate(user.lastActiveAt)}</TableCell>
<TableCell>{user.lastActiveAt ? formatDate(user.lastActiveAt) : formatDate(user.updatedAt)}</TableCell>
<TableCell align="center">
<Chip
label={user.isActive ? 'Active' : 'Inactive'}
color={user.isActive ? 'success' : 'default'}
label={user.emailVerified ? 'Active' : 'Inactive'}
color={user.emailVerified ? 'success' : 'default'}
size="small"
icon={user.isActive ? <CheckCircle /> : <Block />}
icon={user.emailVerified ? <CheckCircle /> : <Block />}
/>
</TableCell>
<TableCell align="center">{user.familyCount}</TableCell>
<TableCell align="center">{user.childrenCount}</TableCell>
<TableCell align="center">{user.deviceCount}</TableCell>
<TableCell align="center">{user.familyCount || 0}</TableCell>
<TableCell align="center">{user.childrenCount || 0}</TableCell>
<TableCell align="center">{user.deviceCount || 0}</TableCell>
<TableCell align="right">
<IconButton
size="small"
@@ -315,9 +285,9 @@ export default function UsersPage() {
<IconButton
size="small"
onClick={() => handleToggleUserStatus(user)}
title={user.isActive ? 'Deactivate' : 'Activate'}
title={user.emailVerified ? 'Deactivate' : 'Activate'}
>
{user.isActive ? <Block /> : <CheckCircle />}
{user.emailVerified ? <Block /> : <CheckCircle />}
</IconButton>
<IconButton
size="small"
@@ -356,53 +326,51 @@ export default function UsersPage() {
<DialogTitle>User Details</DialogTitle>
<DialogContent>
{selectedUser && (
<Box sx={{ pt: 2 }}>
<Grid container spacing={2}>
<Grid item xs={6}>
<Typography variant="subtitle2" color="text.secondary">
Name
</Typography>
<Typography variant="body1">{selectedUser.name}</Typography>
</Grid>
<Grid item xs={6}>
<Typography variant="subtitle2" color="text.secondary">
Email
</Typography>
<Typography variant="body1">{selectedUser.email}</Typography>
</Grid>
<Grid item xs={6}>
<Typography variant="subtitle2" color="text.secondary">
User ID
</Typography>
<Typography variant="body1">{selectedUser.id}</Typography>
</Grid>
<Grid item xs={6}>
<Typography variant="subtitle2" color="text.secondary">
Status
</Typography>
<Chip
label={selectedUser.isActive ? 'Active' : 'Inactive'}
color={selectedUser.isActive ? 'success' : 'default'}
size="small"
/>
</Grid>
<Grid item xs={6}>
<Typography variant="subtitle2" color="text.secondary">
Created At
</Typography>
<Typography variant="body1">
{formatDate(selectedUser.createdAt)}
</Typography>
</Grid>
<Grid item xs={6}>
<Typography variant="subtitle2" color="text.secondary">
Last Active
</Typography>
<Typography variant="body1">
{formatDate(selectedUser.lastActiveAt)}
</Typography>
</Grid>
</Grid>
<Box sx={{ pt: 2, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 2 }}>
<Box>
<Typography variant="subtitle2" color="text.secondary">
Name
</Typography>
<Typography variant="body1">{selectedUser.name}</Typography>
</Box>
<Box>
<Typography variant="subtitle2" color="text.secondary">
Email
</Typography>
<Typography variant="body1">{selectedUser.email}</Typography>
</Box>
<Box>
<Typography variant="subtitle2" color="text.secondary">
User ID
</Typography>
<Typography variant="body1">{selectedUser.id}</Typography>
</Box>
<Box>
<Typography variant="subtitle2" color="text.secondary">
Status
</Typography>
<Chip
label={selectedUser.emailVerified ? 'Active' : 'Inactive'}
color={selectedUser.emailVerified ? 'success' : 'default'}
size="small"
/>
</Box>
<Box>
<Typography variant="subtitle2" color="text.secondary">
Created At
</Typography>
<Typography variant="body1">
{formatDate(selectedUser.createdAt)}
</Typography>
</Box>
<Box>
<Typography variant="subtitle2" color="text.secondary">
Last Active
</Typography>
<Typography variant="body1">
{selectedUser.lastActiveAt ? formatDate(selectedUser.lastActiveAt) : formatDate(selectedUser.updatedAt)}
</Typography>
</Box>
</Box>
)}
</DialogContent>
@@ -434,9 +402,9 @@ export default function UsersPage() {
/>
<FormControlLabel
control={
<Switch defaultChecked={selectedUser.isActive} />
<Switch defaultChecked={selectedUser.emailVerified} />
}
label="Active"
label="Email Verified"
/>
</Box>
)}

View File

@@ -35,7 +35,7 @@ class ApiClient {
private async request(method: string, endpoint: string, data?: any, options?: any) {
const config = {
method,
url: `${API_BASE_URL}/api/v1${endpoint}`,
url: `${API_BASE_URL}${endpoint}`,
headers: {
'Content-Type': 'application/json',
...(this.token ? { Authorization: `Bearer ${this.token}` } : {}),
@@ -55,7 +55,7 @@ class ApiClient {
// Handle token refresh
if (error.response?.status === 401 && this.refreshToken) {
try {
const refreshResponse = await axios.post(`${API_BASE_URL}/api/v1/auth/refresh`, {
const refreshResponse = await axios.post(`${API_BASE_URL}/auth/refresh`, {
refreshToken: this.refreshToken,
});
@@ -75,23 +75,73 @@ class ApiClient {
}
}
// Generic HTTP methods
async get(endpoint: string, options?: any) {
return this.request('GET', endpoint, undefined, options);
}
async post(endpoint: string, data?: any, options?: any) {
return this.request('POST', endpoint, data, options);
}
async patch(endpoint: string, data?: any, options?: any) {
return this.request('PATCH', endpoint, data, options);
}
async put(endpoint: string, data?: any, options?: any) {
return this.request('PUT', endpoint, data, options);
}
async delete(endpoint: string, options?: any) {
return this.request('DELETE', endpoint, undefined, options);
}
// Auth endpoints
async login(email: string, password: string) {
const response = await this.request('POST', '/admin/auth/login', { email, password });
this.setTokens(response.accessToken, response.refreshToken);
// Generate device info for admin dashboard
const deviceInfo = {
deviceId: this.getOrCreateDeviceId(),
platform: 'web',
model: 'Admin Dashboard',
osVersion: navigator.userAgent,
};
const response = await this.request('POST', '/auth/login', {
email,
password,
deviceInfo
});
// Extract tokens from nested response structure
const tokens = response.tokens || response.data?.tokens;
if (tokens?.accessToken && tokens?.refreshToken) {
this.setTokens(tokens.accessToken, tokens.refreshToken);
}
return response;
}
private getOrCreateDeviceId(): string {
if (typeof window === 'undefined') return 'server';
let deviceId = localStorage.getItem('admin_device_id');
if (!deviceId) {
deviceId = 'admin_' + Math.random().toString(36).substring(2) + Date.now().toString(36);
localStorage.setItem('admin_device_id', deviceId);
}
return deviceId;
}
async logout() {
try {
await this.request('POST', '/admin/auth/logout');
await this.request('POST', '/auth/logout');
} finally {
this.clearTokens();
}
}
async getCurrentAdmin() {
return this.request('GET', '/admin/auth/me');
return this.request('GET', '/auth/me');
}
// User management endpoints