Last active
February 5, 2022 12:28
-
-
Save iancover/d42d128e8e5ba1fb8e44caf08daf69c1 to your computer and use it in GitHub Desktop.
Node server example using 'query-string' npm pkg.
This file contains 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 queryString = require('query-string'); | |
const app = express(); | |
const USERS = [ | |
{ | |
id: 1, | |
firstName: 'Joe', | |
lastName: 'Schmoe', | |
userName: '[email protected]', | |
position: 'Sr. Engineer', | |
isAdmin: true, | |
password: 'password', | |
}, | |
{ | |
id: 2, | |
firstName: 'Sally', | |
lastName: 'Student', | |
userName: '[email protected]', | |
position: 'Jr. Engineer', | |
isAdmin: true, | |
password: 'password', | |
}, | |
{ | |
id: 3, | |
firstName: 'Lila', | |
lastName: 'LeMonde', | |
userName: '[email protected]', | |
position: 'Growth Hacker', | |
isAdmin: false, | |
password: 'password', | |
}, | |
{ | |
id: 4, | |
firstName: 'Freddy', | |
lastName: 'Fun', | |
userName: '[email protected]', | |
position: 'Community Manager', | |
isAdmin: false, | |
password: 'password', | |
}, | |
]; | |
function gateKeeper(req, res, next) { | |
let params = req.get('x-username-and-password'); | |
const user = params.split(',')[0]; | |
const pwd = params.split(',')[1]; | |
for (var i = 0; i < USERS.length; i++) { | |
console.log(USERS[i].userName, USERS[i].password); | |
} | |
// const {user, pass} = Object.assign( | |
// {user: null, pass: null}, queryString.parse(req.get('x-username-and-password'))); | |
req.user = USERS.find( | |
(usr, index) => usr.userName === user && usr.password === pwd | |
); | |
next(); | |
} | |
app.use(gateKeeper); | |
app.get('/api/users/me', (req, res) => { | |
if (req.user === undefined) { | |
return res | |
.status(403) | |
.json({ message: 'Must supply valid user credentials' }); | |
} | |
const { firstName, lastName, id, userName, position } = req.user; | |
return res.json({ firstName, lastName, id, userName, position }); | |
}); | |
app.listen(process.env.PORT, () => { | |
console.log(`Your app is listening on port ${process.env.PORT}`); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment