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