Skip to content

Instantly share code, notes, and snippets.

@iancover
Last active February 5, 2022 12:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iancover/d42d128e8e5ba1fb8e44caf08daf69c1 to your computer and use it in GitHub Desktop.
Save iancover/d42d128e8e5ba1fb8e44caf08daf69c1 to your computer and use it in GitHub Desktop.
Node server example using 'query-string' npm pkg.
const express = require('express');
const queryString = require('query-string');
const app = express();
const USERS = [
{
id: 1,
firstName: 'Joe',
lastName: 'Schmoe',
userName: 'joeschmoe@business.com',
position: 'Sr. Engineer',
isAdmin: true,
password: 'password',
},
{
id: 2,
firstName: 'Sally',
lastName: 'Student',
userName: 'sallystudent@business.com',
position: 'Jr. Engineer',
isAdmin: true,
password: 'password',
},
{
id: 3,
firstName: 'Lila',
lastName: 'LeMonde',
userName: 'lila@business.com',
position: 'Growth Hacker',
isAdmin: false,
password: 'password',
},
{
id: 4,
firstName: 'Freddy',
lastName: 'Fun',
userName: 'freddy@business.com',
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