80 lines
1.7 KiB
JavaScript
80 lines
1.7 KiB
JavaScript
import * as redirect from "./redirect";
|
|
|
|
/**
|
|
* @param {string} code the authorization code received from the OIDC
|
|
* provider
|
|
* @returns {boolean} true if the token was fetched, false otherwise
|
|
*/
|
|
async function getToken(code) {
|
|
|
|
const endpoint = `${VITE_AUTH_URL}/...`;
|
|
const formData = {
|
|
"grant_type": "authorization_code",
|
|
"code": code,
|
|
"redirect_uri": redirect.createLink(),
|
|
"client_id": process.env.VITE_CLIENT_ID
|
|
}
|
|
const request = {
|
|
method: "POST",
|
|
headers: {
|
|
"Content-Type": "application/x-www-form-urlencoded",
|
|
},
|
|
|
|
body: new URLSearchParams(formData)
|
|
};
|
|
|
|
const response = await fetch(endpoint, request)
|
|
if (!response.ok) {
|
|
console.error("Failed to retrieve OIDC token")
|
|
console.debug(response)
|
|
|
|
localStorage.clear();
|
|
redirect.redirectToLoginPage()
|
|
return false
|
|
}
|
|
|
|
const {
|
|
// access_token,
|
|
// token_type,
|
|
refresh_token,
|
|
// expires_in,
|
|
id_token
|
|
} = response.body
|
|
|
|
localStorage.setItem("token", id_token);
|
|
localStorage.setItem("refresh_token", refresh_token);
|
|
|
|
return true
|
|
}
|
|
|
|
|
|
/**
|
|
* @param {string} refreshToken the refresh token (optional)
|
|
* @returns {boolean} whether the token has been refreshed or not
|
|
* @warn NOT IMPLEMENTED
|
|
*/
|
|
// TODO
|
|
// async function refreshToken(refreshToken) {}
|
|
|
|
/**
|
|
* @returns {boolean} true if the user is authenticated, false otherwise
|
|
*/
|
|
async function authenticate() {
|
|
const token = localStorage.getItem("token");
|
|
if (token !== null)
|
|
return true;
|
|
const refresh_token = localStorage.getItem("refresh_token");
|
|
if (refresh_token !== null)
|
|
return true;
|
|
|
|
redirect.redirectToLoginPage();
|
|
return false;
|
|
}
|
|
|
|
// FIXME
|
|
// missing functions:
|
|
// - authedAPIRequest (makes an authenticated request to the API)
|
|
|
|
module.exports = {
|
|
|
|
}
|