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


const LOCAL_MODE = (document.location.hostname === "localhost");

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

// Fill session storage with mock data during LOCAL_MODE
if (LOCAL_MODE) {
    localStorage.setItem("googleToken", "");
    localStorage.setItem("googleTokenExpiration", "2000000000");
    localStorage.setItem("googleName", "John Doe");
    localStorage.setItem("googleEmail", "john@doe.com");
    localStorage.setItem("userId", "2");
    localStorage.setItem("simulationId", "1");
    localStorage.setItem("simulationAuthLevel", "OWN");
}

// 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) => {
            let 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
            let currentTime = (new Date()).getTime() / 1000;

            if (parseInt(localStorage.getItem("googleTokenExpiration")) - currentTime <= 0) {
                auth2.signIn().then(() => {
                    localStorage.setItem("googleToken", googleUser.getAuthResponse().id_token);
                    let 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?")
        }
    });
};


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