Skip to content

Commit

Permalink
Merge pull request #3 from ayush-git228/main
Browse files Browse the repository at this point in the history
Updated Blog-backend with jwt
  • Loading branch information
anasvakyathodi authored Oct 6, 2020
2 parents 93ff75d + 80c8c1c commit 103a0f3
Show file tree
Hide file tree
Showing 5 changed files with 164 additions and 0 deletions.
64 changes: 64 additions & 0 deletions blog-backend/authenticate.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
var passport=require("passport");
var LocalStrategy=require("passport-local").Strategy;
var User=require("./models/users");
var JwtStrategy=require("passport-jwt").Strategy;
var ExtractJwt=require("passport-jwt").ExtractJwt;
var jwt=require("jsonwebtoken");
var config=require("./config");
const { authenticate } = require("passport");

exports.local=passport.use(new LocalStrategy(User.authenticate()));

passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());

//here user is a JSON object which will create the token and give it to us.to create the token we will use the jsonwebtoken module.
exports.getToken = function(user){
return jwt.sign(user,config.secretKey, // This(jwt.sign) create token ,it takes payload(user) as first parameter and second is the secret key.
{expiresIn:7200})
//Validity:7200 "seconds"
};

var opts={}; // Options

opts.jwtFromRequest=ExtractJwt.fromAuthHeaderAsBearerToken(); // this specify how our json web token should be extracted from the
// incoming request messsge. This extract JWT supports various methods for extracting information from the header.
opts.secretOrKey = config.secretKey;

exports.jwtPassport=passport.use(new JwtStrategy(opts, // Using JwtStrategy to create a new strategy.
(jwt_payload,done)=>{ // Through this done parameter, we will be passing back information to passport which it will then use for loading things onto the request message.
console.log("Jwt Payload: ",jwt_payload);
User.findOne({_id:jwt_payload._id},(err,user)=> //Seraching for the user with given id.
{
if(err)
{
return done(err,false); //This "done" is what passport passes into this strategy.
}
else if(user)
{
return done(null,user); //Second parameter we got from mongoDB. There is no error so first parameter will be null.
}
else{
return done(null,false); // User not found
}
}
)
})
);
// Uses the jwt coming from the authorization header and with that it verifies the user coming.
exports.verifyUser = passport.authenticate("jwt",{session:false}); // So we are not going to create sessions in this case.
// verifyUser calls the passport.authenticate using the jwt strategy anywhere we need to verify the user.
exports.verifyAdmin = function(req, res, next){
if(req.user.admin)
{
next();
return;
}else{
var err = new Error('You are not authorized to perform this operation!');
err.status = 403; // 403 means Forbidden
return next(err);
}
}



4 changes: 4 additions & 0 deletions blog-backend/config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
//This config file use: Store all configuration information about the server. A way of centralizing all the configuration for our server.
module.exports={
"secretKey":"12345-67890-09846-54123" //secret key to sign in our json web token.
}
18 changes: 18 additions & 0 deletions blog-backend/models/users.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
var mongoose=require("mongoose");
var Schema=mongoose.Schema;
var passportLocalMongoose=require("passport-local-mongoose");
var User=new Schema({
username:{
type: String,
default:' '
},
password:{
type: String,
default:' '
},

});
User.plugin(passportLocalMongoose); //Adding passportLocalMongoose as a plugin which will add support to username and storage of hashed password.

//Exporting model with User Schema from this module.
module.exports=mongoose.model("User",User);
77 changes: 77 additions & 0 deletions blog-backend/routes/users.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
var express = require('express');
var User=require("../models/users");
var passport=require("passport");
var authenticate=require("../authenticate");

var router = express.Router();

// GET users listing.
router.get('/', authenticate.verifyUser,function(req,res,next){
User.find({})
.then((users)=>{
res.statusCode=200;
res.setHeader("Content-type","application/json");
res.json(users);

},(err) => next(err))
.catch((err) => next(err));
});

router.post('/signup', (req, res, next) => {
User.register(new User({username: req.body.username}), req.body.password, (err, user) => {

if(err) {
res.statusCode = 500;
res.setHeader('Content-Type', 'application/json');
res.json({err: err});
}
else {
if(req.body.username)
user.username = req.body.username;
if(req.body.password)
user.password = req.body.password;

user.save((err,user)=>{
if(err){
res.statusCode = 500;
res.setHeader('Content-Type', 'application/json');
res.json({err: err});
return ;
}
else{
passport.authenticate('local')(req, res, () => {
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.json({success: true, status: 'Registration Successful!'});

});
}
})
}
});
});

router.post('/login', passport.authenticate('local'),(req, res) => {
// Here we will be issuing token to the user able to authenticate. A soon as we are done with passport.authenticate we are saying user info is present in the req.
var token=authenticate.getToken({_id:req.user._id})

res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');

res.json({success: true,token:token, status: 'You are successfully logged in!'});

});

router.get('/logout', (req, res) => {
if (req.session) {
req.session.destroy();
res.clearCookie('session-id');
res.redirect('/');
}
else {
var err = new Error('You are not logged in!');
err.status = 403;
// next(err);
}
})
module.exports = router;
1 change: 1 addition & 0 deletions blog-backend/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ express.Router().get("/hello", (req, res) => {
res.send("Hello world");
});
app.use("/posts", require("./routes/postRoutes"));
app.use("/users", require("./routes/users"));

// setup mongoose

Expand Down

0 comments on commit 103a0f3

Please sign in to comment.