aboutsummaryrefslogtreecommitdiff
path: root/app/static/js/jwt.js
blob: 1e0770389c775487eedba40a49a379c38ae94561 (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
// Description: This file contains functions to access the API with JWT authentication.

/**
 * Accept a full URL, method, and body to send to the API.
 *  - If successful, return the response
 *  - If first fail, attempt to refresh JWT token and try again
 *  - If second fail, return false
 * @param {*} endpoint API endpoint
 * @param {*} method String (GET, POST, PUT, DELETE)
 * @param {*} body Data to send to the API
 * @returns boolean
 */
async function accessAPI(endpoint, method, body) {
    let response = await fetch(`/api${endpoint}`, {
        method: method,
        body: body,
    });

    if (response.ok) {
        let data = await response.json();
        data = await data;
        console.log(data);
        return data;
    } else if (response.status === 401) {
        console.log('REFRESHING TOKEN')
        if (await refreshAccessToken()) {
            // Try the request again
            let response = await fetch(`/api${endpoint}`, {
                method: method,
                body: body,
            });
            if (response.ok) {
                let data = await response.json();
                data = await data;
                console.log("REFRESHED DATA")
                return data;
            }
        }
    }
    return false;
}

/**
 * Attempt to refresh the JWT token
 * @returns boolean
 */
async function refreshAccessToken () {
    const response = await fetch('/api/auth/refresh', {
        method: 'POST',
    });
    if (response.ok) {
        console.log("TOKEN REFRESH")
        return true;
    } else {
        console.log("TOKEN REFRESH FAILED")
        return false;
    }
}