diff --git a/src/proxyauth.js b/src/proxyauth.js index 04c6f6c84..17bd023ae 100644 --- a/src/proxyauth.js +++ b/src/proxyauth.js @@ -95,7 +95,7 @@ function auth(req, res, next) { } // endpoint called by login page, username and password posted as JSON body -function login(req, res, next) { +function authenticate(req, res, next) { assert.strictEqual(typeof req.body, 'object'); const appId = req.headers['x-app-id'] || ''; @@ -111,15 +111,32 @@ function login(req, res, next) { api(username, password, appId, function (error, user) { if (error) return next(new HttpError(403, 'Invalid username or password' )); - const token = jwt.sign({ user: users.removePrivateFields(user) }, TOKEN_SECRET, { expiresIn: `${EXPIRY_DAYS}d` }); + req.user = user; + next(); + }); +} - res.cookie('authToken', token, { - httpOnly: true, - maxAge: EXPIRY_DAYS * 86400 * 1000, // milliseconds - secure: true +function authorize(req, res, next) { + const appId = req.headers['x-app-id'] || ''; + if (!appId) return next(new HttpError(503, 'Nginx misconfiguration')); + + apps.get(appId, function (error, app) { + if (error) return next(new HttpError(403, 'No such app' )); + + apps.hasAccessTo(app, req.user, function (error, hasAccess) { + if (error) return next(new HttpError(403, 'Forbidden' )); + if (!hasAccess) return next(new HttpError(403, 'Forbidden' )); + + const token = jwt.sign({ user: users.removePrivateFields(req.user) }, TOKEN_SECRET, { expiresIn: `${EXPIRY_DAYS}d` }); + + res.cookie('authToken', token, { + httpOnly: true, + maxAge: EXPIRY_DAYS * 86400 * 1000, // milliseconds + secure: true + }); + + res.redirect('/'); }); - - res.redirect('/'); }); } @@ -156,10 +173,9 @@ function initializeAuthwallExpressSync() { .use(router) .use(middleware.lastMile()); - router.get ('/', (req, res) => { res.redirect('/login'); }); // this can never happen router.get ('/login', loginPage); router.get ('/auth', jwtVerify, basicAuthVerify, auth); - router.post('/login', json, login); + router.post('/login', json, authenticate, authorize); router.get ('/logout', logoutPage); router.post('/logout', json, logout);