From 43d700c2119e6b2f4878ef7edeb15df4ea556043 Mon Sep 17 00:00:00 2001 From: ayush-git228 <66081505+ayush-git228@users.noreply.github.com> Date: Tue, 6 Oct 2020 20:22:32 +0530 Subject: [PATCH 1/4] Add files via upload --- blog-backend/authenticate.js | 64 ++++++++++++++++++++++++++++++++++++ blog-backend/config.js | 4 +++ 2 files changed, 68 insertions(+) create mode 100644 blog-backend/authenticate.js create mode 100644 blog-backend/config.js diff --git a/blog-backend/authenticate.js b/blog-backend/authenticate.js new file mode 100644 index 0000000..ac0f195 --- /dev/null +++ b/blog-backend/authenticate.js @@ -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); + } +} + + + diff --git a/blog-backend/config.js b/blog-backend/config.js new file mode 100644 index 0000000..bfb9429 --- /dev/null +++ b/blog-backend/config.js @@ -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. +} From 6e71355134bb8693c40a20854b490d3c6c9ed372 Mon Sep 17 00:00:00 2001 From: ayush-git228 <66081505+ayush-git228@users.noreply.github.com> Date: Tue, 6 Oct 2020 20:23:38 +0530 Subject: [PATCH 2/4] Add files via upload --- blog-backend/models/users.js | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 blog-backend/models/users.js diff --git a/blog-backend/models/users.js b/blog-backend/models/users.js new file mode 100644 index 0000000..6ea6ffa --- /dev/null +++ b/blog-backend/models/users.js @@ -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); From 6a03736dd3794bfc0e64d17cf06ed1c12981b93d Mon Sep 17 00:00:00 2001 From: ayush-git228 <66081505+ayush-git228@users.noreply.github.com> Date: Tue, 6 Oct 2020 20:27:03 +0530 Subject: [PATCH 3/4] Add files via upload --- blog-backend/server.js | 1 + 1 file changed, 1 insertion(+) diff --git a/blog-backend/server.js b/blog-backend/server.js index 1459c23..f6beef2 100644 --- a/blog-backend/server.js +++ b/blog-backend/server.js @@ -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 From 80c8c1c3667195bf5777971481b4dd106d848605 Mon Sep 17 00:00:00 2001 From: ayush-git228 <66081505+ayush-git228@users.noreply.github.com> Date: Tue, 6 Oct 2020 20:27:43 +0530 Subject: [PATCH 4/4] Add files via upload --- blog-backend/routes/users.js | 77 ++++++++++++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 blog-backend/routes/users.js diff --git a/blog-backend/routes/users.js b/blog-backend/routes/users.js new file mode 100644 index 0000000..eb9145f --- /dev/null +++ b/blog-backend/routes/users.js @@ -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; \ No newline at end of file