2019-06-21 22:01:34 +00:00
|
|
|
/**
|
|
|
|
* @module flitter-auth/deploy/routing/middleware/RequireAuth
|
|
|
|
*/
|
|
|
|
|
|
|
|
/**
|
|
|
|
* This middleware is provided by Flitter-auth. It will redirect the user
|
|
|
|
* back to their previous location if the does not contain a user object.
|
|
|
|
*
|
|
|
|
* @class
|
|
|
|
*/
|
2019-08-16 14:58:21 +00:00
|
|
|
const Middleware = require('libflitter/middleware/Middleware')
|
|
|
|
class RequireAuth extends Middleware {
|
2019-06-21 22:01:34 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Run the middleware's check. If an authenticated session exists, let the request continue.
|
|
|
|
* If an authenticated session doesn't exist, write the destination to the session and redirect
|
|
|
|
* the user to the login page.
|
|
|
|
* @param {Express/Request} req - the incoming Express request
|
|
|
|
* @param {Express/Response} res - the corresponding Express response
|
|
|
|
* @param {Function} next - Express handler stack callback. This should be called if the middleware check passed to allow the request to continue.
|
|
|
|
*/
|
2019-08-16 14:58:21 +00:00
|
|
|
test(req, res, next) {
|
|
|
|
if (req.session && req.session.auth && (req.session.auth.authenticated === true || req.session.auth.user)) {
|
2019-06-21 22:01:34 +00:00
|
|
|
/*
|
|
|
|
* Call the next function in the stack.
|
|
|
|
*/
|
|
|
|
next()
|
2019-08-16 14:58:21 +00:00
|
|
|
} else {
|
2019-06-21 22:01:34 +00:00
|
|
|
req.session.destination = req.originalUrl
|
|
|
|
return res.redirect('/auth/login')
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = RequireAuth
|