Created
June 7, 2018 04:52
-
-
Save adamgen/d79e3148913bb7ee609fb7c589e94e8e to your computer and use it in GitHub Desktop.
Passport JWT middleware
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 url = require('url'); | |
const router = require('express').Router(); | |
const passport = require('passport'); | |
const jwt = require('jsonwebtoken'); | |
const User = require('../schemas/user'); | |
router.post('/register', (req, res) => { | |
if(!(req.body.email && req.body.password)) return res.status(200).send('no password or email provided'); | |
User.findByEmail(req.body.email, (err, user) => { | |
if(user.length > 0) return res.status(200).send('user with given email exists'); | |
User.make({email: req.body.email, password: req.body.password}, (err, user) => { | |
if(err) return res.status(200).send('can\'t create user'); | |
const token = jwt.sign({email: req.body.email}, 'your_jwt_secret'); | |
return res.json({email: req.body.email, token}); | |
}); | |
}); | |
}); | |
router.post('/login', passport.authenticate('local', {session: false}), (req, res, next) => { | |
const token = jwt.sign({email: req.user.email}, 'your_jwt_secret'); | |
return res.json({email: req.user.email, token}); | |
}, (err, req, res, next) => { | |
return res.send({'status': 'err', 'message': err.message}); | |
}); | |
router.get('/me', (req, res) => { | |
const url_parts = url.parse(req.url, true); | |
const query = url_parts.query; | |
jwt.verify(query.token, 'your_jwt_secret', function(err, decoded) { | |
if(err) return res.status(200).send(err); | |
return res.status(200).send(decoded); | |
}); | |
}); | |
module.exports = router; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for sharing!