-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.ts
93 lines (80 loc) · 2.65 KB
/
utils.ts
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import { configuration } from "./configuration";
import cryptoRandomString from "crypto-random-string";
import httpContext from "express-http-context";
import path from "path";
import fs from "fs";
import { Context, User } from "./types";
import { Item } from "./models";
export const getContext = (): Context => ({
user: httpContext.get("user") as User,
});
const PLS_PERMISSIONS = {
ADMIN: "admin",
CUSTOM_LINK: "custom-link",
};
const LINK_REGEXP = /^[a-z0-9_-]+$/;
// TODO: Test
export const isAdmin = (user: User) => {
return user.pls.includes(PLS_PERMISSIONS.ADMIN);
};
// TODO: Test
export const canCreateCustomLinks = (user: User) => {
return user.pls.includes(PLS_PERMISSIONS.CUSTOM_LINK);
};
// TODO: Test
export const hasMandate = (user: User, mandate: string) =>
user.mandates.map((m) => m.identifier).includes(mandate) ||
user.groups.map((g) => g.identifier).includes(mandate);
// If there is no mandate on the link, and the user owns it, returns true
// If there is a mandate on the link, and the user currently holds that mandate, return true
// If the user is admin, return true
// Else return false
// TODO: Test
export const getHasDeleteAccess = (
user: User,
item: { mandate?: string; user?: string }
): boolean => {
if (isAdmin(user)) return true;
if (item.mandate) {
if (hasMandate(user, item.mandate)) return true;
} else if (item.user === user.user) {
return true;
}
return false;
};
export const generateShortString = async () => {
let iterator = 0;
while (true && iterator < 1000) {
const key = cryptoRandomString({
length: configuration.SHORT_URL_LENGTH,
// TODO: Update to latest version and fix the module issue
// sorry for this
characters: "abcdefghijklmnopqrstuvxyz01234567890-_",
});
const exists = await Item.findOne({ short: key });
if (!exists) {
return key;
}
iterator++;
}
throw new Error("Couldn't generate a unique shortened url. Try again.");
};
export const banned: Record<string, boolean> = {};
const getBlackList = () => {
// Read blacklist from file
(async () => {
console.log("Start read");
const file = fs.readFileSync(
path.join(__dirname, "resources", "everything.txt")
);
const lines = file.toString().split("\n");
for (const line of lines) {
if (line.startsWith("#")) continue;
banned[line] = true;
}
console.log("Read file");
})();
};
getBlackList();
export const isValidDesiredLink = (desired: string): boolean =>
LINK_REGEXP.test(desired);