Register account with email and password

This commit is contained in:
aldrin 2021-04-14 10:30:52 +02:00
parent d4eba6a026
commit c040a5077a
11 changed files with 236 additions and 9 deletions

68
src/api.ts Normal file
View file

@ -0,0 +1,68 @@
import Cookies from "js-cookie";
class APIError extends Error {
constructor(message: string, public readonly errors: unknown) {
super(message);
}
}
class Model {
static async fetch(
method: "get" | "post",
endpoint: string,
item_callback: (item: any) => any
) {
const init = {
headers: new Headers(),
method: method,
//body: JSON.stringify({})
};
const csrfToken = Cookies.get("csrftoken");
if (csrfToken != undefined) {
init.headers.set("X-CSRFToken", csrfToken);
}
init.headers.set("Accept", "application/json");
init.headers.set("Content-Type", "application/json");
const response = await fetch(`/api/${endpoint}`, init);
const dataOrErrors: Array<any> = await response.json();
if (response.status === 200) {
return dataOrErrors.map(item_callback);
} else {
throw new APIError(response.statusText, dataOrErrors);
}
}
protected async create(endpoint: string, data: any) {
const init = {
headers: new Headers(),
method: "post",
body: JSON.stringify(data),
};
const csrfToken = Cookies.get("csrftoken");
if (csrfToken != undefined) {
init.headers.set("X-CSRFToken", csrfToken);
}
init.headers.set("Accept", "application/json");
init.headers.set("Content-Type", "application/json");
const response = await fetch(`/api/${endpoint}/`, init);
const dataOrErrors: Array<any> = await response.json();
if (response.status !== 201) {
throw new APIError(response.statusText, dataOrErrors);
}
}
}
interface UserData {
email: string;
password: string;
}
export class User extends Model implements UserData {
constructor(public email: string, public password: string) {
super();
}
async signup(): Promise<void> {
await super.create("users", { email: this.email, password: this.password });
}
}

View file

@ -1,10 +1,10 @@
<template>
<form class="box" @submit.prevent="">
<form class="box" @submit.prevent="doSignup">
<b-field label="E-Mail-Adresse">
<b-input type="email" icon="user" ref="email" />
<b-input type="email" v-model="user.email" />
</b-field>
<b-field label="Kennwort">
<b-input type="password" icon="key" />
<b-input type="password" v-model="user.password" />
</b-field>
<div v-if="false" class="notification is-danger">
@ -25,7 +25,14 @@
<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
import { User } from "@/api";
@Component
export default class LoginForm extends Vue {}
export default class LoginForm extends Vue {
private user = new User("", "");
private async doSignup() {
await this.user.signup();
}
}
</script>