]>
Commit | Line | Data |
---|---|---|
1 | import { IPv4, IPv6, parse, subnetMatch } from 'ipaddr.js' | |
2 | import { CONFIG } from '../initializers/config' | |
3 | import { UserModel } from '../models/user/user' | |
4 | ||
5 | const isCidr = require('is-cidr') | |
6 | ||
7 | export type SignupMode = 'direct-registration' | 'request-registration' | |
8 | ||
9 | async function isSignupAllowed (options: { | |
10 | signupMode: SignupMode | |
11 | ||
12 | ip: string // For plugins | |
13 | body?: any | |
14 | }): Promise<{ allowed: boolean, errorMessage?: string }> { | |
15 | const { signupMode } = options | |
16 | ||
17 | if (CONFIG.SIGNUP.ENABLED === false) { | |
18 | return { allowed: false } | |
19 | } | |
20 | ||
21 | if (signupMode === 'direct-registration' && CONFIG.SIGNUP.REQUIRES_APPROVAL === true) { | |
22 | return { allowed: false } | |
23 | } | |
24 | ||
25 | // No limit and signup is enabled | |
26 | if (CONFIG.SIGNUP.LIMIT === -1) { | |
27 | return { allowed: true } | |
28 | } | |
29 | ||
30 | const totalUsers = await UserModel.countTotal() | |
31 | ||
32 | return { allowed: totalUsers < CONFIG.SIGNUP.LIMIT } | |
33 | } | |
34 | ||
35 | function isSignupAllowedForCurrentIP (ip: string) { | |
36 | if (!ip) return false | |
37 | ||
38 | const addr = parse(ip) | |
39 | const excludeList = [ 'blacklist' ] | |
40 | let matched = '' | |
41 | ||
42 | // if there is a valid, non-empty whitelist, we exclude all unknown addresses too | |
43 | if (CONFIG.SIGNUP.FILTERS.CIDR.WHITELIST.filter(cidr => isCidr(cidr)).length > 0) { | |
44 | excludeList.push('unknown') | |
45 | } | |
46 | ||
47 | if (addr.kind() === 'ipv4') { | |
48 | const addrV4 = IPv4.parse(ip) | |
49 | const rangeList = { | |
50 | whitelist: CONFIG.SIGNUP.FILTERS.CIDR.WHITELIST.filter(cidr => isCidr.v4(cidr)) | |
51 | .map(cidr => IPv4.parseCIDR(cidr)), | |
52 | blacklist: CONFIG.SIGNUP.FILTERS.CIDR.BLACKLIST.filter(cidr => isCidr.v4(cidr)) | |
53 | .map(cidr => IPv4.parseCIDR(cidr)) | |
54 | } | |
55 | matched = subnetMatch(addrV4, rangeList, 'unknown') | |
56 | } else if (addr.kind() === 'ipv6') { | |
57 | const addrV6 = IPv6.parse(ip) | |
58 | const rangeList = { | |
59 | whitelist: CONFIG.SIGNUP.FILTERS.CIDR.WHITELIST.filter(cidr => isCidr.v6(cidr)) | |
60 | .map(cidr => IPv6.parseCIDR(cidr)), | |
61 | blacklist: CONFIG.SIGNUP.FILTERS.CIDR.BLACKLIST.filter(cidr => isCidr.v6(cidr)) | |
62 | .map(cidr => IPv6.parseCIDR(cidr)) | |
63 | } | |
64 | matched = subnetMatch(addrV6, rangeList, 'unknown') | |
65 | } | |
66 | ||
67 | return !excludeList.includes(matched) | |
68 | } | |
69 | ||
70 | // --------------------------------------------------------------------------- | |
71 | ||
72 | export { | |
73 | isSignupAllowed, | |
74 | isSignupAllowedForCurrentIP | |
75 | } |