PeerTube/server/helpers/signup.ts

61 lines
2.0 KiB
TypeScript
Raw Normal View History

2018-08-14 15:28:30 +02:00
import { UserModel } from '../models/account/user'
import * as ipaddr from 'ipaddr.js'
2019-04-11 11:33:44 +02:00
import { CONFIG } from '../initializers/config'
2018-08-14 15:28:30 +02:00
const isCidr = require('is-cidr')
2019-10-25 13:54:32 +02:00
async function isSignupAllowed (): Promise<{ allowed: boolean, errorMessage?: string }> {
2018-08-14 15:28:30 +02:00
if (CONFIG.SIGNUP.ENABLED === false) {
2019-10-25 13:54:32 +02:00
return { allowed: false }
2018-08-14 15:28:30 +02:00
}
// No limit and signup is enabled
if (CONFIG.SIGNUP.LIMIT === -1) {
2019-10-25 13:54:32 +02:00
return { allowed: true }
2018-08-14 15:28:30 +02:00
}
const totalUsers = await UserModel.countTotal()
2019-10-25 13:54:32 +02:00
return { allowed: totalUsers < CONFIG.SIGNUP.LIMIT }
2018-08-14 15:28:30 +02:00
}
function isSignupAllowedForCurrentIP (ip: string) {
const addr = ipaddr.parse(ip)
let excludeList = [ 'blacklist' ]
let matched = ''
// if there is a valid, non-empty whitelist, we exclude all unknown adresses too
if (CONFIG.SIGNUP.FILTERS.CIDR.WHITELIST.filter(cidr => isCidr(cidr)).length > 0) {
excludeList.push('unknown')
}
if (addr.kind() === 'ipv4') {
const addrV4 = ipaddr.IPv4.parse(ip)
const rangeList = {
whitelist: CONFIG.SIGNUP.FILTERS.CIDR.WHITELIST.filter(cidr => isCidr.v4(cidr))
.map(cidr => ipaddr.IPv4.parseCIDR(cidr)),
blacklist: CONFIG.SIGNUP.FILTERS.CIDR.BLACKLIST.filter(cidr => isCidr.v4(cidr))
.map(cidr => ipaddr.IPv4.parseCIDR(cidr))
}
matched = ipaddr.subnetMatch(addrV4, rangeList, 'unknown')
} else if (addr.kind() === 'ipv6') {
const addrV6 = ipaddr.IPv6.parse(ip)
const rangeList = {
whitelist: CONFIG.SIGNUP.FILTERS.CIDR.WHITELIST.filter(cidr => isCidr.v6(cidr))
.map(cidr => ipaddr.IPv6.parseCIDR(cidr)),
blacklist: CONFIG.SIGNUP.FILTERS.CIDR.BLACKLIST.filter(cidr => isCidr.v6(cidr))
.map(cidr => ipaddr.IPv6.parseCIDR(cidr))
}
matched = ipaddr.subnetMatch(addrV6, rangeList, 'unknown')
}
return !excludeList.includes(matched)
}
// ---------------------------------------------------------------------------
export {
isSignupAllowed,
isSignupAllowedForCurrentIP
}