Skip to content

Instantly share code, notes, and snippets.

@thebigredgeek
Last active May 19, 2020
Embed
What would you like to do?
JWT Login Example
const express = require('express')
, { json } = require('body-parser')
, jwt = require('jsonwebtoken')
, to = require('await-to-js')
, model = require('./model'); // fake model
// This only lives on the server, never the client!
const JWT_SECRET = process.env.JWT_SECRET;
// create a server instance
const app = express();
// parse json bodies as "req.data"
app.use(json());
// add the login route handler
app.post('/login', async (req, res) => {
const { email, password } = req.data;
let err
, user
, token;
// Validate the email and password, and grab the user if
// the email and password are correct;
[err, user] = await to(model.tryUserLogin(user, password));
if (err) {
return res.status(401).send({
message: "Failed to login with provided credentials"
});
}
// Create a JWT token, encoding the user's primary
// key in the body for easy lookup when the token
// is passed in a subsequent request
[err, token] = await to(jwt.sign({ id: user.id }, JWT_SECRET));
if (err) {
// Handle random failures
// while signing tokens
return res.status(500).send({
message: 'An unknown error has occurred'
});
}
// Return the token in the body
return res.status(200).send({
token
});
});
// listen on port 8080
app.listen(8080);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment