Mongodb -User Validation Failed - javascript

I am learning mongodb, but I am running to this wall, and I don't know how to fix it. Please help! It worked before but this time when I make post request I get this error message in Postman "User validation"
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var bcrypt = require('bcrypt-nodejs');
var UserSchema = new Schema({
name: String,
username: { type: String, required: true, index: { unique: true }},
password: { type: String, required: true, select: false }
});
UserSchema.pre('save', function(next) {
var user = this;
if (!user.isModified('password')) return next();
bcrypt.hash(user.password, null, null, function(err, hash) {
if (err) return next(err);
user.password = hash;
next();
});
});
UserSchema.methods.comparePassword = function(password) {
var user = this;
return bcrypt.compareSync(password, user.password);
};
module.exports = mongoose.model('User', UserSchema);
var express = require('express');
var app = express();
var bodyParser = require("body-parser");
var morgan = require('morgan');
var mongoose = require('mongoose');
var port = process.env.PORT || 8080;
var User = require('./app/models/user');
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(function(req,res,next){
res.setHeader('Acess-control-allow-Origin', '*');
res.setHeader('Acess-control-Allow-Methods', 'GET, POST');
res.setHeader('Acess-Control-Allow-Headers', 'X-Requested-With, content-type,\Authorization');
next();
});
app.use(morgan('dev'));
mongoose.connect('mongodb://localhost:27017/myDatabase');
app.get('/', function(req, res){
res.send('Welcome to thome page');
});
var apiRouter = express.Router();
apiRouter.use(function(req, res, next){
console.log('Somebody just came to our app');
next();
});
apiRouter.get('/', function(req, res){
res.json({message: 'Hooray! Welcome to our api1'});
});
app.use('/api', apiRouter);
apiRouter.route('/users')
.post(function(req,res){
var user = new User();
user.name = req.body.name;
user.username = req.body.username;
user.password = req.body.password;
user.save(function(err){
if(err){
if(err.code == 1000)
return res.json({success: false, message: "A user with that username already exists"});
else
return res.send(err);
}
res.json({message: "User created"});
});
});
app.listen(port);
console.log("Magic happens on port " + port);

I had this problem with postman too.
then i decided to use raw data instead of x-www-form-urlencoded with Json(application/json) header.
In your case you can use it like this :
{"name" : "Holly",
"username" : "Hollylawly",
"password" : "supersecret"}
the image for postman req

I fixed by reinstalling postman.
Thank you guys for taking your time to answer the question.
Thanks.

Related

How to make a route to logout user and delete from mongodb database

Hi I am learning to make a web-based chat app in mean stack
I had defined routes for login and home page and using Angularjs sattelizer method $auth.logout and deleting token from local storage to log out a User,
Now my requirement is as soon as a User logs out I also want to remove User Object from database too,
So please let me know how to make a backend route to log out user
Here is My Server.js code
var express = require('express');
var socketIO = require('socket.io');
var http = require('http');
var bcrypt = require('bcryptjs');
var bodyParser = require('body-parser');
var cors = require('cors');
var jwt = require('jwt-simple');
var moment = require('moment');
var mongoose = require('mongoose');
var path = require('path');
var request = require('request');
var config = require('./config');
var User = require('./models/user');
mongoose.connect(config.db);
var port = process.env.PORT || 3000;
var app = express();
var server = http.createServer(app);
var io = socketIO(server);
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, '../public')));
function isAuthenticated(req, res, next){
if(!(req.headers && req.headers.authorization)){
return res.status(400).send({ message: 'You did not provide a JSON web token in the authorization header' });
}
var header = req.headers.authorization.split(' ');
var token = header[1];
var payload = jwt.decode(token, config.tokenSecret);
var now = moment().unix();
if(now > payload.exp){
return res.status(401).send({ message: 'Token has expired.' });
}
User.findById(payload.sub, function(err, user){
if(!user){
return res.status(400).send({ message: 'User no longer exists.' })
}
req.user = user;
next();
})
};
function createToken(user) {
var payload = {
exp: moment().add(14, 'days').unix(),
iat: moment().unix(),
sub: user._id
};
return jwt.encode(payload, config.tokenSecret);
};
app.get('/', function(req, res){
res.sendFile(path.join(__dirname, '../public', 'index.html'));
});
app.post('/auth/login', function(req, res){
User.findOne({email: req.body.email}, '+password', function(err, user){
if(!user){
return res.status(401).send({message: { email: 'Incorrect email'}});
}
bcrypt.compare(req.body.password, user.password, function(err, isMatch){
if(!isMatch){
return res.status(401).send({message: {password: 'Incorrect password'}});
}
user = user.toObject();
delete user.password;
var token = createToken(user);
res.send({token: token, user: user});
})
})
})
app.post('/auth/signup', function(req, res){
User.findOne({email: req.body.email}, function(err, existingUser){
if(existingUser){
return res.status(409).send({ message: 'Email is already taken'});
}
var user = new User({
email: req.body.email,
password: req.body.password
});
bcrypt.genSalt(10, function(err, salt){
bcrypt.hash(user.password, salt, function(err, hash){
user.password = hash;
user.save(function(){
var token = createToken(user);
res.send({ token: token, user:user });
})
})
})
})
});
app.post('/auth/instagram', function(req, res){
var accessTokenUrl = 'https://api.instagram.com/oauth/access_token';
var params = {
client_id: req.body.clientId,
redirect_uri: req.body.redirectUri,
client_secret: config.clientSecret,
code: req.body.code,
grant_type: 'authorization_code'
};
request.post({ url: accessTokenUrl, form: params, json: true }, function(error, response, body){
if(req.headers.authorization){
User.findOne({ instagramId: body.user.id }, function(err, existingUser){
var token = req.headers.authorization.split(' ')[1];
var payload = jwt.decode(token, config.tokenSecret);
User.findById(payload.sub, '+password', function(err, localUser){
if(!localUser){
return res.status(400).send({message: 'User not found.'});
}
if(existingUser){
existingUser.email = localUser.email;
existingUser.password = localUser.password;
localUser.remove();
existingUser.save(function(){
var token = createToken(existingUser);
return res.send({ token: token, user: existingUser });
})
}else{
localUser.instagramId = body.user.id;
localUser.username = body.user.username;
localUser.fullName = body.user.full_name;
localUser.picture = body.user.profile_picture;
localUser.accessToken = body.access_token;
localUser.save(function(){
var token = createToken(localUser);
res.send({ token: token, user: localUser });
});
}
})
});
} else{
User.findOne({ instagramId: body.user.id }, function(err, existingUser){
if(existingUser){
var token = createToken(existingUser);
return res.send({ token: token, user: existingUser })
}
var user = new User({
instagramId: body.user.id,
username: body.user.username,
fullName: body.user.full_name,
picture: body.user.profile_picture,
accessToken: body.access_token
});
user.save(function(){
var token = createToken(user);
res.send({ token: token, user: user });
});
});
}
});
});
app.get('/api/chat', isAuthenticated, function(req, res){
console.log(User._id);
User.find({}, function(err, users){
var userMap = {};
users.forEach(function(user){
userMap[user] = user;
});
res.send(userMap);
});
});
app.get('/api/logout', isAuthenticated, function(req, res){
});
server.listen(port, function(){
console.log(`server is running on ${port}`);
})
model.js
var mongoose = require('mongoose');
var userSchema = mongoose.model('User', new mongoose.Schema({
instagramId: { type: String, index: true },
email: { type: String, unique: true, lowercase: true },
password: { type: String, select: false },
username: String,
fullName: String,
picture: String,
accessToken: String
}));
module.exports = ('User', userSchema);
You can achieve this by using mongoose findByIdAndRemove. The logged in user must be present in req object. You can access his mongoose object Id by req.user._id. Use the above mentioned method to remove the user by Id.
app.get('/api/logout', isAuthenticated, function(req, res){
console.log('User Id', req.user._id);
User.findByIdAndRemove(req.user._id, function(err){
if(err) res.send(err);
res.json({ message: 'User Deleted!'});
})
});
You can see the documentation from here
we can use .findOneAndRemove() or .findByIdAndRemove() of mongoose
app.get('/api/logout', isAuthenticated, function(req, res){
User.findOneAndRemove({email:email-data}, callback(err, res){})
});
we can send the email or document id from client and replace the hardcoded email

Could not get any response nodejs rest api

I am working on a rest api based on this tutorial from Joshmorony, I keep running on error "Could not get any response" while testing on Postman. I have tied consuming the end points on ionic3 project but still running on the same problem. What am I doing wrong that might be leading to this error? I would appreciate your support.
Here is my code.
In the controller folder controllers/authentication.js
const jwt = require('jsonwebtoken');
const bluebird = require('bluebird');
const nodemailer = require('nodemailer');
const User = require('../models/user');
const authConfig = require('../config/auth');
const crypto = bluebird.promisifyAll(require('crypto'));
/**
* Generating JWT tokens
*
*/
function generateToken(user){
return jwt.sign(user, authConfig.secret, {
expiresIn: 10080
});
}
function setUserInfo(request){
return {
_id: request._id,
email: request.email,
role: request.role
};
}
/**
* Local login authentication
*
*/
exports.login = function(req, res, next){
var userInfo = setUserInfo(req.user);
res.status(200).json({
token: 'JWT ' + generateToken(userInfo),
user: userInfo
});
}
/**
* Local registration
*
*/
exports.register = function(req, res, next){
var email = req.body.email;
var password = req.body.password;
var role = req.body.role;
if(!email){
return res.status(422).send({error: 'You must enter an email address'});
}
if(!password){
return res.status(422).send({error: 'You must enter a password'});
}
User.findOne({email: email}, function(err, existingUser){
if(err){
return next(err);
}
if(existingUser){
return res.status(422).send({error: 'That email address is already in use'});
}
var user = new User({
email: email,
password: password,
role: role
});
user.save(function(err, user){
if(err){
return next(err);
}
var userInfo = setUserInfo(user);
res.status(201).json({
token: 'JWT ' + generateToken(userInfo),
user: userInfo
})
});
});
}
/**
* Roles Creation
*
*/
exports.roleAuthorization = function(roles){
return function(req, res, next){
var user = req.user;
User.findById(user._id, function(err, foundUser){
if(err){
res.status(422).json({error: 'No user found.'});
return next(err);
}
if(roles.indexOf(foundUser.role) > -1){
return next();
}
res.status(401).json({error: 'You are not authorized to view this content'});
return next('Unauthorized');
});
}
}
In the model folder model/User.js
const mongoose = require('mongoose');
const bcrypt = require('bcrypt-nodejs');
var UserSchema = new mongoose.Schema({
email: {
type: String,
lowercase: true,
unique: true,
required: true
},
password: {
type: String,
required: true
},
role: {
type: String,
enum: ['reader', 'creator', 'editor'],
default: 'reader'
},
passwordResetToken: String,
passwordResetExpires: Date,
profile: {
name: String,
gender: String,
location: String,
picture: String
}
}, {
timestamps: true
});
UserSchema.pre('save', function(next){
var user = this;
var SALT_FACTOR = 5;
if(!user.isModified('password')){
return next();
}
bcrypt.genSalt(SALT_FACTOR, function(err, salt){
if(err){
return next(err);
}
bcrypt.hash(user.password, salt, null, function(err, hash){
if(err){
return next(err);
}
user.password = hash;
next();
});
});
});
UserSchema.methods.comparePassword = function(passwordAttempt, cb){
bcrypt.compare(passwordAttempt, this.password, function(err, isMatch){
if(err){
return cb(err);
} else {
cb(null, isMatch);
}
});
}
module.exports = mongoose.model('User', UserSchema);
Routes routes.js
const AuthenticationController = require('./controllers/authentication'),
TodoController = require('./controllers/todo'),
express = require('express'),
passportService = require('./config/passport'),
passport = require('passport');
const requireAuth = passport.authenticate('jwt', {session: false}),
requireLogin = passport.authenticate('local', {session: false});
module.exports = function(app){
var apiRoutes = express.Router(),
authRoutes = express.Router(),
todoRoutes = express.Router();
// Auth Routes
apiRoutes.use('/auth', authRoutes);
authRoutes.post('/register', AuthenticationController.register);
authRoutes.post('/login', requireLogin, AuthenticationController.login);
authRoutes.post('/forgot', AuthenticationController.postForgot);
authRoutes.post('/reset/:token', AuthenticationController.postReset);
authRoutes.post('/account/profile', requireAuth, AuthenticationController.postUpdateProfile);
authRoutes.post('/account/password', requireAuth, AuthenticationController.postUpdatePassword);
authRoutes.get('/protected', requireAuth, function(req, res){
res.send({ content: 'Success'});
});
// Set up routes
app.use('/api', apiRoutes);
}
and lastly app.js file
const express = require('express');
const app = express();
const mongoose = require('mongoose');
const errorHandler = require('errorhandler');
const chalk = require('chalk');
const logger = require('morgan');
const bodyParser = require('body-parser');
const cors = require('cors');
const dotenv = require('dotenv');
const databaseConfig = require('./app/config/database');
const router = require('./app/routes');
/**
* Load environment variables from .env file, where API keys and passwords are configured.
*/
dotenv.load({ path: '.env' });
/**
* Connect to MongoDB.
*/
mongoose.Promise = global.Promise;
mongoose.createConnection(process.env.MONGODB_URI || process.env.MONGOLAB_URI);
mongoose.connection.on('error', (err) => {
console.error(err);
console.log('%s MongoDB connection error. Please make sure MongoDB is running.', chalk.red('✗'));
process.exit();
});
/**
* Express configuration.
*/
app.set('host', process.env.OPENSHIFT_NODEJS_IP || '0.0.0.0');
app.set('port', process.env.PORT || process.env.OPENSHIFT_NODEJS_PORT || 8080);
/**
* Error Handler.
*/
app.use(errorHandler());
/**
* Start Express server.
*/
app.listen(app.get('port'), () => {
console.log('%s App is running at http://localhost:%d in %s mode', chalk.green('✓'), app.get('port'), app.get('env'));
console.log(' Press CTRL-C to stop\n');
});
app.use(bodyParser.urlencoded({ extended: false })); // Parses urlencoded bodies
app.use(bodyParser.json()); // Send JSON responses
app.use(logger('dev')); // Log requests to API using morgan
app.use(cors());
router(app);
I managed to get the error, when I was ruling the app in the terminal I got this error "DeprecationWarning: open() is deprecated in mongoose >= 4.11.0, use openUri() instead, or set the useMongoClient option if using connect() or createConnection(). See http://mongoosejs.com/docs/connections.html#use-mongo-client", when I try to modify mongoose.connect(process.env.MONGODB_URI || process.env.MONGOLAB_URI); to mongoose.createConnection(process.env.MONGODB_URI || process.env.MONGOLAB_URI); thats when I get that error of "Could not get any response". Just opted to go with the old connect(). Hope this will help someone experiencing the same issue.

Login system using Passport.js is always executing “failureRedirect” (nodejs)

I'm doing a tutorial and I'm stuck in the login area. When I'm login in with Passport.js it always executing "failureRedirect" in authenticate.
After trying to debug replacing the router.post('login') route I received the following message:
Error: null User: false Info: {"message":"Missing credentials"}
After Reading on some forums I think that the problem could be related to body-parser. I've been trying to solve the problem but I haven't been able yet. I'd appreciate the help of a most experienced node.js programmer.
The structure of the project is:
app.js
routes:
users.js
models:
user.js
user.js
var express = require('express');
var router = express.Router();
var multer = require('multer');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var bodyParser = require('body-parser');
var User = require('../models/user');
var upload = multer({ dest: './uploads' });
// create application/json parser
var jsonParser = bodyParser.json();
// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false });
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
router.get('/register', function(req, res, next) {
res.render('register', {
title: 'Register'
});
});
router.get('/login', function(req, res, next) {
res.render('login', {
'title': 'Login'
});
});
router.post('/register', upload.single('profileimage'), function (req, res, next) {
//Get Form Values
var name = req.body.name;
var email = req.body.email;
var username = req.body.username;
var password = req.body.password;
var password2 = req.body.password2;
// Check for Image Field
if(req.files && req.files.profileimage){
console.log('Uploading File...');
// File Info
var profileImageOriginalName = req.files.profileimage.originalname;
var profileImageName = req.files.profileimage.name;
var profileImageMime = req.files.profileimage.mimetype;
var profileImagePath = req.files.profileimage.path;
var profileImageExt = req.files.profileimage.extension;
var profileImageSize = req.files.profileimage.size;
} else {
// Set a Default Image
var profileImageName = 'noimage.png';
}
// Form Validation
req.checkBody('name', 'Name field is required').notEmpty();
req.checkBody('email', 'Email field is required').notEmpty();
req.checkBody('email', 'Email not valid').isEmail();
req.checkBody('username', 'Username field is required').notEmpty();
req.checkBody('password', 'Password field is required').notEmpty();
req.checkBody('password2', 'Passwords do not match').equals(req.body.password);
// Check for errors
var errors = req.validationErrors();
if(errors){
res.render('register', {
errors: errors,
name: name,
email: email,
username: username,
password: password,
password2: password2
});
} else {
var newUser = new User({
name: name,
email: email,
username: username,
password: password,
profileImage: profileImageName
});
// Create User
User.createUser(newUser, function (err, user) {
if(err) throw err;
console.log(user);
});
//Success Message
req.flash('success', 'You are now registered and may log in');
res.location('/');
res.redirect('/');
}
});
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
User.getUserById(id, function(err, user) {
done(err, user);
});
});
passport.use(new LocalStrategy(
function (username, password, done) {
User.getUserByUsername(username, function (err, user) {
if(err) throw err;
if(!user){
console.log('Unknown User');
return done(null, false, {message: 'Unknown User'});
}
User.comparePassword(password, user.password, function (err, isMatch) {
if(err) throw err;
if(isMatch){
return done(null, user);
} else {
console.log('Invalid Password');
return done(null, false, {message:'Invalid Password'});
}
});
});
}
));
router.post('/login', jsonParser, passport.authenticate('local', {
successRedirect: '/',
failureRedirect: '/users/login',
failureFlash: true //'Invalid username or password'
}), function (req, res) {
console.log('Authentication Successful');
req.flash('success', 'You are logged in');
res.redirect('/');
});
router.post('/login', passport.authenticate('local', function(err, user, info) {
console.log("authenticate");
console.log(err);
console.log(user);
console.log(info);
}), function (req, res) {
console.log('Authentication Successful');
req.flash('success', 'You are logged in');
res.redirect('/');
});
module.exports = router;
user.js
var mongoose = require('mongoose');
var bcrypt = require('bcrypt');
mongoose.connect('mongodb://localhost/nodeauth');
var db = mongoose.connection;
// User Schema
var UserSchema = mongoose.Schema({
username: {
type: String,
index: true
},
password: {
type: String,
required: true,
bcrypt: true
},
email: {
type: String
},
name:{
type: String
},
profileimage:{
type: String
}
});
var User = module.exports = mongoose.model('User', UserSchema);
module.exports.comparePassword = function(candidatePassowrd, hash, callback) {
bcrypt.compare(candidatePassowrd, hash, function (err, isMatch) {
if(err) return callback(err);
callback(null, isMatch);
});
}
module.exports.getUserById = function (id, callback) {
User.findById(id, callback);
}
module.exports.getUserByUsername = function (username, callback) {
var query = {username: username};
User.findOne(query, callback);
}
module.exports.createUser = function (newUser, callback) {
bcrypt.hash(newUser.password, 10, function (err, hash) {
if(err) throw err;
// Set hashed pw
newUser.password = hash;
// Create User
newUser.save(callback);
});
}
app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var expressValidator = require('express-validator');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var bodyParser = require('body-parser');
var multer = require('multer');
var flash = require('connect-flash');
var mongo = require('mongodb');
var mongoose = require('mongoose');
var db = mongoose.connection;
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// Handle File Uploads
// app.use(multer({dest:'./uploads'}));
var upload = multer({ dest: './uploads' });
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// Handle Express Sessions
app.use(session({
secret: 'secret',
saveUninitialized: true,
resave: true
}));
// Passport
app.use(passport.initialize());
app.use(passport.session());
// Validator
app.use(expressValidator({
errorFormatter: function(param, msg, value) {
var namespace = param.split('.')
, root = namespace.shift()
, formParam = root;
while(namespace.length) {
formParam += '[' + namespace.shift() + ']';
}
return {
param : formParam,
msg : msg,
value : value
};
}
}));
// app.use(expressValidator({
// errorFormatter
// }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(flash());
app.use(function (req, res, next) {
res.locals.messages = require('express-messages')(req, res);
next();
});
app.use('/', routes);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
Files on Dropbox:
https://www.dropbox.com/sh/ex26xxo85lfo0my/AADET-j6Ift0q-y-ecWCRUEba?dl=0
Thanks for your help :)
Please check the code here on https://github.com/rupalipemare/Mongoose-Demo, wherein there is complete example demonstrating passport authentication.
First.. Please try to modularize code. Putting a functionalities in different files can help you track bugs faster. Second why are there two POST calls to login route? Remove the first one and no need to send jsonParser. Yo have declared to serialize and deserialize user. So passport will handle rest.

update is not working mongodb, node.js

I am creating multiplayer game, where I have login system as well. I want to update my user's rating using db.collection.update(), but it is not working. There is no error, just when I write username of my player It says "Unknown User". I write it in my app.js. Besides app.js I have 3 more files for my user.
My app.js
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var flash = require('connect-flash');
var fs = require('fs');
var session = require('express-session');
var mongo = require('mongodb');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/loginapp');
var db = mongoose.connection;
var routes = require('./routes/index');
var users = require('./routes/users');
var User = require('./models/users');
// Init App
var app = express();
var server = require("http").Server(app);
// BodyParser Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
// Express Session
app.use(session({
secret: 'secret',
saveUninitialized: true,
resave: true
}));
User.getUserByRating(rating, function(err)
{
if(err) throw err;
});
});
}));
// Connect Flash
app.use(flash());
// Global Vars
app.use(function (req, res, next) {
res.locals.success_msg = req.flash('success_msg');
res.locals.error_msg = req.flash('error_msg');
res.locals.error = req.flash('error');
res.locals.user = req.user || null;
console.log(req.user);
next();
});
app.use('/', routes);
app.use('/users', users);
User.collection.update(
{ username: "example2" },
{
name: "qq",
rating: 1
}
)
My users.js
var express = require('express');
var router = express.Router();
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var User = require('../models/users');
// Register
router.get('/register', function(req, res){
res.render('register');
});
// Login
router.get('/login', function(req, res){
res.render('login');
});
//Register User
router.post('/register', function(req, res){
var name = req.body.name;
var email = req.body.email;
var username = req.body.username;
var password = req.body.password;
var password2 = req.body.password2;
var rating = req.body.rating;
// Validation
req.checkBody('email', 'Email is required').notEmpty();
req.checkBody('email', 'Email is not valid').isEmail();
req.checkBody('username', 'Username is required').notEmpty();
req.checkBody('password', 'Password is required').notEmpty();
req.checkBody('password2', 'Passwords do not match').equals(req.body.password);
var errors = req.validationErrors();
if(errors)
{
res.render('register',{
errors:errors
});
} else
{
var newUser = new User({
name: name,
email:email,
username: username,
password: password,
rating: 1000
});
User.createUser(newUser, function(err, user){
if(err) throw err;
console.log(user);
});
req.flash('success_msg', 'You are registered and can now login');
res.redirect('/users/login');
}
});
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
User.getUserById(id, function(err, user) {
done(err, user);
});
});
router.post('/login',
passport.authenticate('local', {successRedirect:'/', failureRedirect:'/users/login',failureFlash: true}),
function(req, res) {
res.redirect('/');
});
router.get('/logout', function(req, res){
req.logout();
req.flash('success_msg', 'You are logged out');
res.redirect('/users/login');
});
module.exports = router;
My model(again users.js, but in another folder)
var mongoose = require('mongoose');
var bcrypt = require('bcryptjs');
var UserSchema = mongoose.Schema({
username: {
type: String,
index:true
},
password: {
type: String
},
email: {
type: String
},
name: {
type: String
},
rating:
{
type: Number
}
});
var User = module.exports = mongoose.model('User', UserSchema);
module.exports.createUser = function(newUser, callback){
bcrypt.genSalt(10, function(err, salt) {
bcrypt.hash(newUser.password, salt, function(err, hash) {
newUser.password = hash;
newUser.save(callback);
});
});
}
module.exports.getUserByUsername = function(username, callback){
var query = {username: username};
User.findOne(query, callback);
}
module.exports.getUserByRating = function(rating, callback){
User.findOne({ rating : rating}, callback);
}
module.exports.getUserById = function(id, callback){
User.findById(id, callback);
}
module.exports.comparePassword = function(candidatePassword, hash, callback){
bcrypt.compare(candidatePassword, hash, function(err, isMatch) {
if(err) throw err;
callback(null, isMatch);
});
}
My index.js
var express = require('express');
var router = express.Router();
// Get Homepage
router.get('/', ensureAuthenticated, function(req, res){
res.render('index');
});
function ensureAuthenticated(req, res, next){
if(req.isAuthenticated()){
return next();
} else {
//req.flash('error_msg','You are not logged in');
res.redirect('/users/login');
}
}
module.exports = router;
Thanks a lot in advance. I will be grateful for any help.
Your update code uses raw mongo interface:
User.collection.update(
{ username: "example2" },
{
name: "qq",
rating: 1
}
)
This code replace your document as whole(all missed fields like password and etc will be lost).
You may be want to use followed: {$set: {name: 'qq', rating: 1}}
Or use mongoose interface:
User.update({username: 'example2'}, {name: 'qq', rating: 1});
It will add $set part automatically, if you don't specify safe = false in your model.
Check actual database state before you start to do anything in your code. There are some users incosistent with your model schema, and may be no user with example2 name.

Node JS Json web tokens Router.use() requires middleware function but got a undefined

making a login type thing in Node JS and have attempted to use JSON tokens. Here is server.js:
// dependancies
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var morgan = require('morgan');
var mongoose = require('mongoose');
var passwordHash = require('password-hash');
var jwt = require('jsonwebtoken');
var config = require('./config');
var User = require('./app/models/user');
// config
var port = process.env.PORT || 8080;
mongoose.connect(config.database);
app.set('superSecret', config.secret);
// body parser
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(bodyParser.json());
// morgan
app.use(morgan('dev'));
//routes
app.get('/', function(req, res) {
res.send('Hello! The API is at http://localhost:' + port + '/api');
});
app.get('/setup', function(req, res) {
var hashedPassword = passwordHash.generate('catsanddogs');
var tommy = new User({
user: 'Tommy Birt',
password: hashedPassword,
admin: false,
MP: true,
Position: true
});
// save
tommy.save(function(err) {
if (err) throw err;
console.log('Saved');
res.json({
success: true
});
});
});
// API routes
var apiRoutes = express.Router();
apiRoutes.get('/', function(req, res) {
res.json({
message: 'Welcome to this api.'
});
});
apiRoutes.post('/authenticate', function(req, res) {
// Fine user
User.findOne({
user: req.body.user
}, function(err, user) {
// general error...
if (err) throw err;
// incorrect
if (!user) {
res.json({
success: false,
message: 'Authentication failed: No user'
});
} else if (user) {
if (!passwordHash.verify(req.body.password, user.password)) {
res.json({
success: false,
message: 'Authentication failed: Incorrect Password'
});
} else {
// token!
var token = jwt.sign(user, app.get('superSecret'), {
expiresIn: 64000
});
res.json({
success: true,
message: 'Enjoy your token!',
token: token
});
}
}
})
});
app.use('/api', apiRoutes);
apiRoutes.use(function(req, res, next) {
// Lets find our token!
var token = req.body.token || req.query.token || req.headers['x-access-token'];
// Have we found it?
if (token) {
// Verify! No crackers please
jwt.verify(token, app.get('superSecret'), function(err, decoded) {
if (err) {
// Somethings gone wrong...
return res.json({
sucess: false,
message: 'Failed to authenticate token'
});
} else {
// No errors! Yay :)
req.decoded = decoded
next();
}
});
} else {
// No token Sir! Get off this train!
return res.satus(403).send({
success: false,
message: 'Stop cheating'
});
}
});
apiRoutes.use('/bank', bankRoutes);
var bankRoutes = express.Router();
bankRoutes.get('/balance', function(req, res) {
res.send("Welcome to your balance!");
});
// lets roll
app.listen(port);
console.log('We have taken off at http://localhost' + port);
Basically, whenever I run, without navigating to anything, Its thrown up this error: typeError: Router.use() requires middleware function but got a undefined.
What's happening? Why is this error being thrown?
the problem could be in your bankRoutes -
apiRoutes.use('/bank', bankRoutes);
var bankRoutes = express.Router();
bankRoutes.get('/balance', function(req, res) {
res.send("Welcome to your balance!");
});
you are calling bankRoutes before defining it.
so change it like this (first define it than use it) -
var bankRoutes = express.Router();
bankRoutes.get('/balance', function(req, res) {
res.send("Welcome to your balance!");
});
apiRoutes.use('/bank', bankRoutes);

Categories

Resources