Skip to content

Instantly share code, notes, and snippets.

@JeremyTheModernist
Created September 14, 2020 18:02
Show Gist options
  • Save JeremyTheModernist/ad668584e6eb8922aadb49c7941104e6 to your computer and use it in GitHub Desktop.
Save JeremyTheModernist/ad668584e6eb8922aadb49c7941104e6 to your computer and use it in GitHub Desktop.
A gist for very basic server side authorization
const express = require('express');
const bodyParser = require('body-parser');
const jwt = require('jsonwebtoken');
const app = express();
app.use(bodyParser.json());
const users = [];
app.get('/', (req, res, next) => {
res.send(users.length > 0 ? users : 'please add a user at /adduser');
});
// authenticate the user by checking the name and password
const isAuthenticated = (req, res, next) => {
// check to see if any users exist
if (users.length > 0) {
const isUser = users.find((user) => {
return user.name === req.body.name;
});
if (!isUser) {
throw new Error('user does not exist');
}
// see if this is the correct password
const isAuth = users.find((user) => {
return user.password === req.body.password;
});
if (!isAuth) {
throw new Error('password is incorrect');
}
req.userName = isUser.name;
next();
} else {
throw new Error('You have no users');
}
};
// authorize the user by making sure the token exists and then set that token on the request header
const isAuthorized = (req, res, next) => {
if (users.length > 0) {
// see if this returns true for anyone, because token is set when a user signs in
// then return that user who is signed in
const isSignedIn = users.find((user) => {
return user.token;
});
if (!isSignedIn) {
throw new Error('user is not authorized to access this page');
}
// set the request Authorization header for a user
// typically this would be set by the request object on the client through fetch or axios
// but because this is all on the server, then we manually set it here on the middleware.
req.headers.authorization = `Bearer ${isSignedIn.token}`;
next();
} else {
throw new Error('You have no users');
}
};
// first make POST request for a new user
// this should have a setup like so:
// {
// "name":"Scott",
// "password": "funtimes"
// }
app.post('/adduser', (req, res, next) => {
users.push(req.body);
res.send(`Added the following user: ${JSON.stringify(req.body)}`);
});
// when you login, you should login with an existing user and send the data in the following format
// {
// "name":"Scott",
// "password": "funtimes"
// }
app.post('/login', isAuthenticated, (req, res, next) => {
// store any information I need in the token, that I can then use when it's decoded
const token = jwt.sign(
{ userName: req.userName, message: 'you have successfully signed in!' },
'somesupersecretkey',
{
expiresIn: '1h',
}
);
// you have to use the token to set the "Authorization" header, like so
// req.headers.authorization = `Bearer ${token}`
// but that token has to first be stored somewhere, like local state in react.
// in this case we store the token on the user object, locally in our users array
const user = users.find((user) => {
return user.name === req.userName;
});
// set the token for a user;
user.token = token;
res.send(user);
});
app.get('/profile', isAuthorized, (req, res, next) => {
// once bearer token has been set, then add it to the users array, then use it to validate them
// need to use jwt.verify to verify the auth header.
const authHeader = req.get('Authorization');
const token = authHeader.split(' ')[1];
if (!token || token === '') {
req.isAuth = false;
}
let decodedToken;
try {
decodedToken = jwt.verify(token, 'somesupersecretkey');
} catch (err) {
console.log('YOUR ERROR!', err);
req.isAuth = false;
}
if (!decodedToken) {
req.isAuth = false;
} else {
req.isAuth = true;
}
if (!req.isAuth) {
res.send('User is not authorized to access this route');
return;
}
res.send(`Welcome back, ${decodedToken.userName}`);
});
app.listen(3220, () => {
console.log('listenting on port 3220');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment