Skip to content

Commit

Permalink
Add files via upload
Browse files Browse the repository at this point in the history
  • Loading branch information
ayush-git228 authored Oct 6, 2020
1 parent 6a03736 commit 80c8c1c
Showing 1 changed file with 77 additions and 0 deletions.
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;

0 comments on commit 80c8c1c

Please sign in to comment.