/**
* @module flitter-auth/middleware/UserOnly
*/
const Middleware = require('libflitter/middleware/Middleware')
/**
* Allows the request to proceed only if there is an authenticated user in the session.
* Otherwise, redirects the user to the login page of the default provider, storing the target route.
* @extends module:libflitter/middleware/Middleware~Middleware
*/
class UserOnly extends Middleware {
/**
* Redirects the request to a login page if the session is unauthenticated.
* Stores the originalUrl in the 'session.auth.flow' key.
* @param {express/request} req
* @param {express/response} res
* @param {function} next
* @param {object} [args = {}]
* @return {Promise<*>}
*/
async test(req, res, next, args = {}){
if ( req.is_auth ) return next()
else {
// If not signed in, save the target url so we can redirect back here after auth
req.session.auth.flow = req.originalUrl
return res.redirect('/auth/login')
}
}
}
module.exports = UserOnly