Error: Uncaught, unspecified "error" event. (Not a valid BCrypt hash.) - javascript

I am trying to create an api for login in nodejs.but when i check the login route via Http requester it showing nothing in output and command line showing error Error: Uncaught, unspecified "error" event. (Not a valid BCrypt hash.) and i find out that password is not stored in database in encrypted/hash form.
The project structure:
server.js file:
var express = require('express');
var app = express();
var port = process.env.PORT||8080;
var morgan = require('morgan');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var router = express.Router();
var appRoutes = require('./app/routes/api')(router);
var path = require('path');
app.use(morgan('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(__dirname + '/public'));
app.use('/api',appRoutes);
mongoose.connect('mongodb://localhost:27017/tutorial', function(err){
if(err) {
console.log('Not connected to the Database: '+ err);
}
else {
console.log('Succesfully connected to Mongodb');
}
});
app.get('*',function(req,res){
res.sendFile(path.join(__dirname + '/public/app/views/index.html'));
});
app.listen(port, function () {
console.log('Running the server on port ' + port);
});
/app/models/user.js:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var bcrypt = require('bcrypt-nodejs');
var UserSchema = new Schema({
username: { type: String, lowercase: true, required: true, unique: true },
password: { type: String, required: true },
email: { type: String, lowercase: true, required: true, unique: true }
});
UserSchema.pre('save', function(next) {
var user = this;
bcrypt.hash(user.password, null, null, function(err, hash) {
if (err) return next(err);
user.password = hash;
next();
});
next();
});
UserSchema.methods.comparePassword = function(password) {
return bcrypt.compareSync(password, this.password);
};
module.exports = mongoose.model('User', UserSchema);
/app/routes/api.js:
var User =require('../models/user');
module.exports = function(router) {
//http://localhost:8080/api/users
//User Registration Route
router.post('/users', function(req,res){
var user = new User();
user.username = req.body.username;
user.password = req.body.password;
user.email = req.body.email;
if (req.body.username == null || req.body.username == '' || req.body.email == null || req.body.email == ''|| req.body.password == null || req.body.password == '' ){
res.send('Ensure Username, Email and Password is provided');
} else {
user.save(function(err){
if(err){
res.send('Username or Email already exist');
}
else {
res.send('User created!!!')
}
});
}
});
//User login Route
//http://localhost:8080/api/authenticate
router.post('/authenticate',function(req,res) {
User.findOne({ username: req.body.username }).select('email username password').exec(function(err,user){
if (err) throw err;
if (!user){
res.json({ success: false, message: 'Could not authenticate user'});
}else if(user){
var validPassword = user.comparePassword(req.body.password);
if(!validPassword){
res.json({ success: false, message: 'Could not authenticate user'});
}else {
res.json({ success: true, message: 'User Authenticate!!!'});
}
}
});
});
return router;
}
HTTP requester (it is working fine for register api in /app/models/api.js){and user is succesfully registered}
Terminal:
Database:(where password is not stored in hash i dont know why maybe this is main problem)

Your code calls next() twice in your pre-save function, remove it as followed:
UserSchema.pre('save', function(next) {
var user = this;
bcrypt.hash(user.password, null, null, function(err, hash) {
if (err) return next(err);
user.password = hash;
next();
});
next(); // function to remove
});

Related

Why can I not create an User?

I´m trying to set up a register and login server with node.js and mongoose. So I have create an user model and an user route. Can someone find the mistake why I can´t create an user. I connect to Postman under POST : localhost:3000/users/register
my user model:
const mongoose = require('mongoose');
const uniqueValidator = require('mongoose-unique-validator');
const bcrypt = require('bcryptjs');
const UserSchema = new mongoose.Schema({
email: {
type: String,
required: true,
minlength: 1,
trim: true, //calls .trim() on the value to get rid of whitespace
unique: true, //note that the unique option is not a validator; we use mongoose-unique-validator to enforce it
},
password: {
type: String,
required: true,
minlength: 8,
},
});
//this enforces emails to be unique!
UserSchema.plugin(uniqueValidator);
//this function will be called before a document is saved
UserSchema.pre('save', function(next) {
let user = this;
if (!user.isModified('password')) {
return next();
}
//we generate the salt using 12 rounds and then use that salt with the received password string to generate our hash
bcrypt
.genSalt(12)
.then((salt) => {
return bcrypt.hash(user.password, salt);
})
.then((hash) => {
user.password = hash;
next();
})
.catch((err) => next(err));
});
module.exports = mongoose.model('User', UserSchema);
my routes user:
const express = require('express');
const bcrypt = require('bcryptjs');
const User = require('../models/user');
const router = express.Router();
//util function to check if a string is a valid email address
const isEmail = (email) => {
if (typeof email !== 'string') {
return false;
}
const emailRegex = /(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")#(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])/;
return emailRegex.test(email);
};
router.post('/register', async (req, res) => {
try {
const { email, password } = req.body;
if (!isEmail(email)) {
throw new Error('Email must be a valid email address.');
}
if (typeof password !== 'string') {
throw new Error('Password must be a string.');
}
const user = new User({ email, password });
const persistedUser = await user.save();
res.status(201).json({
title: 'User Registration Successful',
detail: 'Successfully registered new user',
});
} catch (err) {
res.status(400).json({
errors: [
{
title: 'Registration Error',
detail: 'Something went wrong during registration process.',
errorMessage: err.message,
},
],
});
}
});
router.post('/login', async (req, res) => {
try {
const { email, password } = req.body;
if (!isEmail(email)) {
return res.status(400).json({
errors: [
{
title: 'Bad Request',
detail: 'Email must be a valid email address',
},
],
});
}
if (typeof password !== 'string') {
return res.status(400).json({
errors: [
{
title: 'Bad Request',
detail: 'Password must be a string',
},
],
});
}
//queries database to find a user with the received email
const user = await User.findOne({ email });
if (!user) {
throw new Error();
}
//using bcrypt to compare passwords
const passwordValidated = await bcrypt.compare(password, user.password);
if (!passwordValidated) {
throw new Error();
}
res.json({
title: 'Login Successful',
detail: 'Successfully validated user credentials',
});
} catch (err) {
res.status(401).json({
errors: [
{
title: 'Invalid Credentials',
detail: 'Check email and password combination',
errorMessage: err.message,
},
],
});
}
});
module.exports = router;
my server :
const express = require('express');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const mongoose = require('mongoose');
const dotenv = require("dotenv");
const app = express();
dotenv.config();
//other imports
const usersRoute = require('./routes/users');
//other app.use statements
//connect to db
mongoose.connect(
process.env.DB_CONNECTION,
{ useNewUrlParser: true,
useUnifiedTopology: true},
() => console.log('Database connected')
);
mongoose.Promise = global.Promise;
const port = process.env.PORT || 3000;
//sets up the middleware for parsing the bodies and cookies off of the requests
app.use(bodyParser.json());
app.use(cookieParser());
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
module.exports = { app };
what I only get is this.:
Cannot POST /users/register
You didn't specify the path prefix in your server file. You should define:
app.use("/users", usersRoute );

Getting NodeJS delete route non functioning

I did the registration portion successfully now I am trying to delete the registered user by id . This is how I did
user controller
const mongoose = require ('mongoose');
const User = mongoose.model('User');
module.exports.register = (req, res, next) =>{
var user = new User();
user.fullName = req.body.fullName;
user.email = req.body.email;
user.password = req.body.password;
user.phoneNumber = req.body.phoneNumber;
user.save((err, doc) =>{
if(!err)
res.send(doc);
else{
if (err.code == 11000)
res.status(422).send(["Entered duplicate email address. Please check"]);
else
return next(err);
}
});
}
And in my index router
const express = require ('express');
const router = express.Router();
const ctrlUser = require ('../controllers/user.controller.js');
// routing functions
router.post('/register' , ctrlUser.register);
router.delete('/:userId' , (req, res, next) =>{
User.remove({_id: req.params.userId})
.exec()
.then(result => {
res.status(200).send(["Deleted"]);
})
.catch(err =>{
if (err.code == 500)
res.status(500).send(["Didn't get deleted"]);
else
return next(err);
});
});
module.exports = router;
When I am testing in postman I am not getting any response. Where did I make the mistake ? Something am I missing out ?
EDIT:- Including user.model
const mongoose = require ('mongoose');
const bcrypt = require('bcryptjs');
//define user schema
var userSchema = new mongoose.Schema({
fullName : {
type: String,
required: "Full name can't be empty"
},
email : {
type: String,
required: "Email can't be empty",
unique: true
},
password : {
type: String,
required: "Password can't be empty",
minlength: [6 ,"Password must be atleast 6 character long"]
},
phoneNumber : {
type: String,
required: "Reqired for further contact.Can't be empty"
},
saltSecret: String //this is user for encryption and decryption of password
});
mongoose.model('User', userSchema);

NodeJS : secure some routes with middleware

I have two files : server.js and user.js , I want to secure some routes in user.js with a middle-ware written in server.je.
server.js
// :::::: G E T T H E P A C K A G E W E N E E D : : : : : : : :
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var morgan = require('morgan');
var mongoose = require('mongoose');
var cors=require('cors');
var jwt = require('jsonwebtoken'); // used to create, sign, and verify tokens
var config = require('./config'); // get our config file
// ─── GET an instance of the router for api routes ────────────────────────────────────────────────────────────────────────
var apiRoutes = express.Router();
var users =require('./app/routes/users');
//
// ────────────────────────────────────────────── II ──────────────────────────────────────────────────────────────────────
// :::::: CONFIGURATION : : : : : : : :
var port = process.env.PORT || 1991; // used to create, sign, and verify tokens
mongoose.connect(config.database, { useMongoClient: true }); // connect to database
app.set('superSecret', config.secret); // secret variable
//
// ────────────────────────────────────────────── III ──────────────────────────────────────────────────────────────────────
// :::::: USE BODY PARSER SO WE CAN GET INFO FROM POST AND/OR URL PARAMETERS : : : : : : : :
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// :::::: USE MORGAN TO LOG REQUESTS TO THE CONSOLE: : : :
app.use(morgan('dev'));
app.use(cors());
// ──────────────────────────────────────────────────────────────
// :::::: R O U T E S : : : : : : : :
// ──────────────────────────────────────────────────────────────
// ─── A P I ROUTES ────────────────────────────────────────
// :::::: MIDDLEWARE to secure route begin with /api: : : :
apiRoutes.use(function(req, res, next) {
console.log('hah');
var token = req.body.token || req.query.token || req.headers['x-access-token'];
if (token) {
// verifies secret and checks exp
jwt.verify(token, app.get('superSecret'), function(err, decoded) {
console.log([err,decoded]);
if (err) { //failed verification.
return res.json({"error": true, success:false, message:'Faild to authenticate token'});
}
req.decoded = decoded;
next(); //no error, proceed
});
} else {
// forbidden without token
return res.status(403).send({
success: false,
message: 'No token provided.'
});
}
});
apiRoutes.get('/', function(req, res) {
res.json({ message: 'Welcome to the coolest API on earth!' });
});
app.use('/api', apiRoutes);
app.use('/user', users);
// ──────────────────────────────────────────────────
// :::::: S T A R T the server: : : : : :
app.listen(port);
console.log('Magic happens at http://localhost:' + port);
user.js
const express=require('express');
const router=express.Router();
const passport= require('passport');
const jwt=require('jsonwebtoken');
var userRoutes = express.Router();
var config = require('../../config'); // get our config file
var User = require('../../app/models/User'); // get our mongoose model
//
// ─── ROUTE TO REGISTER USER ──────────────────────────────────────────────────────────────────────
//
userRoutes.post('/signup', function(req, res) {
if (!req.body.email || !req.body.password || !req.body.firstname || !req.body.lastname || !req.body.gender || !req.body.isTrainer) {
res.json({ success: false, msg: 'set up required fields' });
} else {
var newUser = new User({
email: req.body.email,
password: req.body.password,
firstname: req.body.firstname,
lastname: req.body.lastname,
gender: req.body.gender,
isTrainer: req.body.isTraine
});
User.find({ email: req.body.email}, function(err, user){
if (err) {
res.send({ success: false, msg:'authentication error'})
}
else if (user.length != 0) {
res.send({success: false, msg:'Email already exists'})
console.log(user);
}else {
// save the user
newUser.save(function(err) {
if (err) {
console.log(err);
}else {
res.send({ success: true, msg: 'Your account created successfully! ' });
}
});
}
})
}
});
userRoutes.post('/signin', function(req, res) {
User.findOne({
email: req.body.email
}, function(err, user) {
if (err) throw err;
if (!user) {
res.send({ success: false, msg: 'Check your email' });
} else {
// check if password matches
user.comparePassword(req.body.password, function(err, isMatch) {
if (isMatch && !err) {
// if user is found and password is right create a token
var token = jwt.sign(user, config.secret,{
expiresIn: 0
});
// return the information including token as JSON
res.json({
success: true,
token: token,
username: user.username
});
} else {
res.send({ success: false, msg: 'Check your password!' });
}
});
}
});
});
userRoutes.get('/users', function(req, res) {
User.find({}, function(err, users) {
res.json(users);
});
});
module.exports= userRoutes;
I want to secure the /user/users with the middle-ware so only user with token can access to. some suggestion please to do that or to change code structure
I would create a helper module that looks like this (e.g. auth.js):
module.exports=function(req,res,next){
//check user
if(valid){
next();
}else{
res.end("auth error");
}
};
So you can simply do this everywhere:
app.use("/top-secret",require("auth.js"));
app.get("/top-secret/main",...);
If you extend the helper module with some closures, it gets realy useful, e.g.:
module.exports.minLevel=function(level){
return function(req,res,next){
if(validUser && level<=user.level){
next();
}else{
res.end("auth error");
}
};
};
Use case
app.use("/admin",require("auth.js").minLevel(5));

NodeJS doesn't like passport + sequelize logins

I'm going crazy with nodejs. I'm trying to realize the backend for a simple user management webapp powered by NodeJS, using Passport-Local and Sequelize libraries. Right now I just designed the user model. The main problem I have is that the signup process gives me an error: it looks like that I'm working on an undefined object. Could please someone help me in figuring out what's going on?
Here is my code (merged with some solutions I found on internet - obviously nothing works, according to Murphy's laws).
Could please Javascript programmers forgive me if the code is not good. My excuse is that it is my first programming attempt in Javascript, I MUST do it for a project and last (excuse) but not least I grew up with C and microchips.
ERROR:
TypeError: Cannot read property 'findOne' of undefined
at Strategy._verify (/home/me/Documents/cerbero/config/passport.js:21:17)
app.js
var app = express();
//blabla favicon stuff
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({ secret:'holaholaholaholaholaholahola',
resave:true,
saveUninitialized:true
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
var models = require("./models")
require('./config/passport.js')(passport, models.usermodel);
app.use('/', index);
app.use('/user', require('./routes/users')(passport));
models.sequelize.sync().then(function(){
console.log("Database connected");
}).catch(function(err) {
console.log(err, "Somenthing went wrong with the dbdbdb");
});
//blabla listening stuff
module.exports = app;
models/usermodel.js
module.exports = function(sequelize, Sequelize) {
var User = sequelize.define('user', {
id: {
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
username: {
type: Sequelize.TEXT
},
public_key: {
type: Sequelize.TEXT
},
email: {
type: Sequelize.STRING,
validate: {
isEmail: true
}
},
password: {
type: Sequelize.STRING,
allowNull: false
},
last_login: {
type: Sequelize.DATE
},
});
return User;
}
routes/users.js
var express = require('express');
module.exports = function(passport, user) {
var router = express.Router();
//blablabla other routes
router.get('/signup', function(req,res,next) {
res.render('signup', {message: req.flash('signupMessage')});
});
router.post('/signup', passport.authenticate('local-signup', {
successRedirect: '/user/dashboard',
failureRedirect: '/user/signup'}
));
router.post('/login', passport.authenticate('local'), function(req, res) {
res.redirect('/');
});
return router;
};
function isLogged(req, res, next) {
if (req.isAuthenticated())
return next();
res.redirect('/');
};
EDIT
I forgot passport strategy.
passport.js
var bCrypt = require('bcrypt-nodejs');
module.exports = function(passport, user) {
var User = user;
var LocalStrategy = require('passport-local').Strategy;
console.log('debug: sono nella routine');
passport.use('local-signup', new LocalStrategy(
{
usernameField: 'email',
passwordField: 'password',
passReqToCallback: true
},
function(req, email, password, done) {
User.findOne({
where: {
email: email
}
}).then(function(user) {
if (user) {
return done(null, false, {message: req.flash('email already taken')});
console.log('mail already taken');
}
else {
var pass = generateHash(password);
var data =
{
email: email,
password: pass,
username: req.body.username,
public_key: '0',
last_login: null
};
User.create(data).then(function(newUser, created) {
if (!newUser) {
return done(null, false);
}
if (newUser) {
return done(null, newUser, {message: req.flash('tappost')});
}
next();
});
}
});
}
));
passport.deserializeUser(function(id, done) {
User.findById(id).then(function(user) {
if (user) {
done(null, user.get());
} else {
done(user.errors, null);
}
});
});
passport.serializeUser(function(user,done) {
done(null, user.id);
});
var generateHash = function(password) {
return bCrypt.hashSync(password, bCrypt.genSaltSync(8), null);
};
Problem solved.
"Just" changed how to reference the model in passport.js as follow
var User = user;
had to rewritten as
var User = db.user;
Here the definitive passport strategy file
const db = require('./../models/');
var bCrypt = require('bcrypt-nodejs');
module.exports = function(passport) {
var User = db.user;
var LocalStrategy = require('passport-local').Strategy;
passport.use('local-signup', new LocalStrategy(
{
usernameField: 'email',
passwordField: 'password',
passReqToCallback: true
},
function(req, email, password, done) {
var generateHash = function(password) {
return bCrypt.hashSync(password, bCrypt.genSaltSync(8), null);
};
User.findOne({
where: {
email: email
}
}).then(function(user) {
if (user) {
return done(null, false, {message: req.flash('email already taken')});
console.log('mail already taken');
}
else {
var pass = generateHash(password);
var data =
{
email: email,
password: pass,
username: req.body.username,
public_key: '0',
last_login: null
};
User.create(data).then(function(newUser, created) {
if (!newUser) {
return done(null, false);
}
if (newUser) {
return done(null, newUser, {message: req.flash('tappost')});
}
});
}
}).catch(function(err) {
console.log(err);
});
}
));
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
User.findById(id).then(function(user){
done(null, user);
}).catch(function(e){
done(e, false);
});
});
}

express js cannot GET /page

I am very stuck with a routing error on express.js. I am using jade to render my page views. I have read all the docs and refactored many times to no avail.
This is the plain contents of the link that is pointing to the '/sell' route.
index.jade
include layout
html
button.btn.btn-primary(type='submit', href='/sell') Add Item
When clicking this button the browser returns the following as a 404:
Cannot GET /sell
The problem here is that all other routes work correctly, if you are to modify the above href to other pages i.e. '/' , '/sign_in', etc no error occurs. The problem appears to be isolated to the '/sell' route.
The controller with the '/sell' route is below:
server.js
var dotenv = require('dotenv');
dotenv.load();
var session = require('express-session')
var nodemailer = require('nodemailer');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var bcrypt = require('bcrypt');
var async = require('async');
var crypto = require('crypto');
var cookieParser = require('cookie-parser');
var flash = require('express-flash');
var express = require('express');
var app = express();
var mongoose = require('mongoose');
var root = __dirname;
var path = require('path');
var User = require('./models/user');
var bodyParser = require('body-parser');
var errorHelper = require('mongoose-error-helper').errorHelper;
var validator = require('validator');
var Item = require("./models/item")
var username, email, password, owner, product_name, condition, details, price;
mongoose.connect(process.env.MONGODB_CONGO_DEV);
// Middleware
app.set('views', 'app/views');
app.set('view engine', 'jade');
app.set('port', process.env.PORT || 3000);
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true}));
app.use(cookieParser());
app.use(session( {
secret: 'session secret key',
resave: false,
saveUninitialized: true
}));
app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
// Routing
app.get('/', function(req,res) {
res.render('index', {
title: 'Congo',
message: 'Congo',
user: req.user
});
});
app.get('/sell', function(req,res) {
res.render('item', {
title: 'Congo - Sell',
message: 'Sell',
user: req.user
});
});
app.get('/sign_in', function(req,res) {
res.render('sign_in', {
title: 'Congo',
message: 'sign in motherfucker',
user: req.user
});
});
app.post('/sign_in', function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err) return next(err)
if (!user) {
req.flash('error', 'Incorrect login details');
return res.redirect('/sign_in')
};
req.logIn(user, function(err) {
if (err) return next(err);
res.
return res.redirect('/');
});
})(req, res, next);
});
app.get('/sign_up', function(req, res) {
res.render('sign_up', {
title: 'Congo',
message: 'sign up',
user: req.user
});
});
app.post('/sign_up', function(req, res) {
var user = new User({
username: req.body.username,
email: req.body.email,
password: req.body.password
});
if (req.body.confirm != req.body.password) {
req.flash('error', 'Password do not match')
res.redirect('/sign_up')
};
else if (validator.isEmail(req.body.email) === false) {
req.flash('error', 'Invalid email address')
res.redirect('/sign_up')
};
else {
user.save(function(err) {
if (err) {
req.flash('error', 'Email already in use')
res.redirect('/sign_up')
} else {
req.logIn(user, function(err) {
res.redirect('/');
});
}
});
};
});
app.get('/logout', function(req, res){
req.logout();
res.redirect('/');
});
app.get('/forgot', function(req, res) {
res.render('forgot', {
user: req.user,
message: 'you wally'
});
});
app.get('/profile', function(req, res) {
res.render('profile', {
user: req.user,
message: 'User profile'
});
});
app.post('/forgot', function(req, res, next) {
async.waterfall([
function(done) {
crypto.randomBytes(20, function(err, buf) {
var token = buf.toString('hex');
done(err, token);
});
},
function(token, done) {
User.findOne({ email: req.body.email }, function(err, user) {
if (!user) {
req.flash('error', 'No account with that email address exists.');
return res.redirect('/forgot');
};
user.resetPasswordToken = token;
user.resetPasswordExpires = Date.now() + 3600000; // 1 hour
user.save(function(err) {
done(err, token, user);
});
});
},
function(token, user, done) {
var smtpTransport = nodemailer.createTransport('SMTP', {
service: 'Gmail',
auth: {
user: 'harryandrew.dix#gmail.com',
pass: process.env.GMAIL_PASS
};
});
var mailOptions = {
to: user.email,
from: 'passwordreset#demo.com',
subject: 'Node.js Password Reset',
text: 'You are receiving this because you (or someone else) have requested the reset of the password for your account.\n\n' +
'Please click on the following link, or paste this into your browser to complete the process:\n\n' +
'http://' + req.headers.host + '/reset/' + token + '\n\n' +
'If you did not request this, please ignore this email and your password will remain unchanged.\n'
};
smtpTransport.sendMail(mailOptions, function(err) {
req.flash('info', 'An e-mail has been sent to ' + user.email + ' with further instructions.');
done(err, 'done');
});
};
], function(err) {
if (err) return next(err);
res.redirect('/forgot');
});
});
app.get('/reset/:token', function(req,res) {
User.findOne({resetPasswordToken: req.params.token, resetPasswordExpires: { $gt: Date.now()}}, function(err,user) {
if (!user) {
req.flash('error', 'Password reset token invalid or expired.');
return res.redirect('/forgot');
}
res.render('reset', {
user: req.user,
message: 'reset dem pass'
});
});
});
app.post('/reset/:token', function(req, res) {
async.waterfall([
function(done) {
User.findOne({ resetPasswordToken: req.params.token, resetPasswordExpires: { $gt: Date.now() } }, function(err, user) {
if (!user) {
req.flash('error', 'Password reset token is invalid or has expired.');
return res.redirect('back');
};
user.password = req.body.password;
user.resetPasswordToken = undefined;
user.resetPasswordExpires = undefined;
user.save(function(err) {
req.logIn(user, function(err) {
done(err, user);
});
});
});
},
function(user, done) {
var smtpTransport = nodemailer.createTransport('SMTP', {
service: 'Gmail',
auth: {
user: 'harryandrew.dix#gmail.com',
pass: process.env.GMAIL_PASS
};
});
var mailOptions = {
to: user.email,
from: 'passwordreset#demo.com',
subject: 'Your password has been changed',
text: 'Hello,\n\n' +
'This is a confirmation that the password for your account ' + user.email + ' has just been changed.\n'
};
smtpTransport.sendMail(mailOptions, function(err) {
req.flash('success', 'Success! Your password has been changed.');
done(err);
});
};
], function(err) {
res.redirect('/');
});
});
// app.post('/add_item', function(req, res) {
// var item = new Item({
// owner: req.user.id,
// product_name: req.body.product_name,
// condition: req.body.condition,
// details: req.body.details,
// price: req.body.price
// });
// item.save(function(err) {
// if (err) {
// req.flash('error', 'Something went wrong, make sure you are signed in.')
// res.redirect('/add_item');
// } else {
// req.logIn(item, function(err) {
// res.redirect('/user_profile');
// });
// };
// });
// });
var server = app.listen(3000, function() {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s',host,port);
});
item.jade
include layout
html
block content
form(method='POST')
legend(style='font-family: Raleway; font-size: 30px;') Item Details
.form-group
label(for='product_name') Product Name
input.form-control(type='text', name='product_name', placeholder='include product name, brand, condition, colour etc.', required autofocus)
.form-group
label(for='condition') Condition
input.form-control(type='text', name='condition', placeholder='e.g. New, Used', required)
.form-group
label(for='image') Image
input.form-control(type='file', name='image')
.form-group
label(for='details') Details
textarea.form-control(name='details', cols='40', rows='5')
.form-group
label(for='price') Price
.input-group
.input-group-addon £
input.form-control(type='text', placeholder='Amount', required)
.input-group-addon .00
br
br
button#btnSubmit.btn.btn-primary(type='submit') Post Item
I think it's acting as form post and tries to reach app.post('/sell')
Change it:
button.btn.btn-primary(type='submit', href='/sell') Add Item
to:
a.btn.btn-primary(href='/sell') Add Item
also remove some parts of middleware and keep only these lines:
app.set('views', 'app/views');
app.set('view engine', 'jade');
app.set('port', process.env.PORT || 3000);
app.use(logger('dev'));
and then navigate in Your browser to /sell route, check if it's working.
if Yes - so problem with one of middlewares that we have deleted to check.
You should add a logger middleware and see what error the server gives when you try to go to that route. Another thing to try would be to rename the sell route and see if that works. That could indicate a conflict with another one of your routes, although it's not clear where this would be from looking at your code.

Categories