backend.js (1554B)
1 function callBackend(method, endpoint, data = null, headers = {}) { 2 let token = localStorage.getItem('token'); 3 if (token) { 4 headers['Authorization'] = 'Bearer ' + token; 5 } 6 if (data) { 7 data = JSON.stringify(data); 8 headers['Content-Type'] = 'application/json'; 9 } else { 10 data = undefined; 11 } 12 return fetch('http://localhost:8000/' + endpoint, { 13 method: method, 14 headers: { 15 'Accept': 'application/json', // responding content-type 16 ...headers 17 }, 18 body: data 19 }).then(res => res.json()).catch(e => ({})); 20 } 21 22 function parseJWT(token) { 23 var base64 = token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/'); 24 var jsonPayload = decodeURIComponent(window.atob(base64).split('').map(c => 25 '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2) 26 ).join('')); 27 28 return JSON.parse(jsonPayload); 29 } 30 31 function getUser() { 32 let token = localStorage.getItem('token'); 33 if (!token) 34 return Promise.resolve(null); 35 36 let { sub: id, username: name, roles } = parseJWT(token); 37 38 return callBackend('GET', `api/player/${id}/email`).then(() => { 39 return { id, name, roles, token }; 40 }).catch(e => null); 41 } 42 43 function login(username, password) { 44 return callBackend('POST', 'api/login_check', { username, password }) 45 .then(({ token, code, message }) => { 46 if (token) { 47 localStorage.setItem('token', token); 48 return {}; 49 } 50 return { code, message }; 51 }); 52 } 53 54 function register(username, email, password) { 55 return callBackend('POST', 'register', { username, email, password }); 56 } 57 58 function logout() { 59 localStorage.removeItem('token'); 60 }