Files
ToBePlayed-Frontend/src/utils/auth.js
T

36 lines
1.4 KiB
JavaScript

// The tokens live in HttpOnly cookies that no script can read. This flag only remembers that a login happened; a
// stale flag costs one 401 and a failed refresh, then the login page opens.
export const SESSION_KEY = 'tbp_session';
// Where the token lived before the cookies. Removed on the next login or logout.
const LEGACY_TOKEN_KEY = 'tbp_jwt';
export const hasSession = () => localStorage.getItem(SESSION_KEY) !== null;
/**
* Changes on every login and on every settings save, so a hook that shows the user's Steam data can load again.
*/
export const sessionStamp = () => localStorage.getItem(SESSION_KEY);
export const markSession = () => {
localStorage.setItem(SESSION_KEY, String(Date.now()));
localStorage.removeItem(LEGACY_TOKEN_KEY);
};
export const clearSession = () => {
localStorage.removeItem(SESSION_KEY);
localStorage.removeItem(LEGACY_TOKEN_KEY);
};
/**
* Returns the path when it is a path inside this app, else null. The login page uses it to go back after a
* session expired; "//host", "/\host" and tabs or line breaks (browsers drop them, so "/\t/host" is "//host")
* would leave the app, "/login" would loop.
*/
export function safeReturnPath(path) {
if (typeof path !== 'string' || !path.startsWith('/') || path.startsWith('//') || path.startsWith('/\\')
|| /[\t\n\r]/.test(path)) {
return null;
}
return path === '/login' || path.startsWith('/login?') ? null : path;
}