Last active
May 19, 2020 19:48
-
-
Save thebigredgeek/6dd65e77c19b334587624c9c4d47b45a to your computer and use it in GitHub Desktop.
JWT Login Example
This file contains hidden or 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') | |
, { 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