-
Notifications
You must be signed in to change notification settings - Fork 8
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
6a03736
commit 80c8c1c
Showing
1 changed file
with
77 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
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; |