Skip to content

Commit

Permalink
BE #1 User registration added
Browse files Browse the repository at this point in the history
  • Loading branch information
tito433 committed May 17, 2020
1 parent 2156a8d commit 67191d1
Show file tree
Hide file tree
Showing 4 changed files with 131 additions and 3 deletions.
31 changes: 31 additions & 0 deletions models/user.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
const mongoose=require('mongoose');
const Schema=mongoose.Schema;

var passportLocalMongoose = require('passport-local-mongoose');

var User = new Schema({
fullname: {
type: String,
default: ''
},
email: {
type: String,
default: ''
}
});

User.plugin(passportLocalMongoose,{
usernameLowerCase:true,
passwordValidator : (password,cb)=>{
if (!password.trim()) {
return cb('Password can not be empty!');
}
else if(password.trim().length<8){
return cb('Password must be at least 8 chars long');
}
// return an empty cb() on success
return cb()
}
});

module.exports = mongoose.model('User', User);
55 changes: 55 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@
"express": "4.16.1",
"mongodb": "^3.5.7",
"mongoose": "^5.9.14",
"morgan": "1.9.1"
"morgan": "1.9.1",
"passport": "^0.4.1",
"passport-local-mongoose": "^6.0.1"
},
"devDependencies": {
"jest": "^26.0.1",
Expand Down
44 changes: 42 additions & 2 deletions routes/users.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,49 @@
var express = require('express');
var router = express.Router();
var User =require('../models/user');

/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
router.get('/', (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.fullname)
user.fullname = req.body.fullname;
if (req.body.email)
user.email = req.body.email;

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


module.exports = router;

0 comments on commit 67191d1

Please sign in to comment.