diff options
Diffstat (limited to 'server/helpers/express-utils.ts')
-rw-r--r-- | server/helpers/express-utils.ts | 77 |
1 files changed, 77 insertions, 0 deletions
diff --git a/server/helpers/express-utils.ts b/server/helpers/express-utils.ts new file mode 100644 index 000000000..d023117a8 --- /dev/null +++ b/server/helpers/express-utils.ts | |||
@@ -0,0 +1,77 @@ | |||
1 | import * as express from 'express' | ||
2 | import * as multer from 'multer' | ||
3 | import { CONFIG, REMOTE_SCHEME } from '../initializers' | ||
4 | import { logger } from './logger' | ||
5 | import { User } from '../../shared/models/users' | ||
6 | import { generateRandomString } from './utils' | ||
7 | |||
8 | function isNSFWHidden (res: express.Response) { | ||
9 | if (res.locals.oauth) { | ||
10 | const user: User = res.locals.oauth.token.User | ||
11 | if (user) return user.nsfwPolicy === 'do_not_list' | ||
12 | } | ||
13 | |||
14 | return CONFIG.INSTANCE.DEFAULT_NSFW_POLICY === 'do_not_list' | ||
15 | } | ||
16 | |||
17 | function getHostWithPort (host: string) { | ||
18 | const splitted = host.split(':') | ||
19 | |||
20 | // The port was not specified | ||
21 | if (splitted.length === 1) { | ||
22 | if (REMOTE_SCHEME.HTTP === 'https') return host + ':443' | ||
23 | |||
24 | return host + ':80' | ||
25 | } | ||
26 | |||
27 | return host | ||
28 | } | ||
29 | |||
30 | function badRequest (req: express.Request, res: express.Response, next: express.NextFunction) { | ||
31 | return res.type('json').status(400).end() | ||
32 | } | ||
33 | |||
34 | function createReqFiles ( | ||
35 | fieldNames: string[], | ||
36 | mimeTypes: { [ id: string ]: string }, | ||
37 | destinations: { [ fieldName: string ]: string } | ||
38 | ) { | ||
39 | const storage = multer.diskStorage({ | ||
40 | destination: (req, file, cb) => { | ||
41 | cb(null, destinations[ file.fieldname ]) | ||
42 | }, | ||
43 | |||
44 | filename: async (req, file, cb) => { | ||
45 | const extension = mimeTypes[ file.mimetype ] | ||
46 | let randomString = '' | ||
47 | |||
48 | try { | ||
49 | randomString = await generateRandomString(16) | ||
50 | } catch (err) { | ||
51 | logger.error('Cannot generate random string for file name.', { err }) | ||
52 | randomString = 'fake-random-string' | ||
53 | } | ||
54 | |||
55 | cb(null, randomString + extension) | ||
56 | } | ||
57 | }) | ||
58 | |||
59 | const fields = [] | ||
60 | for (const fieldName of fieldNames) { | ||
61 | fields.push({ | ||
62 | name: fieldName, | ||
63 | maxCount: 1 | ||
64 | }) | ||
65 | } | ||
66 | |||
67 | return multer({ storage }).fields(fields) | ||
68 | } | ||
69 | |||
70 | // --------------------------------------------------------------------------- | ||
71 | |||
72 | export { | ||
73 | isNSFWHidden, | ||
74 | getHostWithPort, | ||
75 | badRequest, | ||
76 | createReqFiles | ||
77 | } | ||