|
|
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("");
|
|
|
};
|