Skip to content

Instantly share code, notes, and snippets.

@cokeSchlumpf
Created November 23, 2017 15:02
Show Gist options
  • Save cokeSchlumpf/e7492a721a940699faebef0fffa2fe5e to your computer and use it in GitHub Desktop.
Save cokeSchlumpf/e7492a721a940699faebef0fffa2fe5e to your computer and use it in GitHub Desktop.
Benutzerverwaltung
(req, res, next) => {
const auth = req.cookies.auth;
const token = _.get(auth, 'token');
if (token) {
cloudant((db) => {
const selector = {
entity: 'user',
token: token
};
db.find({ selector }, (err, result) => {
const docs = _.get(result, 'docs', []);
if (err || _.size(docs) < 1) {
next();
}
else {
const user = docs[0];
const uuser = _.assign({}, user, {
lastActivity: Date.now()
});
db.insert(uuser, (err) => {
if (err) {
winston.error('Unable to update user data in database', err);
}
else {
req.user = user;
}
next();
});
}
});
});
}
else {
next();
}
}
export const authorize = (...roles) => (req, res, next) => {
if (_.isUndefined(req.user)) {
res.redirect(LOGIN_URL);
}
else if (_.size(roles) > 0 && _.size(_.intersection(roles, _.get(req, 'user.roles', []))) === 0) {
res
.status(401)
.redirect(UNAUTHORIZED_URL);
}
else {
next();
}
}
const api = express.Router();
api.use(authorize('role1'));
api.post('/', handleRequest);
api.use(authorize('admin'));
api.get('/info', authorize('hallo'), handleInfo);
api.get('/', handleRequest);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment