feat: Implement a structured API service layer for authentication and user management, replacing the old API utility.
This commit is contained in:
@@ -1,7 +1,7 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useState } from 'react';
|
||||
import { api, type User } from '@/lib/api';
|
||||
import { usersService, User } from '@/services';
|
||||
import Link from 'next/link';
|
||||
|
||||
export default function DashboardPage() {
|
||||
@@ -21,7 +21,7 @@ export default function DashboardPage() {
|
||||
const fetchDashboardData = async () => {
|
||||
setIsLoading(true);
|
||||
try {
|
||||
const response = await api.getUsers(1, 100);
|
||||
const response = await usersService.getUsers({ page: 1, limit: 100 });
|
||||
const users = response.users || [];
|
||||
setStats({
|
||||
totalUsers: response.total || 0,
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { api, type User } from '@/lib/api';
|
||||
import { usersService, User, getErrorMessage } from '@/services';
|
||||
|
||||
export default function UsersPage() {
|
||||
const router = useRouter();
|
||||
@@ -21,12 +21,13 @@ export default function UsersPage() {
|
||||
setIsLoading(true);
|
||||
setError('');
|
||||
try {
|
||||
const response = await api.getUsers(currentPage, limit);
|
||||
const response = await usersService.getUsers({ page: currentPage, limit });
|
||||
setUsers(response.users || []);
|
||||
setTotalUsers(response.total || 0);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to fetch users');
|
||||
if (err instanceof Error && err.message.includes('Unauthorized')) {
|
||||
const errorMessage = getErrorMessage(err);
|
||||
setError(errorMessage);
|
||||
if (errorMessage.includes('Unauthorized')) {
|
||||
router.push('/login');
|
||||
}
|
||||
} finally {
|
||||
|
||||
@@ -2,53 +2,38 @@
|
||||
|
||||
import React, { createContext, useContext, useState, useEffect, useCallback } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { api, type LoginResponse } from '@/lib/api';
|
||||
|
||||
interface User {
|
||||
id: string;
|
||||
email: string;
|
||||
role: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
avatar: string | null;
|
||||
}
|
||||
import { authService, AuthUser, getErrorMessage } from '@/services';
|
||||
|
||||
interface AuthContextType {
|
||||
user: User | null;
|
||||
user: AuthUser | null;
|
||||
isLoading: boolean;
|
||||
isAuthenticated: boolean;
|
||||
login: (email: string, password: string) => Promise<void>;
|
||||
logout: () => Promise<void>;
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
const AuthContext = createContext<AuthContextType | undefined>(undefined);
|
||||
|
||||
export function AuthProvider({ children }: { children: React.ReactNode }) {
|
||||
const [user, setUser] = useState<User | null>(null);
|
||||
const [user, setUser] = useState<AuthUser | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const router = useRouter();
|
||||
|
||||
const checkAuth = useCallback(() => {
|
||||
try {
|
||||
const token = localStorage.getItem('accessToken');
|
||||
const storedUser = localStorage.getItem('user');
|
||||
const storedUser = authService.getStoredUser();
|
||||
|
||||
if (token && storedUser) {
|
||||
const parsedUser = JSON.parse(storedUser);
|
||||
if (parsedUser.role === 'ADMIN') {
|
||||
setUser(parsedUser);
|
||||
} else {
|
||||
// Not admin, clear storage
|
||||
localStorage.removeItem('accessToken');
|
||||
localStorage.removeItem('refreshToken');
|
||||
localStorage.removeItem('user');
|
||||
}
|
||||
if (storedUser && storedUser.role === 'ADMIN') {
|
||||
setUser(storedUser);
|
||||
} else if (storedUser) {
|
||||
// Not admin, clear storage
|
||||
authService.clearAuth();
|
||||
}
|
||||
} catch {
|
||||
// Invalid stored data
|
||||
localStorage.removeItem('accessToken');
|
||||
localStorage.removeItem('refreshToken');
|
||||
localStorage.removeItem('user');
|
||||
authService.clearAuth();
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
@@ -59,14 +44,21 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
|
||||
}, [checkAuth]);
|
||||
|
||||
const login = async (email: string, password: string) => {
|
||||
const response: LoginResponse = await api.login(email, password);
|
||||
setUser(response.user);
|
||||
router.push('/dashboard');
|
||||
setError(null);
|
||||
try {
|
||||
const response = await authService.login({ email, password });
|
||||
setUser(response.user);
|
||||
router.push('/dashboard');
|
||||
} catch (err) {
|
||||
const errorMessage = getErrorMessage(err);
|
||||
setError(errorMessage);
|
||||
throw new Error(errorMessage);
|
||||
}
|
||||
};
|
||||
|
||||
const logout = async () => {
|
||||
try {
|
||||
await api.logout();
|
||||
await authService.logout();
|
||||
} finally {
|
||||
setUser(null);
|
||||
router.push('/login');
|
||||
@@ -81,6 +73,7 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
|
||||
isAuthenticated: !!user,
|
||||
login,
|
||||
logout,
|
||||
error,
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
|
||||
147
src/lib/api.ts
147
src/lib/api.ts
@@ -1,147 +0,0 @@
|
||||
const API_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3001/api/v1';
|
||||
|
||||
interface ApiResponse<T> {
|
||||
success: boolean;
|
||||
data: T;
|
||||
message?: string;
|
||||
}
|
||||
|
||||
interface LoginResponse {
|
||||
user: {
|
||||
id: string;
|
||||
email: string;
|
||||
role: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
avatar: string | null;
|
||||
};
|
||||
accessToken: string;
|
||||
refreshToken: string;
|
||||
}
|
||||
|
||||
interface User {
|
||||
id: string;
|
||||
email: string;
|
||||
role: string;
|
||||
status: string;
|
||||
emailVerified: boolean;
|
||||
authProvider: string;
|
||||
createdAt: string;
|
||||
lastLoginAt: string | null;
|
||||
profile: {
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
avatar: string | null;
|
||||
phone: string | null;
|
||||
city: string | null;
|
||||
state: string | null;
|
||||
country: string | null;
|
||||
} | null;
|
||||
}
|
||||
|
||||
class ApiClient {
|
||||
private baseUrl: string;
|
||||
|
||||
constructor() {
|
||||
this.baseUrl = API_URL;
|
||||
}
|
||||
|
||||
private getToken(): string | null {
|
||||
if (typeof window === 'undefined') return null;
|
||||
return localStorage.getItem('accessToken');
|
||||
}
|
||||
|
||||
private async request<T>(
|
||||
endpoint: string,
|
||||
options: RequestInit = {}
|
||||
): Promise<ApiResponse<T>> {
|
||||
const token = this.getToken();
|
||||
|
||||
const headers: HeadersInit = {
|
||||
'Content-Type': 'application/json',
|
||||
...(token && { Authorization: `Bearer ${token}` }),
|
||||
...options.headers,
|
||||
};
|
||||
|
||||
const response = await fetch(`${this.baseUrl}${endpoint}`, {
|
||||
...options,
|
||||
headers,
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(data.message || 'An error occurred');
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
async login(email: string, password: string): Promise<LoginResponse> {
|
||||
const response = await this.request<LoginResponse>('/auth/login', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ email, password }),
|
||||
});
|
||||
|
||||
// Check if user is ADMIN
|
||||
if (response.data.user.role !== 'ADMIN') {
|
||||
throw new Error('Access denied. Admin privileges required.');
|
||||
}
|
||||
|
||||
// Store tokens
|
||||
localStorage.setItem('accessToken', response.data.accessToken);
|
||||
localStorage.setItem('refreshToken', response.data.refreshToken);
|
||||
localStorage.setItem('user', JSON.stringify(response.data.user));
|
||||
|
||||
return response.data;
|
||||
}
|
||||
|
||||
async logout(): Promise<void> {
|
||||
try {
|
||||
await this.request('/auth/logout', { method: 'POST' });
|
||||
} finally {
|
||||
localStorage.removeItem('accessToken');
|
||||
localStorage.removeItem('refreshToken');
|
||||
localStorage.removeItem('user');
|
||||
}
|
||||
}
|
||||
|
||||
async getCurrentUser(): Promise<User> {
|
||||
const response = await this.request<User>('/auth/me');
|
||||
return response.data;
|
||||
}
|
||||
|
||||
async getUsers(page = 1, limit = 10): Promise<{ users: User[]; total: number; page: number; limit: number }> {
|
||||
const response = await this.request<{ users: User[]; total: number; page: number; limit: number }>(
|
||||
`/users?page=${page}&limit=${limit}`
|
||||
);
|
||||
return response.data;
|
||||
}
|
||||
|
||||
async refreshToken(): Promise<{ accessToken: string; refreshToken: string }> {
|
||||
const refreshToken = localStorage.getItem('refreshToken');
|
||||
if (!refreshToken) {
|
||||
throw new Error('No refresh token available');
|
||||
}
|
||||
|
||||
const response = await fetch(`${this.baseUrl}/auth/refresh`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ refreshToken }),
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(data.message || 'Failed to refresh token');
|
||||
}
|
||||
|
||||
localStorage.setItem('accessToken', data.data.accessToken);
|
||||
localStorage.setItem('refreshToken', data.data.refreshToken);
|
||||
|
||||
return data.data;
|
||||
}
|
||||
}
|
||||
|
||||
export const api = new ApiClient();
|
||||
export type { User, LoginResponse };
|
||||
120
src/services/api.ts
Normal file
120
src/services/api.ts
Normal file
@@ -0,0 +1,120 @@
|
||||
import axios, { AxiosError, AxiosInstance, InternalAxiosRequestConfig } from 'axios';
|
||||
|
||||
// API Response types
|
||||
export interface ApiResponse<T = unknown> {
|
||||
success: boolean;
|
||||
data: T;
|
||||
statusCode?: number;
|
||||
timestamp?: string;
|
||||
message?: string;
|
||||
}
|
||||
|
||||
export interface ApiErrorResponse {
|
||||
success: false;
|
||||
statusCode: number;
|
||||
timestamp: string;
|
||||
path: string;
|
||||
method: string;
|
||||
error: string;
|
||||
message: string | string[];
|
||||
errors?: Array<{ field: string; errors: string[] }>;
|
||||
}
|
||||
|
||||
// Create axios instance
|
||||
const api: AxiosInstance = axios.create({
|
||||
baseURL: process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3001/api/v1',
|
||||
timeout: 30000,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
});
|
||||
|
||||
// Request interceptor
|
||||
api.interceptors.request.use(
|
||||
(config: InternalAxiosRequestConfig) => {
|
||||
// Add auth token if available
|
||||
if (typeof window !== 'undefined') {
|
||||
const token = localStorage.getItem('accessToken');
|
||||
if (token && config.headers) {
|
||||
config.headers.Authorization = `Bearer ${token}`;
|
||||
}
|
||||
}
|
||||
return config;
|
||||
},
|
||||
(error: AxiosError) => {
|
||||
return Promise.reject(error);
|
||||
}
|
||||
);
|
||||
|
||||
// Response interceptor
|
||||
api.interceptors.response.use(
|
||||
(response) => {
|
||||
return response;
|
||||
},
|
||||
async (error: AxiosError<ApiErrorResponse>) => {
|
||||
const originalRequest = error.config as InternalAxiosRequestConfig & { _retry?: boolean };
|
||||
|
||||
// Handle 401 Unauthorized - try to refresh token
|
||||
if (error.response?.status === 401 && !originalRequest._retry) {
|
||||
originalRequest._retry = true;
|
||||
|
||||
try {
|
||||
const refreshToken = localStorage.getItem('refreshToken');
|
||||
if (refreshToken) {
|
||||
const response = await axios.post(
|
||||
`${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3001/api/v1'}/auth/refresh`,
|
||||
{ refreshToken }
|
||||
);
|
||||
|
||||
const { accessToken, refreshToken: newRefreshToken } = response.data.data;
|
||||
localStorage.setItem('accessToken', accessToken);
|
||||
localStorage.setItem('refreshToken', newRefreshToken);
|
||||
|
||||
// Retry original request with new token
|
||||
if (originalRequest.headers) {
|
||||
originalRequest.headers.Authorization = `Bearer ${accessToken}`;
|
||||
}
|
||||
return api(originalRequest);
|
||||
}
|
||||
} catch (refreshError) {
|
||||
// Refresh failed, clear storage and redirect to login
|
||||
localStorage.removeItem('accessToken');
|
||||
localStorage.removeItem('refreshToken');
|
||||
localStorage.removeItem('user');
|
||||
|
||||
if (typeof window !== 'undefined') {
|
||||
window.location.href = '/login';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return Promise.reject(error);
|
||||
}
|
||||
);
|
||||
|
||||
// Helper to extract error message
|
||||
export function getErrorMessage(error: unknown): string {
|
||||
if (error instanceof AxiosError) {
|
||||
const apiError = error.response?.data as ApiErrorResponse;
|
||||
if (apiError?.message) {
|
||||
return Array.isArray(apiError.message)
|
||||
? apiError.message.join(', ')
|
||||
: apiError.message;
|
||||
}
|
||||
}
|
||||
if (error instanceof Error) {
|
||||
return error.message;
|
||||
}
|
||||
return 'An unexpected error occurred';
|
||||
}
|
||||
|
||||
// Helper to extract field errors
|
||||
export function getFieldErrors(error: unknown): Array<{ field: string; errors: string[] }> {
|
||||
if (error instanceof AxiosError) {
|
||||
const apiError = error.response?.data as ApiErrorResponse;
|
||||
return apiError?.errors || [];
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
export default api;
|
||||
115
src/services/auth.service.ts
Normal file
115
src/services/auth.service.ts
Normal file
@@ -0,0 +1,115 @@
|
||||
import api, { ApiResponse } from './api';
|
||||
|
||||
// Types
|
||||
export interface LoginRequest {
|
||||
email: string;
|
||||
password: string;
|
||||
}
|
||||
|
||||
export interface AuthUser {
|
||||
id: string;
|
||||
email: string;
|
||||
role: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
avatar: string | null;
|
||||
}
|
||||
|
||||
export interface AuthResponse {
|
||||
user: AuthUser;
|
||||
accessToken: string;
|
||||
refreshToken: string;
|
||||
}
|
||||
|
||||
export interface MessageResponse {
|
||||
message: string;
|
||||
}
|
||||
|
||||
// Auth Service
|
||||
class AuthService {
|
||||
private basePath = '/auth';
|
||||
|
||||
async login(data: LoginRequest): Promise<AuthResponse> {
|
||||
const response = await api.post<ApiResponse<AuthResponse>>(
|
||||
`${this.basePath}/login`,
|
||||
data
|
||||
);
|
||||
|
||||
const authData = response.data.data;
|
||||
|
||||
// Check if user is ADMIN
|
||||
if (authData.user.role !== 'ADMIN') {
|
||||
throw new Error('Access denied. Admin privileges required.');
|
||||
}
|
||||
|
||||
// Store tokens and user
|
||||
localStorage.setItem('accessToken', authData.accessToken);
|
||||
localStorage.setItem('refreshToken', authData.refreshToken);
|
||||
localStorage.setItem('user', JSON.stringify(authData.user));
|
||||
|
||||
return authData;
|
||||
}
|
||||
|
||||
async logout(): Promise<void> {
|
||||
try {
|
||||
await api.post<ApiResponse<MessageResponse>>(`${this.basePath}/logout`);
|
||||
} finally {
|
||||
localStorage.removeItem('accessToken');
|
||||
localStorage.removeItem('refreshToken');
|
||||
localStorage.removeItem('user');
|
||||
}
|
||||
}
|
||||
|
||||
async getCurrentUser(): Promise<AuthUser> {
|
||||
const response = await api.get<ApiResponse<AuthUser>>(`${this.basePath}/me`);
|
||||
return response.data.data;
|
||||
}
|
||||
|
||||
async refreshToken(): Promise<{ accessToken: string; refreshToken: string }> {
|
||||
const refreshToken = localStorage.getItem('refreshToken');
|
||||
if (!refreshToken) {
|
||||
throw new Error('No refresh token available');
|
||||
}
|
||||
|
||||
const response = await api.post<ApiResponse<{ accessToken: string; refreshToken: string }>>(
|
||||
`${this.basePath}/refresh`,
|
||||
{ refreshToken }
|
||||
);
|
||||
|
||||
const tokens = response.data.data;
|
||||
localStorage.setItem('accessToken', tokens.accessToken);
|
||||
localStorage.setItem('refreshToken', tokens.refreshToken);
|
||||
|
||||
return tokens;
|
||||
}
|
||||
|
||||
// Get stored user from localStorage
|
||||
getStoredUser(): AuthUser | null {
|
||||
if (typeof window === 'undefined') return null;
|
||||
|
||||
const storedUser = localStorage.getItem('user');
|
||||
if (storedUser) {
|
||||
try {
|
||||
return JSON.parse(storedUser);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// Check if user is authenticated
|
||||
isAuthenticated(): boolean {
|
||||
if (typeof window === 'undefined') return false;
|
||||
return !!localStorage.getItem('accessToken');
|
||||
}
|
||||
|
||||
// Clear auth data
|
||||
clearAuth(): void {
|
||||
localStorage.removeItem('accessToken');
|
||||
localStorage.removeItem('refreshToken');
|
||||
localStorage.removeItem('user');
|
||||
}
|
||||
}
|
||||
|
||||
export const authService = new AuthService();
|
||||
21
src/services/index.ts
Normal file
21
src/services/index.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
// API Client
|
||||
export { default as api } from './api';
|
||||
export type { ApiResponse, ApiErrorResponse } from './api';
|
||||
export { getErrorMessage, getFieldErrors } from './api';
|
||||
|
||||
// Auth Service
|
||||
export { authService } from './auth.service';
|
||||
export type {
|
||||
LoginRequest,
|
||||
AuthUser,
|
||||
AuthResponse,
|
||||
MessageResponse,
|
||||
} from './auth.service';
|
||||
|
||||
// Users Service
|
||||
export { usersService } from './users.service';
|
||||
export type {
|
||||
User,
|
||||
UsersListResponse,
|
||||
UserFilters,
|
||||
} from './users.service';
|
||||
79
src/services/users.service.ts
Normal file
79
src/services/users.service.ts
Normal file
@@ -0,0 +1,79 @@
|
||||
import api, { ApiResponse } from './api';
|
||||
|
||||
// Types
|
||||
export interface User {
|
||||
id: string;
|
||||
email: string;
|
||||
role: string;
|
||||
status: string;
|
||||
emailVerified: boolean;
|
||||
authProvider: string;
|
||||
createdAt: string;
|
||||
lastLoginAt: string | null;
|
||||
profile: {
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
avatar: string | null;
|
||||
phone: string | null;
|
||||
city: string | null;
|
||||
state: string | null;
|
||||
country: string | null;
|
||||
} | null;
|
||||
}
|
||||
|
||||
export interface UsersListResponse {
|
||||
users: User[];
|
||||
total: number;
|
||||
page: number;
|
||||
limit: number;
|
||||
}
|
||||
|
||||
export interface UserFilters {
|
||||
page?: number;
|
||||
limit?: number;
|
||||
role?: string;
|
||||
status?: string;
|
||||
search?: string;
|
||||
}
|
||||
|
||||
// Users Service
|
||||
class UsersService {
|
||||
private basePath = '/users';
|
||||
|
||||
async getUsers(filters: UserFilters = {}): Promise<UsersListResponse> {
|
||||
const params = new URLSearchParams();
|
||||
|
||||
if (filters.page) params.append('page', filters.page.toString());
|
||||
if (filters.limit) params.append('limit', filters.limit.toString());
|
||||
if (filters.role) params.append('role', filters.role);
|
||||
if (filters.status) params.append('status', filters.status);
|
||||
if (filters.search) params.append('search', filters.search);
|
||||
|
||||
const queryString = params.toString();
|
||||
const url = queryString ? `${this.basePath}?${queryString}` : this.basePath;
|
||||
|
||||
const response = await api.get<ApiResponse<UsersListResponse>>(url);
|
||||
return response.data.data;
|
||||
}
|
||||
|
||||
async getUserById(id: string): Promise<User> {
|
||||
const response = await api.get<ApiResponse<User>>(`${this.basePath}/${id}`);
|
||||
return response.data.data;
|
||||
}
|
||||
|
||||
async updateUser(id: string, data: Partial<User>): Promise<User> {
|
||||
const response = await api.patch<ApiResponse<User>>(`${this.basePath}/${id}`, data);
|
||||
return response.data.data;
|
||||
}
|
||||
|
||||
async deleteUser(id: string): Promise<void> {
|
||||
await api.delete(`${this.basePath}/${id}`);
|
||||
}
|
||||
|
||||
async updateUserStatus(id: string, status: string): Promise<User> {
|
||||
const response = await api.patch<ApiResponse<User>>(`${this.basePath}/${id}/status`, { status });
|
||||
return response.data.data;
|
||||
}
|
||||
}
|
||||
|
||||
export const usersService = new UsersService();
|
||||
Reference in New Issue
Block a user