umami/lib/auth.js

65 lines
1.4 KiB
JavaScript
Raw Normal View History

2022-10-12 06:48:33 +02:00
import { parseSecureToken, parseToken } from 'next-basics';
import { getAccount, getWebsite } from 'queries';
import { SHARE_TOKEN_HEADER, TYPE_ACCOUNT, TYPE_WEBSITE } from 'lib/constants';
2022-10-12 06:48:33 +02:00
import { secret } from 'lib/crypto';
2020-07-28 08:52:14 +02:00
2022-10-12 06:48:33 +02:00
export function getAuthToken(req) {
try {
const token = req.headers.authorization;
2020-07-28 08:52:14 +02:00
2022-08-29 05:20:54 +02:00
return parseSecureToken(token.split(' ')[1], secret());
} catch {
return null;
}
2020-08-05 07:45:05 +02:00
}
2022-10-12 06:48:33 +02:00
export function getShareToken(req) {
try {
2022-10-25 04:48:10 +02:00
return parseToken(req.headers[SHARE_TOKEN_HEADER], secret());
2022-10-12 06:48:33 +02:00
} catch {
return null;
}
}
2022-10-12 06:48:33 +02:00
export function isValidToken(token, validation) {
try {
if (typeof validation === 'object') {
2022-10-25 04:48:10 +02:00
return !Object.keys(validation).find(key => token[key] !== validation[key]);
} else if (typeof validation === 'function') {
2022-10-25 04:48:10 +02:00
return validation(token);
}
} catch (e) {
return false;
}
return false;
}
export async function allowQuery(req, type) {
2022-10-25 04:48:10 +02:00
const { id } = req.query;
2022-10-12 22:11:44 +02:00
const { userId, isAdmin, shareToken } = req.auth ?? {};
2022-10-12 22:11:44 +02:00
if (isAdmin) {
return true;
}
2022-10-12 22:11:44 +02:00
if (shareToken) {
2022-10-25 04:48:10 +02:00
return isValidToken(shareToken, { id });
2022-10-12 22:11:44 +02:00
}
2022-10-12 22:11:44 +02:00
if (userId) {
if (type === TYPE_WEBSITE) {
const website = await getWebsite({ websiteUuid: id });
return website && website.userId === userId;
} else if (type === TYPE_ACCOUNT) {
const account = await getAccount({ accountUuid: id });
2022-10-25 20:01:28 +02:00
return account && account.accountUuid === id;
}
}
return false;
}