CoreID/app/routing/middleware/Traps.middleware.js
2020-05-20 09:56:03 -05:00

62 lines
1.4 KiB
JavaScript

const { Middleware } = require('libflitter')
class TrapUtility {
constructor(req, res, configs) {
this.request = req
this.response = res
this.user = req.user
this.configs = configs
}
async begin(trap_name) {
this.user.trap = trap_name
this.request.trust.assume()
await this.user.save()
}
redirect() {
this.request.trust.assume()
return this.response.redirect(this.config().redirect_to)
}
async end() {
this.user.trap = ''
this.request.trust.unassume()
await this.user.save()
}
has_trap() {
return !!this.user.trap
}
get_trap() {
return this.user.trap
}
config() {
return this.configs[this.get_trap()]
}
allows(route) {
const config = this.config()
return route.startsWith('/assets') || config.allowed_routes.includes(route.toLowerCase().trim())
}
}
class TrapsMiddleware extends Middleware {
static get services() {
return [...super.services, 'models', 'configs']
}
async test(req, res, next, args = {}) {
if ( !req?.user ) return next()
req.trap = new TrapUtility(req, res, this.configs.get('traps.types'))
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