hanze/memory

memory-backend/frontend/login.js in main
Repositories | Summary | Log | Files

login.js (1323B) download


 1function callBackend(method, endpoint, data, headers = {}) {
 2	return fetch('http://localhost:8000/' + endpoint, {
 3		method: method,
 4    	headers: {
 5			'Content-Type': 'application/json', // own content-type
 6			'Accept': 'application/json', // responding content-type
 7			...headers
 8		},
 9		body: JSON.stringify(data)
10	}).then(res => res.json());
11}
12
13function parseJWT(token) {
14	var base64 = token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/');
15	var jsonPayload = decodeURIComponent(window.atob(base64).split('').map(function(c) {
16		return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
17	}).join(''));
18
19	return JSON.parse(jsonPayload);
20}
21
22function storeToken({ token, code, message }) {
23	if (code) {
24		alert(`Error: ${message} (${code})`);
25		return;
26	}
27	localStorage.setItem('token', token);
28
29	alert('Success!');
30}
31
32function getPayload() {
33    let { sub: id, username, roles } = parseJWT(localStorage.getItem('token'));
34
35	return { id, username, roles };
36}
37
38function getToken() {
39	let username = document.getElementById('user').value;
40	let password = document.getElementById('password').value;
41	
42	let data = { username, password };
43	
44	callBackend('POST', 'api/login_check', data)
45	  .then(storeToken).then(() => console.log(getPayload()));
46}
47
48document.getElementById('submit').addEventListener('click', getToken);