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; $(document).ready(function() { const displayName = cookie.get('displayName'); if (!displayName) { // not logged in $('button#logout').css('display', 'none'); $('div#loginWidgets').css('display', 'initial'); $('span#displayName').text(''); } else { // logged in $('button#logout').css('display', 'initial'); $('span#displayName').text(`Logged in as ${displayName}`); } }); $('button#logout').click(function(event) { event.preventDefault(); logout(); }); // 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(`
id: ${todo.id}, task: ${todo.task}
`); }); } } catch (err) { console.error(err); $('div#todos').html(String(err)); } }); const finalizeLogin = user => { const { jwt, displayName } = user; cookie.set('jwt', jwt); cookie.set('displayName', displayName); window.location.reload(); }; const logout = () => { cookie.remove('jwt'); cookie.remove('displayName'); window.location.reload(); }; $('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 user = resp.data; finalizeLogin(user); } catch (err) { logout(); alert(err); } }); $('button#google-login').click(async function() { const GoogleAuth = gapi.auth2.getAuthInstance(); try { const googleUser = await GoogleAuth.signIn(); const authResponse = googleUser.getAuthResponse(true); const resp = await axios.post(`${LOGIN_API_URL}/login/google`, { accessToken: authResponse.access_token }); const user = resp.data; finalizeLogin(user); } catch (err) { logout(); alert(err); } }); window.gapiInit = () => { console.log('gapiInit'); gapi.load('auth2', function() { gapi.auth2.init({ client_id: GOOGLE_OAUTH_ID, }); }); };