summaryrefslogtreecommitdiff
path: root/rushs/eplace/src/pages/complete/epita/index.js
blob: ced46cfb6a55227321b703f84ba7e7fdf5f3a145 (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
// FIXME: This file should handle the auth redirection

// Get the code from the URL parameters and redirect to the relevant page
const params = new URLSearchParams(window.location.search);

const code = params.get("code");
const form = new FormData();

form.append("client_id", import.meta.env.VITE_CLIENT_ID);
form.append("redirect_uri", `${import.meta.env.VITE_URL}/complete/epita/`);
form.append("grant_type", "authorization_code");
form.append("code", code);
const config = {
    method: "POST",
    body: form,
};

export async function getToken() {
    try {
        const res = await fetch(
            `${import.meta.env.VITE_URL}/auth-api/token`,
            config,
        );
        const response = await res.json();

        const token = response.id_token;

        localStorage.setItem("token", token);
        localStorage.setItem("refresh_token", response.refresh_token);
        window.location.replace(import.meta.env.VITE_URL);
        return true;
    } catch (error) {
        console.log(error);
        return false;
    }
}

if (!code) {
    const authQueryParams = {
        client_id: import.meta.env.VITE_CLIENT_ID,
        scope: "epita profile picture",
        redirect_uri: `${import.meta.env.VITE_URL}/complete/epita/`,
        response_type: "code",
    };
    const url = new URL(
        `?client_id=${authQueryParams.client_id}&scope=${authQueryParams.scope}&redirect_uri=${authQueryParams.redirect_uri}&response_type=${authQueryParams.response_type}`,
        `${import.meta.env.VITE_AUTH_URL}/authorize`,
    );

    window.location.replace(url);
} else {
    getToken();
}