94 lines
2.7 KiB
TypeScript
94 lines
2.7 KiB
TypeScript
import api from './api';
|
||
import { User } from './users';
|
||
|
||
// Типы данных
|
||
export interface LoginCredentials {
|
||
username: string;
|
||
password: string;
|
||
}
|
||
|
||
export interface RegisterData {
|
||
email: string;
|
||
password: string;
|
||
password_confirm: string;
|
||
first_name?: string;
|
||
last_name?: string;
|
||
phone?: string;
|
||
}
|
||
|
||
export interface AuthResponse {
|
||
access_token: string;
|
||
token_type: string;
|
||
user: User;
|
||
}
|
||
|
||
// Сервис для аутентификации
|
||
const authService = {
|
||
// Вход в систему
|
||
login: async (credentials: LoginCredentials): Promise<AuthResponse> => {
|
||
// Создаем FormData для отправки данных в формате x-www-form-urlencoded
|
||
const formData = new URLSearchParams();
|
||
formData.append('username', credentials.username);
|
||
formData.append('password', credentials.password);
|
||
|
||
const response = await api.post<AuthResponse>('/auth/login', formData.toString(), {
|
||
headers: {
|
||
'Content-Type': 'application/x-www-form-urlencoded',
|
||
},
|
||
});
|
||
|
||
// Сохраняем токен в localStorage
|
||
if (response.data.access_token) {
|
||
localStorage.setItem('token', response.data.access_token);
|
||
}
|
||
|
||
return response.data;
|
||
},
|
||
|
||
// Регистрация нового пользователя
|
||
register: async (data: RegisterData): Promise<AuthResponse> => {
|
||
const response = await api.post<AuthResponse>('/auth/register', data);
|
||
|
||
// Сохраняем токен в localStorage
|
||
if (response.data.access_token) {
|
||
localStorage.setItem('token', response.data.access_token);
|
||
}
|
||
|
||
return response.data;
|
||
},
|
||
|
||
// Выход из системы
|
||
logout: (): void => {
|
||
localStorage.removeItem('token');
|
||
},
|
||
|
||
// Проверка, авторизован ли пользователь
|
||
isAuthenticated: (): boolean => {
|
||
return !!localStorage.getItem('token');
|
||
},
|
||
|
||
// Получить текущий токен
|
||
getToken: (): string | null => {
|
||
return localStorage.getItem('token');
|
||
},
|
||
|
||
// Запрос на сброс пароля
|
||
resetPassword: async (email: string): Promise<void> => {
|
||
await api.post('/auth/reset-password', { email });
|
||
},
|
||
|
||
// Установка нового пароля после сброса
|
||
setNewPassword: async (token: string, password: string): Promise<void> => {
|
||
await api.post('/auth/set-new-password', { token, password });
|
||
},
|
||
|
||
// Изменение пароля авторизованным пользователем
|
||
changePassword: async (currentPassword: string, newPassword: string): Promise<void> => {
|
||
await api.post('/auth/change-password', {
|
||
current_password: currentPassword,
|
||
new_password: newPassword
|
||
});
|
||
}
|
||
};
|
||
|
||
export default authService;
|