login with api

This commit is contained in:
Missez 2026-01-14 13:58:25 +07:00
parent d8a9909eb9
commit ff5b189b2f
16 changed files with 1241 additions and 66 deletions

View file

@ -0,0 +1,92 @@
export interface LoginRequest {
email: string;
password: string;
}
// API Response structure (from backend)
export interface ApiLoginResponse {
token: string;
refreshToken: string;
user: {
id: number;
username: string;
email: string;
updated_at: string;
created_at: string;
role: {
code: string;
name: {
en: string;
th: string;
};
};
profile: {
prefix: {
en: string;
th: string;
};
first_name: string;
last_name: string;
phone: string | null;
avatar_url: string | null;
birth_date: string | null;
};
};
}
// Frontend User structure
export interface LoginResponse {
token: string;
refreshToken: string;
user: {
id: string;
email: string;
fullName: string;
role: string;
};
}
export const authService = {
async login(email: string, password: string): Promise<LoginResponse> {
const config = useRuntimeConfig();
try {
const response = await $fetch<ApiLoginResponse>('/api/auth/login', {
method: 'POST',
baseURL: config.public.apiBaseUrl as string,
body: {
email,
password
}
});
// Transform API response to frontend format
return {
token: response.token,
refreshToken: response.refreshToken,
user: {
id: response.user.id.toString(),
email: response.user.email,
fullName: `${response.user.profile.first_name} ${response.user.profile.last_name}`,
role: response.user.role.code // Use role.code (ADMIN, INSTRUCTOR, etc.)
}
};
} catch (error: any) {
// Handle API errors
if (error.response?.status === 401) {
throw new Error('Invalid credentials');
}
throw new Error('Login failed');
}
},
async logout(): Promise<void> {
// TODO: Call logout API if available
// For now, just clear local storage
if (process.client) {
localStorage.removeItem('token');
localStorage.removeItem('refreshToken');
localStorage.removeItem('user');
}
}
};