summaryrefslogtreecommitdiffstats
path: root/main.js
blob: a7aae91793914845a42b070565bbddc1184480cd (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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
import "regenerator-runtime/runtime"
import authConfig from "./auth_config.json";
import { Elm } from "./src/Main.elm";

// The Auth0 client, initialized in configureClient()
let auth0 = null;

/**
 * Starts the authentication flow
 */
const login = async(targetUrl) => {
    try {
        console.log("Logging in", targetUrl);

        const options = {
            redirect_uri: window.location.origin
        };

        if (targetUrl) {
            options.appState = { targetUrl };
        }

        await auth0.loginWithRedirect(options);
    } catch (err) {
        console.log("Log in failed", err);
    }
};

/**
 * Executes the logout flow
 */
const logout = () => {
    try {
        console.log("Logging out");
        auth0.logout({
            returnTo: window.location.origin
        });
    } catch (err) {
        console.log("Log out failed", err);
    }
};

/**
 * Initializes the Auth0 client
 */
const configureClient = async() => {
    auth0 = await createAuth0Client({
        domain: authConfig.domain,
        client_id: authConfig.clientId
    });
    window.auth0 = auth0;
};

const authenticateIfNeeded = async() => {
    await configureClient();

    const userDataExists = await auth0.isAuthenticated();

    if (userDataExists) {
        // If user is in browser state, use that user data
        console.log("> User is authenticated");
        window.history.replaceState({}, document.title, window.location.pathname);
        return;
    }

    console.log("> User not authenticated");

    // No user data in browser, try checking the query params for callback info
    const query = window.location.search;
    const shouldParseResult = query.includes("code=") && query.includes("state=");

    if (shouldParseResult) {
        // If URL contains callback query params, parse them and authenticate
        console.log("> Parsing redirect");
        try {
            await auth0.handleRedirectCallback();

            console.log("Logged in!");

            window.history.replaceState({}, document.title, window.location.pathname);
            return;
        } catch (err) {
            console.log("Error parsing redirect:", err);
        }
    }

    // No data to authenticate with, start login flow and redirect
    login();
}

// Will run when page finishes loading
window.onload = async() => {
    await authenticateIfNeeded();
    await runElmApp();
};

const runElmApp = async() => {
    try {
        const user = await auth0.getUser();
        const flags = {
            email: user.email,
            name: user.name,
            pictureUrl: user.picture,
        };

        const app = Elm.Main.init({
            node: document.getElementById("app"),
            flags,
        });

        app.ports.showAlert.subscribe((message) => window.alert(message));
        app.ports.requestLogout.subscribe(logout);
    } catch (err) {
        console.error(err);
    }
}