frontPanel/src/api/auth.ts
2024-05-13 16:24:41 +03:00

99 lines
2.4 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { makeRequest } from "@api/makeRequest";
import type {
LoginRequest,
LoginResponse,
RegisterRequest,
RegisterResponse,
} from "@frontend/kitui";
import { parseAxiosError } from "../utils/parse-error";
const API_URL = process.env.REACT_APP_DOMAIN + "/auth";
export const register = async (
login: string,
password: string,
phoneNumber: string,
): Promise<[RegisterResponse | null, string?]> => {
try {
const registerResponse = await makeRequest<
RegisterRequest,
RegisterResponse
>({
url: `${API_URL}/register`,
body: { login, password, phoneNumber },
useToken: false,
withCredentials: true,
});
return [registerResponse];
} catch (nativeError) {
const [error] = parseAxiosError(nativeError);
return [null, `Не удалось зарегестрировать аккаунт. ${error}`];
}
};
export const login = async (
login: string,
password: string,
): Promise<[LoginResponse | null, string?]> => {
try {
const loginResponse = await makeRequest<LoginRequest, LoginResponse>({
url: `${API_URL}/login`,
body: { login, password },
useToken: false,
withCredentials: true,
});
return [loginResponse];
} catch (nativeError) {
const [error] = parseAxiosError(nativeError);
return [null, `Не удалось войти. ${error}`];
}
};
export const logout = async (): Promise<[unknown, string?]> => {
try {
const logoutResponse = await makeRequest<never, void>({
method: "POST",
url: `${API_URL}/logout`,
useToken: true,
withCredentials: true,
});
return [logoutResponse];
} catch (nativeError) {
const [error] = parseAxiosError(nativeError);
return [null, error];
}
};
export const recover = async (
email: string,
): Promise<[unknown | null, string?]> => {
try {
const formData = new FormData();
formData.append("email", email);
formData.append(
"RedirectionURL",
process.env.REACT_APP_DOMAIN + "/changepwd",
);
const recoverResponse = await makeRequest<unknown, unknown>({
url: process.env.REACT_APP_DOMAIN + "/codeword/recover",
body: formData,
useToken: false,
withCredentials: true,
});
return [recoverResponse];
} catch (nativeError) {
const [error] = parseAxiosError(nativeError);
return [null, `Не удалось восстановить пароль. ${error}`];
}
};