blob: 3deeda32b53145394cc74ac49fa702233630b59a (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
|
import 'regenerator-runtime/runtime';
import axios from 'axios';
import $ from 'jquery';
import cookie from 'js-cookie';
const LOGIN_API_URL = process.env.LOGIN_API_URL;
const POSTGREST_API_URL = process.env.POSTGREST_API_URL;
const GOOGLE_OAUTH_ID = process.env.GOOGLE_OAUTH_ID;
$('button#logout').click(function(event) {
event.preventDefault();
cookie.remove('jwt');
alert('Logged out.');
});
// fetch data from postgrest
$('button#fetchTodosBtn').click(async function() {
$('div#todos').html('');
const jwt = cookie.get('jwt');
try {
const resp = await axios.get(`${POSTGREST_API_URL}/todos`, {
headers: { Authorization: `Bearer ${jwt}` },
});
const todos = resp.data;
if (todos.length === 0) {
$('div#todos').html('No TODOs.');
} else {
todos.forEach(todo => {
$('div#todos').append(`<div>id: ${todo.id}, task: ${todo.task}</div>`);
});
}
} catch (err) {
console.error(err);
$('div#todos').html(String(err));
}
});
$('form#loginForm').submit(async function(event) {
event.preventDefault();
const username = $(this).find('input#username').val();
const password = $(this).find('input#password').val();
try {
const resp = await axios.post(`${LOGIN_API_URL}/login/userpass`, { username, password });
const payload = resp.data;
const { jwt, displayName } = payload;
cookie.set('jwt', jwt);
alert(`Logged in as ${displayName}.`);
} catch (err) {
cookie.remove('jwt');
alert(err);
}
});
$('button#google-login').click(async function() {
const GoogleAuth = gapi.auth2.getAuthInstance();
try {
const user = await GoogleAuth.signIn();
const authResponse = user.getAuthResponse(true);
const resp = await axios.post(`${LOGIN_API_URL}/login/google`, { accessToken: authResponse.access_token });
const payload = resp.data;
const { jwt, displayName } = payload;
cookie.set('jwt', jwt);
alert(`Logged in as ${displayName}.`);
} catch (err) {
console.error(err);
}
});
window.gapiInit = () => {
console.log('gapiInit');
gapi.load('auth2', function() {
gapi.auth2.init({
client_id: GOOGLE_OAUTH_ID,
});
});
};
|