login with api
This commit is contained in:
parent
d8a9909eb9
commit
ff5b189b2f
16 changed files with 1241 additions and 66 deletions
92
frontend_management/services/auth.service.ts
Normal file
92
frontend_management/services/auth.service.ts
Normal 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');
|
||||
}
|
||||
}
|
||||
};
|
||||
Loading…
Add table
Add a link
Reference in a new issue