CoreID/app/routing/middleware/Traps.middleware.js

113 lines
3.1 KiB
JavaScript
Raw Normal View History

2020-05-20 14:56:03 +00:00
const { Middleware } = require('libflitter')
class TrapUtility {
constructor(req, res, configs) {
this.request = req
this.session = req.session
2020-05-20 14:56:03 +00:00
this.response = res
this.user = req.user
this.configs = configs
}
async begin(trap_name, { session_only = false }) {
if ( session_only || !this.user ) {
this.session.trap = trap_name
} else {
this.user.trap = trap_name
await this.user.save()
}
if ( this.config().assume_trust )
this.request.trust.assume()
2020-05-20 14:56:03 +00:00
}
redirect() {
if ( this.config().assume_trust )
this.request.trust.assume()
2020-05-20 14:56:03 +00:00
return this.response.redirect(this.config().redirect_to)
}
async end() {
if ( this.config().assume_trust )
this.request.trust.unassume()
if ( this.user ) {
this.user.trap = ''
await this.user.save()
}
this.session.trap = ''
2020-05-20 14:56:03 +00:00
}
has_trap(name = '') {
if ( name )
return (this.user && this.user.trap === name) || this.session.trap === name
return (this.user && this.user.trap) || this.session.trap
2020-05-20 14:56:03 +00:00
}
get_trap() {
if ( this.session.trap ) return this.session.trap
else if ( this.user ) return this.user.trap
2020-05-20 14:56:03 +00:00
}
trap_exists(name) {
return !!this.configs[name]
}
2020-05-20 14:56:03 +00:00
config() {
return this.configs[this.get_trap()]
}
allows(route) {
const config = this.config()
const allowed = route.startsWith('/assets') || config.allowed_routes.includes(route.toLowerCase().trim())
if ( allowed ) return true
for ( const allowed_route of config.allowed_routes ) {
console.log('comparing', allowed_route, 'to', route)
const allowed_parts = allowed_route.split('/')
const parts = route.split('/')
let matches = true
for ( let i = 0; i < allowed_parts.length; i += 1 ) {
if ( allowed_parts[i] !== parts[i] && allowed_parts[i] !== '*' ) {
matches = false
}
}
if ( matches ) {
console.log('allows true')
return true
}
}
console.log('allows false')
return false
2020-05-20 14:56:03 +00:00
}
}
class TrapsMiddleware extends Middleware {
static get services() {
return [...super.services, 'models', 'configs']
}
async test(req, res, next, args = {}) {
const Setting = this.models.get('Setting')
2020-05-20 14:56:03 +00:00
req.trap = new TrapUtility(req, res, this.configs.get('traps.types'))
if (
!req.trap.has_trap()
&& req.user
&& !req.user.email_verified
&& (await Setting.get('auth.require_email_verify'))
) {
req.session.email_verify_flow = req.originalUrl
await req.trap.begin('verify_email', { session_only: false })
}
2020-05-20 14:56:03 +00:00
if ( !req.trap.has_trap() ) return next()
else if ( req.trap.allows(req.path) ) return next()
else return req.trap.redirect()
}
}
module.exports = exports = TrapsMiddleware