Last active
December 27, 2018 18:09
-
-
Save anshulrgoyal/e8927797f449ffd2906c109e22bf057b to your computer and use it in GitHub Desktop.
Simple server for verifying json web token
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'); | |
| const jwt=require('jsonwebtoken'); | |
| const user=require('./user'); | |
| const key=require("./key"); | |
| const app=express(); | |
| app.use(require('body-parser').json()); | |
| app.use(function(req,res,next){ | |
| try{ | |
| const token = req.headers.authorization.split(" ")[1] | |
| jwt.verify(token, key.tokenKey, function (err, payload) { | |
| console.log(payload) | |
| if (payload) { | |
| user.findById(payload.userId).then( | |
| (doc)=>{ | |
| req.user=doc; | |
| next() | |
| } | |
| ) | |
| } else { | |
| next() | |
| } | |
| }) | |
| }catch(e){ | |
| next() | |
| } | |
| }) | |
| app.post('/api/auth/signin',function(req,res){ | |
| user.findOne({email:req.body.email}).then((user)=>{ | |
| user.comparePassword(req.body.password,(err,isMatch)=>{ | |
| if(isMatch){ | |
| var token=jwt.sign({userId:user.id},key.tokenKey); | |
| res.status(200).json({ | |
| userId:user.id, | |
| username:user.username, | |
| image:user.image, | |
| name:user.first, | |
| token | |
| }) | |
| } | |
| else{ | |
| res.status(400).json({message:'Invalid Password/Username'}); | |
| } | |
| }) | |
| }).catch((err)=>{ | |
| res.status(400).json({message:'Invalid Password/Username'}); | |
| }) | |
| }) | |
| app.listen("3001"||process.env.PORT,()=>{ | |
| console.log('done.....') | |
| }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment