Commit 26dfbe9e by Shaik Moses

JWT

parents
ACCESS_TOKEN=a1cf0e9b88b85a81ccfaebf1e7a1a5636fff70d16d9a68ee7c8f6e18985cbac68e6206175f319b0f045ca9554a38039cb11c50b18c92ab46abbd6d19b3904031
REFRESH_ACCESS_TOKEN=1eab8976df88c553a16cecf187fc29c5cd9a16a5665c8571506acdb9d595587afbe76e8e2633fde572a20bb342d91bb4e508c26cb7837b62eedaffe73106d1f4
\ No newline at end of file
/node_modules
const jwt= require("jsonwebtoken")
const authontication=(req,res,next)=>{
const header = req.headers['authorization']
const token = header && header.split(' ')[1]
if(token == null)return res.status(400)
jwt.verify(token,process.env.ACCESS_TOKEN,(err,user)=>{
if(err) return res.status(403)
req.user = user
})
next()
}
module.exports= authontication
\ No newline at end of file
{
"name": "jwt_toots",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "nodemon server.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"dotenv": "^8.2.0",
"express": "^4.17.1",
"jsonwebtoken": "^8.5.1",
"nodemon": "^2.0.7"
}
}
const express = require('express')
const router = express.Router()
const AUTH = require('./authentication.js')
const jwt= require("jsonwebtoken")
const post_data=[
{
name : "cool"
},
{
name:"coool1"
}
]
router.get('/',AUTH,(req,res)=>{
const post=post_data.filter(post=> post.name === req.user.name)
if(post.length == 0){
res.json({message:"this is empty"})
}else{
res.json({data:post_data.filter(post=> post.name === req.user.name)})
}
})
router.post('/login',(req,res)=>{
const name = req.body.name
const user = {name : name}
const access_token=jwt.sign(user,process.env.ACCESS_TOKEN,{expiresIn : '100s'})
res.json({access_token:access_token})
})
module.exports = router
\ No newline at end of file
require('dotenv').config()
const express = require('express')
const app = express()
const jwt = require('jsonwebtoken')
const router = require('./routes.js')
//to parse the data in json
app.use(express.json())
//api for jwt authentication
app.use('/api',router)
//port config
app.listen(3000,()=>console.log("this server is running at 3000"))
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment