signup.ts 2.0 KB

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