Created
April 30, 2020 20:36
-
-
Save thanhdatvo/ab93f5a3e4deea59ba2a305707d1871e to your computer and use it in GitHub Desktop.
Expressjs Chained Middlewares
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
function authenticate(req, res, next) { | |
if (req.params.status === "authenticated") { | |
req.isAuthenticated = true | |
} else { | |
req.isAuthenticated = false | |
} | |
next(); | |
} | |
function authorize(req, res, next) { | |
if (req.isAuthenticated == false) { | |
next() | |
return | |
} | |
if (req.params.role === "admin") { | |
req.redirectRoute = "dashboard" | |
} else if (req.params.role === "user") { | |
req.redirectRoute = `homepage/${req.params.userId}` | |
} else { | |
req.redirectRoute = "contact-support" | |
} | |
next(); | |
} | |
app.get('/verify/:status/:role/:userId', authenticate, authorize, function (req, res) { | |
if(req.isAuthenticated == false){ | |
res.status(403); | |
res.send('Unauthenticated. Please signup!'); | |
return | |
} | |
res.send('Redirecting ' + req.redirectRoute); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment