You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

93 lines
2.1 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

import { atom } from "nanostores";
import { api } from "../api";
import { setAuth } from "./auth";
export class DjangoValidationError extends Error {
errors;
constructor(errObject) {
super("");
this.name = "DjangoValidationError";
const fieldsErrors = [];
for (const field in errObject) {
fieldsErrors.push({
name: field,
errors: errObject[field],
});
}
this.errors = fieldsErrors;
}
}
export const signinLoading$ = atom(false);
export const signinError$ = atom("");
const DEFAULT_ERROR = "Невозможно войти с предоставленными учетными данными.";
export async function signin(values) {
signinLoading$.set(true);
signinError$.set("");
try {
const { data } = await api.request({
url: "/realms/SST/protocol/openid-connect/token",
baseURL: "https://kk.dev.selftech.ru/",
method: "POST",
data: {
"grant_type": "password",
client_id: "postnet",
client_secret: "K2yHweEUispkVeWn03VMk843sW2Moic5",
username: values.login,
password: values.password,
},
headers: {
'Content-type': 'application/x-www-form-urlencoded',
},
});
setAuth(true);
return data;
} catch (e) {
var error = DEFAULT_ERROR;
if (e.response?.data?.detail) {
error = e.response?.data?.detail;
signinError$.set(error);
}
throw new DjangoValidationError(e.response.data);
} finally {
signinLoading$.set(false);
}
}
export const resetSignin = function () {};
export const signupLoading$ = atom(false);
export const signupError$ = atom("");
export async function register(values) {
signupLoading$.set(true);
try {
const { data } = await api.post("accounts/register/", values);
return data;
} catch (e) {
if (e.response.data?.non_field_errors) {
signupError$.set(e.response.data.non_field_errors.join(" "));
}
throw new DjangoValidationError(e.response.data);
} finally {
signupLoading$.set(false);
}
}
export const resetSignup = function () {
signupError$.set("");
};