Users#
Get Logged User#
To get data about the currently logged-in user, plugins can use the getLoggedUser method
defined in window.minerva.users object available globally. It returns a User object, or
undefined if no user is currently logged in.
Example of getLoggedUser method usage:#
window.minerva.users.getLoggedUser();Get Auth Token#
To call the MINERVA backend as the currently logged-in user, plugins can use the getAuthToken method defined in window.minerva.users object. It returns a promise that resolves to a token, which should be sent in the Authorization: Bearer <token> header.
- the token is refreshed before it is returned, so it is valid when the promise resolves, but it is short-lived: call
getAuthToken()before each request instead of keeping the token - the promise resolves to
nullwhen the plugin cannot act as the user:- no user is logged in (this includes a session that expired: MINERVA logs the user out first, so
getLoggedUser()returnsundefinedafterwards) - the plugin is not allowed to act as the user; plugin permissions do not exist yet, so this does not happen today, but plugins should be prepared for it
- no user is logged in (this includes a session that expired: MINERVA logs the user out first, so
- use
getLoggedUser()to tell these cases apart:nullwith no logged-in user means a guest,nullwith a logged-in user means the plugin is not allowed to act for the user - the promise is rejected when the token could not be refreshed for any other reason, such as a network or server error; the failure is usually temporary, so the plugin can retry later
Most API endpoints also serve guests, so a token is only needed for data or actions that belong to the user. A plugin that reads public data should send the token when it has one and make an unauthenticated request otherwise.
Example of getAuthToken method usage for public data:#
// authenticate when possible, otherwise ask as a guest
async function fetchFromMinerva(url) {
// a failed refresh falls back to a guest request instead of failing the read
const token = await window.minerva.users.getAuthToken().catch(() => null);
const headers = token === null ? {} : { Authorization: `Bearer ${token}` };
return fetch(url, { headers });
}Example of getAuthToken method usage for an action that needs a user:#
let token;
try {
token = await window.minerva.users.getAuthToken();
} catch (error) {
showMessage('Could not reach MINERVA. Try again later.');
return;
}
if (token === null) {
if (window.minerva.users.getLoggedUser() === undefined) {
showMessage('Log in to MINERVA to save your selection.');
} else {
showMessage('This plugin is not allowed to act on your behalf.');
}
return;
}
await fetch(url, { method: 'POST', headers: { Authorization: `Bearer ${token}` }, body });The address of the MINERVA API can be read with getApiUrls, see Project.