Created
October 1, 2019 02:36
-
-
Save harrisonmalone/51ccbffe4cd4ea8ac3cd9587d8c11ed6 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 express = require('express'); | |
| const users = require('./users'); | |
| const app = express(); | |
| const PORT = process.env.PORT || 5000 | |
| const authenticate = ({ username, password }) => { | |
| const user = users.find((user) => { | |
| return user.username === username | |
| }) | |
| if (user) { | |
| if (user.password === password) { | |
| return user | |
| } | |
| } | |
| } | |
| const checkRole = (req, res, next) => { | |
| if (req.role === "admin") { | |
| next() | |
| } else { | |
| res.status(403).send('you\'re not authorized') | |
| } | |
| } | |
| app.use(express.json()) | |
| app.use((req, res, next) => { | |
| const user = authenticate(req.body) | |
| if (user) { | |
| req.role = user.role | |
| next() | |
| } else { | |
| res.status(403).send('you\'re not authenticated') | |
| } | |
| }) | |
| app.post('/login', checkRole, (req, res) => { | |
| res.send('welcome user! 😊') | |
| }) | |
| app.listen(PORT, () => console.log(`listening on port ${PORT}`)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment