feat: Implement AuthService for user registration with detailed field error handling and updated user roles.

This commit is contained in:
pradeepkumar
2025-12-22 11:53:53 +05:30
parent de32edb7ab
commit 5c6ab92056
6 changed files with 447 additions and 74 deletions

View File

@@ -4,42 +4,50 @@ import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { signIn } from 'next-auth/react';
import Link from 'next/link';
import { authService, AuthService, RegisterRequest } from '@/services';
type UserType = 'user' | 'admin';
type UserType = 'USER' | 'AGENT';
interface ValidationError {
field: string;
errors: string[];
}
export default function SignUpPage() {
const router = useRouter();
const [userType, setUserType] = useState<UserType>('user');
const [name, setName] = useState('');
const [userType, setUserType] = useState<UserType>('USER');
const [firstName, setFirstName] = useState('');
const [lastName, setLastName] = useState('');
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [showPassword, setShowPassword] = useState(false);
const [error, setError] = useState('');
const [fieldErrors, setFieldErrors] = useState<ValidationError[]>([]);
const [loading, setLoading] = useState(false);
const getFieldError = (fieldName: string): string | null => {
const fieldError = fieldErrors.find((e) => e.field === fieldName);
return fieldError ? fieldError.errors[0] : null;
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setLoading(true);
setError('');
setFieldErrors([]);
try {
const response = await fetch('/api/auth/register', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name,
email,
password,
role: userType.toUpperCase(),
}),
});
const registerData: RegisterRequest = {
firstName,
lastName,
email,
password,
role: userType,
};
const data = await response.json();
if (!response.ok) {
throw new Error(data.message || 'Registration failed');
}
await authService.register(registerData);
// Auto login after successful registration
const result = await signIn('credentials', {
email,
password,
@@ -53,7 +61,14 @@ export default function SignUpPage() {
router.refresh();
}
} catch (err) {
setError(err instanceof Error ? err.message : 'Registration failed');
// Get field errors
const errors = AuthService.getFieldErrors(err);
if (errors.length > 0) {
setFieldErrors(errors);
setError('Please fix the errors below');
} else {
setError(AuthService.getErrorMessage(err));
}
} finally {
setLoading(false);
}
@@ -88,9 +103,9 @@ export default function SignUpPage() {
<div className="inline-flex bg-[#f0f5fc] rounded-[20px] p-0.5">
<button
type="button"
onClick={() => setUserType('user')}
onClick={() => setUserType('USER')}
className={`px-7 py-2 text-sm font-light rounded-[20px] transition-all duration-200 ${
userType === 'user'
userType === 'USER'
? 'bg-[#00293d] text-[#f0f5fc]'
: 'text-[#00293d]'
}`}
@@ -99,14 +114,14 @@ export default function SignUpPage() {
</button>
<button
type="button"
onClick={() => setUserType('admin')}
onClick={() => setUserType('AGENT')}
className={`px-7 py-2 text-sm font-light rounded-[20px] transition-all duration-200 ${
userType === 'admin'
userType === 'AGENT'
? 'bg-[#00293d] text-[#f0f5fc]'
: 'text-[#00293d]'
}`}
>
Admin
Agent
</button>
</div>
</div>
@@ -119,16 +134,37 @@ export default function SignUpPage() {
</div>
)}
{/* Name Input */}
<div>
<input
type="text"
placeholder="Name"
value={name}
onChange={(e) => setName(e.target.value)}
required
className="w-full px-6 py-6 bg-[#f0f5fc] rounded-[20px] text-[#00293d] text-sm font-light placeholder:text-[#00293d] focus:outline-none focus:ring-2 focus:ring-[#00293d]/20 transition-all"
/>
{/* First Name & Last Name */}
<div className="flex gap-4">
<div className="flex-1">
<input
type="text"
placeholder="First Name"
value={firstName}
onChange={(e) => setFirstName(e.target.value)}
required
className={`w-full px-6 py-6 bg-[#f0f5fc] rounded-[20px] text-[#00293d] text-sm font-light placeholder:text-[#00293d] focus:outline-none focus:ring-2 focus:ring-[#00293d]/20 transition-all ${
getFieldError('firstName') ? 'ring-2 ring-red-400' : ''
}`}
/>
{getFieldError('firstName') && (
<p className="text-red-500 text-xs mt-1 ml-2">{getFieldError('firstName')}</p>
)}
</div>
<div className="flex-1">
<input
type="text"
placeholder="Last Name"
value={lastName}
onChange={(e) => setLastName(e.target.value)}
className={`w-full px-6 py-6 bg-[#f0f5fc] rounded-[20px] text-[#00293d] text-sm font-light placeholder:text-[#00293d] focus:outline-none focus:ring-2 focus:ring-[#00293d]/20 transition-all ${
getFieldError('lastName') ? 'ring-2 ring-red-400' : ''
}`}
/>
{getFieldError('lastName') && (
<p className="text-red-500 text-xs mt-1 ml-2">{getFieldError('lastName')}</p>
)}
</div>
</div>
{/* Email Input */}
@@ -139,36 +175,51 @@ export default function SignUpPage() {
value={email}
onChange={(e) => setEmail(e.target.value)}
required
className="w-full px-6 py-6 bg-[#f0f5fc] rounded-[20px] text-[#00293d] text-sm font-light placeholder:text-[#00293d] focus:outline-none focus:ring-2 focus:ring-[#00293d]/20 transition-all"
className={`w-full px-6 py-6 bg-[#f0f5fc] rounded-[20px] text-[#00293d] text-sm font-light placeholder:text-[#00293d] focus:outline-none focus:ring-2 focus:ring-[#00293d]/20 transition-all ${
getFieldError('email') ? 'ring-2 ring-red-400' : ''
}`}
/>
{getFieldError('email') && (
<p className="text-red-500 text-xs mt-1 ml-2">{getFieldError('email')}</p>
)}
</div>
{/* Password Input */}
<div className="relative">
<input
type={showPassword ? 'text' : 'password'}
placeholder="Password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
className="w-full px-6 py-6 bg-[#f0f5fc] rounded-[20px] text-[#00293d] text-sm font-light placeholder:text-[#00293d] focus:outline-none focus:ring-2 focus:ring-[#00293d]/20 transition-all pr-14"
/>
<button
type="button"
onClick={() => setShowPassword(!showPassword)}
className="absolute right-5 top-1/2 -translate-y-1/2 text-[#00293d]/60 hover:text-[#00293d] transition-colors"
>
{showPassword ? (
<svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
</svg>
) : (
<svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21" />
</svg>
)}
</button>
<div>
<div className="relative">
<input
type={showPassword ? 'text' : 'password'}
placeholder="Password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
className={`w-full px-6 py-6 bg-[#f0f5fc] rounded-[20px] text-[#00293d] text-sm font-light placeholder:text-[#00293d] focus:outline-none focus:ring-2 focus:ring-[#00293d]/20 transition-all pr-14 ${
getFieldError('password') ? 'ring-2 ring-red-400' : ''
}`}
/>
<button
type="button"
onClick={() => setShowPassword(!showPassword)}
className="absolute right-5 top-1/2 -translate-y-1/2 text-[#00293d]/60 hover:text-[#00293d] transition-colors"
>
{showPassword ? (
<svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
</svg>
) : (
<svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21" />
</svg>
)}
</button>
</div>
{getFieldError('password') && (
<p className="text-red-500 text-xs mt-1 ml-2">{getFieldError('password')}</p>
)}
<p className="text-[#00293d]/60 text-xs mt-2 ml-2">
Min 8 chars, 1 uppercase, 1 lowercase, 1 number, 1 special character
</p>
</div>
{/* Sign Up Button */}

71
src/services/api.ts Normal file
View File

@@ -0,0 +1,71 @@
import axios, { AxiosError, AxiosInstance, InternalAxiosRequestConfig } from 'axios';
// API Response types
export interface ApiResponse<T = unknown> {
success: boolean;
data: T;
statusCode?: number;
timestamp?: 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;
},
(error: AxiosError<ApiErrorResponse>) => {
// Handle common errors
if (error.response) {
const { status } = error.response;
// Handle 401 Unauthorized
if (status === 401) {
if (typeof window !== 'undefined') {
localStorage.removeItem('accessToken');
localStorage.removeItem('refreshToken');
}
}
}
return Promise.reject(error);
}
);
export default api;

View File

@@ -0,0 +1,146 @@
import api, { ApiResponse, ApiErrorResponse } from './api';
import { AxiosError } from 'axios';
// Types
export interface RegisterRequest {
firstName: string;
lastName?: string;
email: string;
password: string;
role: 'USER' | 'AGENT';
}
export interface LoginRequest {
email: string;
password: string;
}
export interface AuthUser {
id: string;
email: string;
role: string;
firstName?: string;
lastName?: string;
avatar?: string;
}
export interface AuthResponse {
user: AuthUser;
accessToken: string;
refreshToken: string;
}
export interface ForgotPasswordRequest {
email: string;
}
export interface ResetPasswordRequest {
token: string;
password: string;
}
export interface VerifyEmailRequest {
token: string;
}
export interface MessageResponse {
message: string;
}
// Auth Service
class AuthService {
private basePath = '/auth';
async register(data: RegisterRequest): Promise<ApiResponse<AuthResponse>> {
const response = await api.post<ApiResponse<AuthResponse>>(
`${this.basePath}/register`,
data
);
return response.data;
}
async login(data: LoginRequest): Promise<ApiResponse<AuthResponse>> {
const response = await api.post<ApiResponse<AuthResponse>>(
`${this.basePath}/login`,
data
);
return response.data;
}
async forgotPassword(data: ForgotPasswordRequest): Promise<ApiResponse<MessageResponse>> {
const response = await api.post<ApiResponse<MessageResponse>>(
`${this.basePath}/forgot-password`,
data
);
return response.data;
}
async resetPassword(data: ResetPasswordRequest): Promise<ApiResponse<MessageResponse>> {
const response = await api.post<ApiResponse<MessageResponse>>(
`${this.basePath}/reset-password`,
data
);
return response.data;
}
async verifyEmail(data: VerifyEmailRequest): Promise<ApiResponse<MessageResponse>> {
const response = await api.post<ApiResponse<MessageResponse>>(
`${this.basePath}/verify-email`,
data
);
return response.data;
}
async resendVerification(): Promise<ApiResponse<MessageResponse>> {
const response = await api.post<ApiResponse<MessageResponse>>(
`${this.basePath}/resend-verification`
);
return response.data;
}
async getCurrentUser(): Promise<ApiResponse<AuthUser>> {
const response = await api.get<ApiResponse<AuthUser>>(`${this.basePath}/me`);
return response.data;
}
async refreshToken(refreshToken: string): Promise<ApiResponse<{ accessToken: string; refreshToken: string }>> {
const response = await api.post<ApiResponse<{ accessToken: string; refreshToken: string }>>(
`${this.basePath}/refresh`,
{ refreshToken }
);
return response.data;
}
async logout(): Promise<ApiResponse<MessageResponse>> {
const response = await api.post<ApiResponse<MessageResponse>>(`${this.basePath}/logout`);
return response.data;
}
// Helper to extract error message from API error
static 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
static getFieldErrors(error: unknown): Array<{ field: string; errors: string[] }> {
if (error instanceof AxiosError) {
const apiError = error.response?.data as ApiErrorResponse;
return apiError?.errors || [];
}
return [];
}
}
export const authService = new AuthService();
export { AuthService };

16
src/services/index.ts Normal file
View File

@@ -0,0 +1,16 @@
// API Client
export { default as api } from './api';
export type { ApiResponse, ApiErrorResponse } from './api';
// Services
export { authService, AuthService } from './auth.service';
export type {
RegisterRequest,
LoginRequest,
AuthUser,
AuthResponse,
ForgotPasswordRequest,
ResetPasswordRequest,
VerifyEmailRequest,
MessageResponse,
} from './auth.service';