umami/lib/auth.js

54 lines
1.2 KiB
JavaScript
Raw Normal View History

import { parseSecureToken, parseToken } from './crypto';
import { SHARE_TOKEN_HEADER } from './constants';
import { getWebsiteById } from './queries';
2020-07-28 08:52:14 +02:00
export async function getAuthToken(req) {
try {
const token = req.headers.authorization;
2020-07-28 08:52:14 +02:00
return parseSecureToken(token.split(' ')[1]);
} catch {
return null;
}
2020-08-05 07:45:05 +02:00
}
export async function isValidToken(token, validation) {
try {
const result = await parseToken(token);
if (typeof validation === 'object') {
return !Object.keys(validation).find(key => result[key] !== validation[key]);
} else if (typeof validation === 'function') {
return validation(result);
}
} catch (e) {
return false;
}
return false;
}
export async function allowQuery(req, skipToken) {
2020-10-11 11:29:55 +02:00
const { id } = req.query;
const token = req.headers[SHARE_TOKEN_HEADER];
const websiteId = +id;
const website = await getWebsiteById(websiteId);
if (website) {
2020-10-13 01:31:51 +02:00
if (token && token !== 'undefined' && !skipToken) {
return isValidToken(token, { website_id: websiteId });
}
const authToken = await getAuthToken(req);
if (authToken) {
const { user_id, is_admin } = authToken;
return is_admin || website.user_id === user_id;
}
}
return false;
}