I already looked at the other answers for similar questions, yet none of them worked for me. I two pieces of code, one to test that cookies were working(cookieTest.js), and one to actually use them(users.js). I tried moving the app.use() statements for the session middleware and the cookie middleware to no avail. Any ideas on how to fix this?
users.js
//Mongoose Setup
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
mongoose.connect("MY_DB");
var path = require('path');
var appDir = path.dirname(require.main.filename);
var bodyParser = require('body-parser')
var User = require('../models/user.js');
var passport = require('passport');
var LocalStrategy = require('passport-local');
var uuid = require('node-uuid');
var cookieParser = require('cookie-parser');
//Express Setup
var express = require('express');
var router = express.Router();
var app = express();
var expressValidator = require("express-validator");
var session = require('express-session');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(expressValidator());
app.use(bodyParser.json());
app.use(cookieParser());
app.use(session({secret: '_secret_', cookie: { maxAge: 60 * 60 * 1000 }, saveUninitialized: false, resave: false}))
//Routes
router.get('/register', function(req, res){
res.sendFile(appDir + "/views/register.html");
})
router.post('/register', function(req, res) {
req.check('name', 'Name must be Filled in').notEmpty();
req.check('email', 'Email must be Filled in').notEmpty();
req.check('email', "Invalid Email").isEmail();
req.check('password', 'Password Field must be Filled in').notEmpty();
req.check('password', 'Passwords do not Match').equals(req.body.password2)
var errors = req.validationErrors();
if(errors) res.send(errors)
else{
var newUser = new User({
name: req.body.name,
email: req.body.email,
password: req.body.password,
info: req.body.user_bio
});
User.createUser(newUser, function(err, user){
if(err) throw err;
});
res.redirect('../')
}
})
router.get('/login', function(req, res){
res.sendFile(appDir + "/views/login.html");
})
router.post('/login', function(req, res){
var email = req.body.email;
var candidatePass = req.body.password;
User.findOne({ 'email': email }, 'password id', function (err, user) {
if (err) return handleError(err);
User.checkPassword(candidatePass, user.password, function(err, isMatch){
if(err) throw err;
if(!isMatch) res.end('Password Incorrect!');
else{
req.session.userId = user.id;
res.redirect('../');
}
})
})
})
//Exports
module.exports = router;
When I run this I get the error TypeError: Cannot set property 'userId' of undefined, which means that req.session is undefined. However, when I run this, it works fine
var express = require('express');
var session = require('express-session');
var app = express();
var uuid = require('node-uuid');
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// Use the session middleware
app.use(session({
secret: 'jaredasch',
cookie: { maxAge: 60 * 60 * 1000 },
saveUninitialized: false,
resave: false
}))
// Access the session as req.session
app.get('/', function(req, res, next) {
var sess = req.session
if (sess.uuid) {
res.setHeader('Content-Type', 'text/html');
res.write('<p>Session UUID: ' + sess.uuid + '</p>');
res.write('<p>expires in: ' + (sess.cookie.maxAge / 1000) + 's</p>');
res.write('<form method = \'POST\'action = \'/\'><button type = \'submit\'></form>');
res.end()
} else {
sess.uuid = uuid.v4();
res.setHeader('Content-Type', 'text/html');
res.write('Set Up Session \n')
res.write('<p>Session UUID: ' + sess.uuid + '</p>');
res.end('<p>expires in: ' + (sess.cookie.maxAge / 1000) + 's</p>');
}
})
app.post('/', function(req,res){
req.session.destroy(function(err) {
if(err) throw err;
console.log('Session Destroyed')
})
res.redirect('/');
})
app.listen(3000, function(){
console.log('Listening on Port 3000')
});
Why does this work and the one above not, and how could I fix the one above? How would you reccomend fixing such an issue?
Try using app.use(cookieParser("_secret_")); so that its the same secret as with Express
Related
I am trying to set up a MEAN (mongodb, express, nodejs, angular6(CLI)) app. Trying to post user signup form data to mongo database, but its throwing an error. It is my first MEAN app, trying to learn.
Do I miss something here?
Error: Route.post() requires callback functions but got a [object Undefined]
server.js
Here is server.js file.
var express = require('express');
var bodyParser = require('body-parser');
var path = require('path');
var http = require('http');
var app = express();
var api = require('./server/routes/api');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false}));
app.use(express.static(path.join(__dirname + '/dist/meanshopcart')));
app.use('/api', api);
app.post('/sign-up', api.signup);
app.get('*', function(req, res) {
res.sendFile(path.join(__dirname, '/dist/meanshopcart/index.html'));
});
var port = process.env.PORT || '3000';
app.set('port', port);
var server = http.createServer(app);
//app.listen(port, function(){
// console.log("Server is running..!!");
//});
server.listen(port, function(err){
if(err){
return console.log('something bad happened', err);
}
console.log("Server is running..!!");
});
Routes Folder(routes/api.js)
my routes folder ./server/routes/api.js
var express = require('express');
var router = express.Router();
const mongoose = require('mongoose');
const User = require('../models/users');
const db = 'mongodb://localhost:27017/meanshopapp';
mongoose.connect(db, function(err){
console.log("mongo connection done");
if(err){
console.log("Error.."+err);
}
});
router.get('/', (req, res)=>{
console.log("get api ");
User.find({}, function(err, users) {
if (err) throw err;
// object of all the users
console.log(users);
});
res.send(users);
});
exports.signup = function(req, res, next){
console.log("new user entered");
var newUser = new User();
newUser.name = req.body.name;
newUser.email = req.body.email;
newUser.password = req.body.password;
newUser.phoneNo = req.body.phone;
newUser.address = req.body.address;
newUser.save(function(err){
if(err){
console.log("error saving user");
}
else{
console.log("user inserted");
}
})
};
module.exports = router;
Model
this is my user schema user.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const userSchema = new Schema({
name : { type: String },
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
phoneNo: { type: Number },
address: { type: String }
});
module.exports = mongoose.model('user', userSchema, 'users');
You are using exports and module.exports.
Either you should follow #dimagolovin's answer
OR
module.exports = {router};
and use
`app.use('/api', api.router);
app.post('/sign-up', api.signup);`
Try to change the follwing in ./server/routes/api.js
function signup(req, res, next){
console.log("new user entered");
var newUser = new User();
newUser.name = req.body.name;
newUser.email = req.body.email;
newUser.password = req.body.password;
newUser.phoneNo = req.body.phone;
newUser.address = req.body.address;
newUser.save(function(err){
if(err){
console.log("error saving user");
}
else{
console.log("user inserted");
}
})
};
module.exports = {router, signup};
It should do the work
When im logging in the req.user but i gone undefined and req.isAuthenticated() is False. Maybe I'm doing something wrong, I ran out of ideas.
Also deserializeUser is never called, instead serializeUser still working well.
I also check all other issue, almost of them just rearranged the position of bodyParser and cookieParser but it's not work with my issue.
app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var cors = require('cors')
var mongoose = require('mongoose');
mongoose.Promise = global.Promise;
var session = require('express-session');
var passport = require('passport');
var passportconfig = require('./config/passport')(passport);
var flash = require('connect-flash');
// var index = require('./routes/index');
var wallet = require('./routes/api/walletAPI');
var index = require('./routes/index');
var app = express();
//mongoose connection
mongoose.connect('mongodb://localhost:27017/wallet');
var dbMongo = mongoose.connection;
dbMongo.on('err', console.error.bind(console, 'connect fail'));
dbMongo.once('open', function () {
console.log('mongo connected');
});
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Credentials', true);
res.header('Access-Control-Allow-Origin', req.headers.origin);
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept');
if ('OPTIONS' == req.method) {
res.send(200);
} else {
next();
}
});
//Enable All CORS Requests
// app.use(cors({credentials: true}));
app.use(logger('dev'));
app.use(cookieParser());
const cookieExpirationDate = new Date();
const cookieExpirationDays = 365;
cookieExpirationDate.setDate(cookieExpirationDate.getDate() + cookieExpirationDays);
app.use(session({secret: 'keyboard cat', saveUninitialized: true, resave: true, cookie: {
secure: false,
httpOnly: true,
expires: cookieExpirationDate // use expires instead of maxAge
}}));
app.use(passport.initialize());
app.use(passport.session());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, 'public')));
app.use(function(err, req, res, next) {
console.log(err);
});
app.use(flash());
// app.use('/', index);
app.use('/wallet/api', wallet);
app.use('/', index);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// Session-persisted message middleware
app.use(function(req, res, next){
var err = req.session.error,
msg = req.session.notice,
success = req.session.success;
delete req.session.error;
delete req.session.success;
delete req.session.notice;
if (err) res.locals.error = err;
if (msg) res.locals.notice = msg;
if (success) res.locals.success = success;
next();
});
// 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;
walletAPI.js
var express = require('express');
var router = express.Router();
var walletController = require('../../controller/walletController');
router.post('/login', function (req, res, next) {
var result = walletController.log_in(req, res, next);
req.session.save();
})
walletController.js
var history = require('../models/history');
var wallet = require('../models/wallet');
var md5 = require('md5');
var passport = require('passport');
exports.log_in = passport.authenticate('local-signin', {
successRedirect: '/a',
failureRedirect: '/login',
failureFlash: 'Invalid username or password.',
successFlash: 'Success.'
});
passport.js
var LocalStrategy = require('passport-local').Strategy;
var User = require('../models/wallet');
var md5 = require('md5');
module.exports = function(passport){
//Passport configuration
passport.serializeUser(function(user, done) {
console.log('user:')
console.log(user._id)
done(null, user._id);
});
passport.deserializeUser(function(id, done) {
console.log('id:')
console.log(id)
User.findById(id, function(err, user) {
done(err, user);
});
done(null, id);
});
passport.use('local-signin',new LocalStrategy({
usernameField : 'username',
passwordField : 'password',
passReqToCallback: true,
},
function(req, username, password, done) {
process.nextTick(function () {
User.findOne({'username': username}, function (err, user) {
// console.log(user)
if (err) {
return done(err);
}
if (!user) {
return done(null, false, req.flash('loginMessage', 'No user found.'));
}
else if (user.password !== md5(password)) {
return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.'));
}
return done(null, user);
});
})
}
));
}
When I try to run my code it gives me Reference Error: LocalStrategy is not defined.
This is my first time using node.js and I hit a wall with this. I appreciate the help in advance.
I put all the code in one snippet so you can go through it easily. I have tried other posts for fixes but have been unsuccessful.
/***********
Modules
***********/
//Load the express library
var express = require('express');
//Create a new variable called “app”; we pass on the express() method.
var app = express();
//Set Port
var port = 7878;
var mongoose = require('mongoose'); //Place this on top; Loads mongoose library
var bodyParser = require('body-parser');
var passport = require('passport');
var LocalStratgy = require('passport-local').Strategy;
/*Body parser*///whenever you do a post request from the form, it gets the data through a URL encoded format.
app.use(bodyParser.urlencoded({
extended: true
}));
app.use('/js', express.static(__dirname + '/js'));
/*Initialize Passport*/
app.use(passport.initialize());
app.use(passport.session());
/***********
Database
***********/
/*Database connection - MongoDB*/
//Created from the command earlier. Ensure this is done on the first_db instance
var usr = 'admin';
var pwd = '123456';
var dbHost = 'localhost';
var dbPort = '27017';
var database = 'first_db';
var url = 'mongodb://' + usr + ':' + pwd + '#' + dbHost + ':' + dbPort + '/' + database;
console.log('mongodb connection = ' + url);
mongoose.connect(url, function(err) {
if(err) {
console.log('connection error: ', err);
} else {
console.log('connection successful');
}
});
/***********
Models
***********/
//User model
//Define our fields for the table
var UserSchema = new mongoose.Schema({
user_id: mongoose.Schema.ObjectId,
username: String,
password: String
});
//Create model object
var User = mongoose.model('user', UserSchema);
/***********
Routes
***********/
var bcrypt = require('bcrypt-nodejs'); //should be placed on top
//Renders our html file
app.get('/', function (req, res, next) {
res.sendFile( __dirname + '/index.html');
});
//render register.html when /register is called
app.get('/register', function (req, res, next) {
res.sendFile( __dirname + '/register.html');
});
app.get('/home', function (req, res, next) {
res.sendFile(__dirname + '/home.html');
});
app.post('/login', passport.authenticate('local'),
function(req, res) {
res.redirect('/home');
});
/* Login logic for passport.authenticate*/
passport.use(new LocalStrategy(
function(username, password, done) {
User.findOne({ username: username }, function (err, user) {
if(user !== null) {
var isPasswordCorrect = bcrypt.compareSync(password, user.password);
if(isPasswordCorrect) {
console.log("Username and password correct!");
return done(null, user);
} else {
console.log("Password incorrect!");
return done(null, false);
}
} else {
console.log("Username does not exist!");
return done(null, false);
}
});
}
));
/**********
Serialize and Deserialize here for passport.authenticate
**********/
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser(function(user, done) {
done(err, user);
});
app.post('/register', function (req, res, next) {
var password = bcrypt.hashSync(req.body.password);
req.body.password = password;
User.create(req.body, function(err, saved) {
if(err) {
console.log(err);
res.json({ message : err });
} else {
res.json({ message : "User successfully registered!"});
}
});
});
app.listen(port, '0.0.0.0', function() {
console.log('Server running at port ' + port);
});
The reason is you have defined var LocalStratgy, not LocalStrategy.
You're using it like this-
https://www.npmjs.com/package/passport-local-mongoose#configure-passportpassport-local
// use static authenticate method of model in LocalStrategy
passport.use(new LocalStrategy(User.authenticate()));
// use static serialize and deserialize of model for passport session support
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
But I suggest you to use it like this -
https://www.npmjs.com/package/passport-local-mongoose#simplified-passportpassport-local-configuration
// CHANGE: USE "createStrategy" INSTEAD OF "authenticate"
passport.use(User.createStrategy());
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
I have a node-express app that authenticates user data and upload files using multer, when i click on submit, the name, email, username and password fields are stored in the mongodb database. But the profileimage file is not stored in the uploads folder nor stored by monogdb. I tried using some help i found online but all worked with my app but did not store the picture in the folder nor did mongodb pass the profileimage field in the cli as expected by the model i used. Please What am I not getting right here, that's stopping the file from being uploaded and stored in the required folder and the name of the file being displayed in the mongodb cli?
Note: Other codes that worked fine with my app are commented in the below code sample but none stored the picture in the desired folder.
users.js
var express = require('express');
var router = express.Router();
var multer = require('multer');
var uploads = multer({dest: './uploads/'});
/*var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './uploads/');
},
filename: function (req, file, cb) {
var originalname = file.originalname;
var extension = originalname.split(".");
filename = Date.now() + '.' + extension[extension.length-1];
cb(null, filename);
}
}); */
//Require a model page
var User = require('../models/user');
/* 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': 'Log In'
});
});
//router.post('/register', multer({storage: storage, dest: './uploads/'}).single('profileimage'), function(req,res){
router.post('/register', uploads.single('profileimage'), function(req,res,next){
//Get Form Value
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.file){
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';
}
/*if(req.file){
console.log('uploading File...');
// File Info
originalname = req.files.profileimage.originalname;
feildname = req.files.profileimage.fieldname;
mimetype = req.files.profileimage.mimetype;
path = req.files.profileimage.path;
encoding = req.files.profileimage.encoding;
size = req.files.profileimage.size;
} else {
// Set a Default Image
var original = '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('/');
}
});
module.exports = router;
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 multer = require('multer');
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
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.json());
app.use(bodyParser.urlencoded({ extended: false }));
//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(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 handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
models/user.js
var mongoose = require('mongoose');
//This chooses the database to use for storing data a very important step
mongoose.connect('mongodb://localhost/nodeauth');
var db = mongoose.connection;
//User Schema
var UserSchema = mongoose.Schema({
username: {
type: String,
index: true
},
password: {
type: String
},
email: {
type: String
},
name: {
type: String
},
profileimaage: {
type: String
}
});
var User = module.exports = mongoose.model('User', UserSchema);
module.exports.createUser = function (newUser, callback) {
newUser.save(callback);
}
create multerhelper.js file in your app nd add below code in it
const multer = require('multer');
// const fs = require('fs');
let fs = require('fs-extra');
let storage = multer.diskStorage({
destination: function (req, file, cb) {
let Id = req.body.id;
let path = `tmp/daily_gasoline_report/${Id}`;
fs.mkdirsSync(path);
cb(null, path);
},
filename: function (req, file, cb) {
// console.log(file);
let extArray = file.mimetype.split("/");
let extension = extArray[extArray.length - 1];
cb(null, file.fieldname + '-' + Date.now() + "." + extension);
}
})
var upload = multer({ storage: storage });
let createUserImage = upload.single('images');
let multerHelper = {
createUserImage,
}
module.exports = multerHelper;
in your user.js file import this file
const multerhelper = require("../multerhelper.js");
router.post('/register',multerhelper , function(req,res,next){
Here you are just loading the multer module not using anywhere.
Check the link for full uses :
https://github.com/expressjs/multer
I am new to nodejs and trying to develop nodejs demo application referring this article. I followed all steps
and its first phase is working fine for me. But after adding passport authentication it is not working
here is my app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var passport = require('passport');
//add for Mongo support
//var mongoose = require('mongoose');
var api = require('./routes/api');
var authenticate = require('./routes/authenticate')(passport);
//connect to Mongo
// mongoose.connect('mongodb://localhost:27017/MEAN_Stack');
// require('./models/models.js');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(session({
secret: 'keyboard cat'
}));
//app.use(bodyParser.json());
//app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(passport.initialize());
app.use(passport.session());
//// Initialize Passport
var initPassport = require('./passport-init');
initPassport(passport);
app.use('/api', api);
app.use('/auth', authenticate);
// 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 handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
here is my api.js
var express = require('express');
var router = express.Router();
//Register the authentication middleware
//router.use('/posts');
//api for all posts
router.route('/posts')
//create a new post
.post(function(req, res){
//TODO create a new post in the database
res.send({message:"TODO create a new post in the database rhushikesh"});
})
.get(function(req, res){
//TODO get all the posts in the database
res.send({message:"TODO get all the posts in the database"});
})
//api for a specfic post
router.route('/posts/:id')
//create
.put(function(req,res){
return res.send({message:'TODO modify an existing post by using param ' + req.param.id});
})
.get(function(req,res){
return res.send({message:'TODO get an existing post by using param ' + req.param.id});
})
.delete(function(req,res){
return res.send({message:'TODO delete an existing post by using param ' + req.param.id})
});
module.exports = router;
here is my authenticate.js
var express = require('express');
var router = express.Router();
module.exports = function(passport){
//sends successful login state back to angular
router.get('/success', function(req, res){
res.send({state: 'success', user: req.user ? req.user : null});
});
//sends failure login state back to angular
router.get('/failure', function(req, res){
res.send({state: 'failure', user: null, message: "Invalid username or password1111"});
});
//log in
router.post('/login', passport.authenticate('login', {
successRedirect: '/auth/success',
failureRedirect: '/auth/failure'
}));
//sign up
router.post('/signup', passport.authenticate('signup', {
successRedirect: '/auth/success',
failureRedirect: '/auth/failure'
}));
//log out
router.get('/signout', function(req, res) {
req.logout();
res.redirect('/');
});
return router;
}
here is my passport-init.js
var LocalStrategy = require('passport-local').Strategy;
var bCrypt = require('bcrypt-nodejs');
//temporary data store
var users = {};
module.exports = function(passport){
// Passport needs to be able to serialize and deserialize users to support persistent login sessions
passport.serializeUser(function(user, done) {
console.log('serializing user:',user.username);
return done(null, user.username);
});
passport.deserializeUser(function(username, done) {
return done('we have not implemented this', false);
});
passport.use('login', new LocalStrategy({
passReqToCallback : true
},
function(req, username, password, done) {
if(!users[username]){
console.log('User Not Found with username '+username);
return done(null, false);
}
if(isValidPassword(users[username], password)){
//sucessfully authenticated
return done(null, users[username]);
}
else{
console.log('Invalid password '+username);
return done(null, false)
}
}
));
passport.use('signup', new LocalStrategy({
passReqToCallback : true // allows us to pass back the entire request to the callback
},
function(req, username, password, done) {
// if (users[username]){
// console.log('User already exists with username: ' + username);
// return done(null, false);
// }
//store user in memory
users[username] = {
username: username,
password: createHash(password)
}
console.log(users[username].username + ' Registration successful');
return done(null, users[username]);
})
);
var isValidPassword = function(user, password){
return bCrypt.compareSync(password, user.password);
};
// Generates hash using bCrypt
var createHash = function(password){
return bCrypt.hashSync(password, bCrypt.genSaltSync(10), null);
};
};
When i try to hit the signup api from postman it always redirect to failure api. I also have tried with the debugger but i am not getting the controller over there.
just uncomment following line in app.js
//app.use(bodyParser.json());
//app.use(bodyParser.urlencoded({ extended: false }));
and update passport-init.js
passport.deserializeUser(function(username, done) {
return done('we have not implemented this', false);
});
to
passport.deserializeUser(function(username, done) {
return done(null, users[username]);
});