summaryrefslogtreecommitdiff
path: root/src/scripts/user-authentication.ts
blob: e9d13091a73d35b284082089bfc6c31210666ee6 (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
///<reference path="../../typings/index.d.ts" />
import * as $ from "jquery";


// Redirect the user to the splash page, if not signed in
if (localStorage.getItem("googleToken") === null) {
    window.location.replace("/");
}

// Set the username in the navbar
$("nav .user .username").text(localStorage.getItem("googleName"));


// Set the language of the GAuth button to be English
window["___gcfg"] = {
    lang: 'en'
};

/**
 * Google signin button.
 */
window["gapiSigninButton"] = () => {
    gapi.signin2.render('google-signin', {
        'scope': 'profile email',
        'onsuccess': (googleUser) => {
            const auth2 = gapi.auth2.getAuthInstance();

            // Handle signout click
            $("nav .user .sign-out").click(() => {
                removeUserInfo();
                auth2.signOut().then(() => {
                    window.location.href = "/";
                });
            });

            // Check if the token has expired
            const currentTime = (new Date()).getTime() / 1000;

            if (parseInt(localStorage.getItem("googleTokenExpiration")) - currentTime <= 0) {
                auth2.signIn().then(() => {
                    localStorage.setItem("googleToken", googleUser.getAuthResponse().id_token);
                    const expirationTime = (new Date()).getTime() / 1000 + parseInt(googleUser.getAuthResponse().expires_in) - 5;
                    localStorage.setItem("googleTokenExpiration", expirationTime.toString());
                });
            }
        },
        'onfailure': () => {
            window.location.href = "/";
            console.log("Oops, something went wrong with your Google signin... Try again?");
        }
    });
};


/**
 * Removes session storage items.
 */
export function removeUserInfo() {
    localStorage.removeItem("googleToken");
    localStorage.removeItem("googleTokenExpiration");
    localStorage.removeItem("googleName");
    localStorage.removeItem("googleEmail");
    localStorage.removeItem("userId");
    localStorage.removeItem("simulationId");
}