feat: create login register
This commit is contained in:
@@ -0,0 +1,82 @@
|
||||
import { useState } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { authService } from "../api/auth.service";
|
||||
import { useApi } from "@/shared/api/hooks/use.api";
|
||||
import type {
|
||||
LoginCredentials,
|
||||
RegisterData,
|
||||
OrganizationCreateData,
|
||||
} from "../types/auth.types";
|
||||
|
||||
export const useAuth = () => {
|
||||
const navigate = useNavigate();
|
||||
const { isLoading, error, request } = useApi();
|
||||
const [authError, setAuthError] = useState<string | null>(null);
|
||||
|
||||
const login = async (credentials: LoginCredentials) => {
|
||||
setAuthError(null);
|
||||
const result = await request(() => authService.login(credentials));
|
||||
|
||||
if (result) {
|
||||
authService.saveAuthData(result.access_token, result.user);
|
||||
|
||||
// Проверяем, есть ли уже организация
|
||||
const orgs = await request(() => authService.getOrganizations());
|
||||
if (orgs && orgs.length > 0) {
|
||||
authService.saveOrganization(orgs[0]);
|
||||
navigate("/home");
|
||||
} else {
|
||||
navigate("/create-organization");
|
||||
}
|
||||
} else if (error) {
|
||||
setAuthError(error);
|
||||
}
|
||||
};
|
||||
|
||||
const register = async (data: RegisterData) => {
|
||||
setAuthError(null);
|
||||
|
||||
if (data.password !== data.confirmPassword) {
|
||||
setAuthError("Пароли не совпадают");
|
||||
return;
|
||||
}
|
||||
|
||||
const { confirmPassword, ...registerData } = data;
|
||||
const result = await request(() => authService.register(registerData));
|
||||
|
||||
if (result) {
|
||||
authService.saveAuthData(result.access_token, result.user);
|
||||
navigate("/create-organization");
|
||||
} else if (error) {
|
||||
setAuthError(error);
|
||||
}
|
||||
};
|
||||
|
||||
const createOrganization = async (data: OrganizationCreateData) => {
|
||||
setAuthError(null);
|
||||
const result = await request(() => authService.createOrganization(data));
|
||||
|
||||
if (result) {
|
||||
authService.saveOrganization(result);
|
||||
navigate("/home");
|
||||
} else if (error) {
|
||||
setAuthError(error);
|
||||
}
|
||||
};
|
||||
|
||||
const logout = () => {
|
||||
authService.logout();
|
||||
navigate("/");
|
||||
};
|
||||
|
||||
return {
|
||||
login,
|
||||
register,
|
||||
createOrganization,
|
||||
logout,
|
||||
isLoading,
|
||||
error: authError,
|
||||
isAuthenticated: authService.isAuthenticated(),
|
||||
hasOrganization: authService.hasOrganization(),
|
||||
};
|
||||
};
|
||||
Reference in New Issue
Block a user