blob: 8efc6796030fb32a957678e5870689fae6e1ef0c (
plain)
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
|
import limiter from './limiter';
import { IUser } from '../../models/user';
import { IApp } from '../../models/app';
import endpoints from './endpoints';
export default async (endpoint: string, user: IUser, app: IApp, data: any, file?: any) => {
const isSecure = user != null && app == null;
const ep = endpoints.find(e => e.name === endpoint);
if (ep == null) {
throw 'ENDPOINT_NOT_FOUND';
}
if (ep.meta.secure && !isSecure) {
throw 'ACCESS_DENIED';
}
if (ep.meta.requireCredential && user == null) {
throw 'CREDENTIAL_REQUIRED';
}
if (ep.meta.requireCredential && user.isSuspended) {
throw 'YOUR_ACCOUNT_HAS_BEEN_SUSPENDED';
}
if (ep.meta.requireAdmin && !user.isAdmin) {
throw 'YOU_ARE_NOT_ADMIN';
}
if (ep.meta.requireModerator && !user.isAdmin && !user.isModerator) {
throw 'YOU_ARE_NOT_MODERATOR';
}
if (app && ep.meta.kind && !app.permission.some(p => p === ep.meta.kind)) {
throw 'PERMISSION_DENIED';
}
if (ep.meta.requireCredential && ep.meta.limit) {
try {
await limiter(ep, user); // Rate limit
} catch (e) {
// drop request if limit exceeded
throw 'RATE_LIMIT_EXCEEDED';
}
}
let res;
// API invoking
try {
res = await ep.exec(data, user, app, file);
} catch (e) {
if (e && e.name == 'INVALID_PARAM') {
throw {
code: e.name,
param: e.param,
reason: e.message
};
} else {
throw e;
}
}
return res;
};
|