Signed-off-by: garionion <github@entr0py.de>
This commit is contained in:
garionion 2021-04-03 17:34:28 +02:00
parent bb249e63fc
commit e7cd3a4e6b
Signed by: garionion
GPG key ID: 53352FA607FA681A
4 changed files with 75 additions and 0 deletions

52
src/api/index.ts Normal file
View file

@ -0,0 +1,52 @@
import { LoginResponse, token } from "./types";
import { get, set } from "idb-keyval";
import { unref } from "vue";
const url = "http://192.168.178.5:8080/api";
let token: token;
let ready = false;
export async function init() {
if (ready) return;
await get("token").then((val: token) => {
if (val !== undefined) {
token = val;
}
});
ready = true;
}
export async function isLoggedIn(): Promise<boolean> {
await init();
return token !== undefined && token.expiration > Date.now();
}
export async function login(user: string, password: string): Promise<boolean> {
await init();
let response = await fetch(`${url}/auth`, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify({ username: user, password: password }),
});
const login: LoginResponse = await response.json();
if (response.ok) {
if (login.success) {
token = {
jwt: login.token,
expiration: Date.parse(login.expiration),
};
set("token", token).catch((error) => console.error(error));
return true;
} else {
return Promise.reject(new Error(login.message));
}
} else {
const error = new Error(login.message);
return Promise.reject(error);
}
}

11
src/api/types.ts Normal file
View file

@ -0,0 +1,11 @@
export interface token {
jwt: string;
expiration: number;
}
export interface LoginResponse {
expiration: string;
message: string;
success: boolean;
token: string;
}