refactor: Remove djoser dependency

This commit is contained in:
aldrin 2021-05-18 12:07:03 +02:00
parent a8464d7536
commit 048c8927b8
7 changed files with 62 additions and 54 deletions

View file

@ -29,7 +29,7 @@ async function request(
}
init.headers.set("Accept", "application/json");
init.headers.set("Content-Type", "application/json");
const response = await fetch(`/api/${endpoint}/`, init);
const response = await fetch(`/${endpoint}/`, init);
if (response.status !== 204) {
if (response.status === successStatus) {
return await response.json();
@ -39,6 +39,16 @@ async function request(
}
}
async function api_request(
method: HTTPMethod,
endpoint: string,
successStatus: number,
data: any,
authToken?: string
) {
return request(method, `api/${endpoint}`, successStatus, data, authToken);
}
export class User {
email: string | undefined;
password: string | undefined;
@ -48,20 +58,37 @@ export class User {
private token = "";
static async confirm(uid: string, token: string): Promise<void> {
await request("POST", "users/activation", 204, { uid, token });
await api_request("POST", "users/activation", 204, { uid, token });
}
async login(): Promise<void> {
const response = await request("POST", "token/login", 200, {
email: this.email,
password: this.password,
});
this.token = response.auth_token;
this.isAuthenticated = true;
if (!this.email || !this.password) throw new APIError("", "");
// logout any existing sessions
//await logout()
// fetch the login endpoint we use for authentication
const loginEndpoint = "/api-auth/login/";
// fetch the login page, so it sets csrf cookies
await window.fetch(loginEndpoint);
// authenticate us
const body = new window.FormData();
body.append("username", this.email);
body.append("password", this.password);
const csrf_token = Cookies.get("csrftoken");
if (csrf_token) body.append("csrfmiddlewaretoken", csrf_token);
const res = await window.fetch(loginEndpoint, { method: "post", body });
// successful logins are followed by a redirect
if (res.redirected && res.status === 200) {
this.isAuthenticated = true;
} else {
throw new APIError("", "");
}
}
async save(): Promise<void> {
await request(
await api_request(
"PATCH",
"users/me",
200,
@ -74,7 +101,7 @@ export class User {
}
async signup(): Promise<void> {
await request("POST", "users", 201, {
await api_request("POST", "users", 201, {
email: this.email,
password: this.password,
});