forked from umami-software/umami
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.js
50 lines (38 loc) · 1.24 KB
/
auth.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import { parse } from 'cookie';
import { parseSecureToken, parseToken } from './crypto';
import { AUTH_COOKIE_NAME, TOKEN_HEADER } from './constants';
import { getWebsiteById } from './queries';
export async function getAuthToken(req) {
const token = parse(req.headers.cookie || '')[AUTH_COOKIE_NAME];
return parseSecureToken(token);
}
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) {
const { id } = req.query;
const token = req.headers[TOKEN_HEADER];
const websiteId = +id;
const website = await getWebsiteById(websiteId);
if (website) {
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;
}