Skip to content

Instantly share code, notes, and snippets.

@harrisonmalone
Created October 1, 2019 02:36
Show Gist options
  • Select an option

  • Save harrisonmalone/51ccbffe4cd4ea8ac3cd9587d8c11ed6 to your computer and use it in GitHub Desktop.

Select an option

Save harrisonmalone/51ccbffe4cd4ea8ac3cd9587d8c11ed6 to your computer and use it in GitHub Desktop.
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