Created
October 14, 2019 19:27
-
-
Save mahmoudafer/9c056c9207c72762ce9fddd0d0523cb2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const mongoose = require('mongoose'), | |
models = require('./models'), | |
jwt = require('jsonwebtoken') | |
app.all('*', (req, res, next) => { | |
const noAuthorization = ['/login', '/resetPassReq', '/resetPass', '/signup']; | |
if (noAuthorization.indexOf(req.path) !== -1) { // does not require authentication | |
return next() | |
} | |
// authenticate | |
let authUser | |
if (typeof req.headers.authorization !== 'undefined') { | |
try { | |
authUser = jwt.verify(req.headers.authorization, process.env.TOKEN_SECRET) | |
} catch (err) { | |
return res.status(400).json({ | |
status: err.message, | |
}) | |
} | |
} else { | |
return res.status(403).json({ | |
status: "Not logged in", | |
meta: null | |
}) | |
} | |
models.users.findOne({ | |
ID: authUser.ID | |
}, (err, user) => { | |
if (err) { | |
return next(err, false) | |
} | |
if (!user) { | |
return res.status(404).json({ | |
status: "User does not exist", | |
meta: null | |
}); | |
} | |
// authorize | |
const roleAccess = {} | |
roleAccess.student = ['/profile', '/buses', '/savenotificationtoken'] | |
roleAccess.driver = ['/ride'] | |
roleAccess.fo = ['/addseatcash', '/register'] | |
roleAccess.sao = roleAccess.student.concat(['/term', '/addbus', '/removebus', '/pushnotification', '/rides']); | |
roleAccess.admin = roleAccess.sao.concat(['/changerole']).concat(roleAccess.fo) | |
if (roleAccess[user.role] && roleAccess[user.role].indexOf(req.path) === -1) { | |
console.log(`a ${user.role} was trying to authorize to ${req.path} but got kicked out`) | |
return res.status(401).json({ | |
status: "User unauthorized", | |
meta: null | |
}) | |
} | |
req.authUser = user | |
next() | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment