105 lines
2.4 KiB
TypeScript
105 lines
2.4 KiB
TypeScript
import http from '@/lib/http';
|
|
|
|
export interface LoginCredentials {
|
|
email: string;
|
|
password: string;
|
|
remember?: boolean;
|
|
}
|
|
|
|
export interface User {
|
|
id: number;
|
|
name: string;
|
|
email: string;
|
|
email_verified_at?: string;
|
|
created_at: string;
|
|
updated_at: string;
|
|
}
|
|
|
|
export interface LoginResponse {
|
|
user: User;
|
|
token?: string;
|
|
message?: string;
|
|
}
|
|
|
|
export interface ApiError {
|
|
message: string;
|
|
errors?: Record<string, string[]>;
|
|
}
|
|
|
|
class AuthService {
|
|
/**
|
|
* Login user with email and password
|
|
*/
|
|
async login(credentials: LoginCredentials): Promise<LoginResponse> {
|
|
try {
|
|
const response = await http.post<LoginResponse>(
|
|
'http://localhost:8000/api/auth/login',
|
|
credentials
|
|
);
|
|
return response.data;
|
|
} catch (error: any) {
|
|
throw this.handleError(error);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Logout the current user
|
|
*/
|
|
async logout(): Promise<void> {
|
|
try {
|
|
await http.post('http://localhost:8000/api/auth/logout');
|
|
} catch (error: any) {
|
|
throw this.handleError(error);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Get the current authenticated user
|
|
*/
|
|
async getCurrentUser(): Promise<User> {
|
|
try {
|
|
const response = await http.get<{ user: User }>(
|
|
'http://localhost:8000/api/auth/user'
|
|
);
|
|
return response.data.user;
|
|
} catch (error: any) {
|
|
throw this.handleError(error);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Check if user is authenticated
|
|
*/
|
|
async checkAuth(): Promise<boolean> {
|
|
try {
|
|
await this.getCurrentUser();
|
|
return true;
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Handle API errors
|
|
*/
|
|
private handleError(error: any): Error {
|
|
if (error.response?.data) {
|
|
const apiError = error.response.data as ApiError;
|
|
const message = apiError.message || 'An error occurred';
|
|
const errors = apiError.errors;
|
|
|
|
if (errors) {
|
|
const firstError = Object.values(errors)[0];
|
|
return new Error(firstError ? firstError[0] : message);
|
|
}
|
|
|
|
return new Error(message);
|
|
}
|
|
|
|
return new Error(error.message || 'Network error occurred');
|
|
}
|
|
}
|
|
|
|
export const authService = new AuthService();
|
|
export default authService;
|