Passport and Mongoose Issue - node.js

Hi I have this models:
user.js
// app/models/user.js
// load the things we need
var Schema = require('mongoose').Schema;
var bcrypt = require('bcrypt-nodejs');
var db = require('mongoose');
// define the schema for our user model
// create the model for users and expose it to our app
module.exports = function(app){
var userSchema = Schema({
local : {
email : String,
password : String,
},
facebook : {
id : String,
token : String,
email : String,
name : String
},
twitter : {
id : String,
token : String,
displayName : String,
username : String
},
google : {
id : String,
token : String,
email : String,
name : String
}
});
// methods ======================
// generating a hash
userSchema.methods.generateHash = function(password) {
return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
};
// checking if password is valid
userSchema.methods.validPassword = function(password) {
return bcrypt.compareSync(password, this.local.password);
};
return db.model('User', userSchema);
};
post.js
var db = require('mongoose');
module.exports = function(app){
var Schema = require('mongoose').Schema;
var post = Schema({
title: String,
private: Boolean,
text: String,
tags: [],
createdAt: { type: Date, default: Date.now }
});
return db.model('post', post);
};
And a passport config file:
// config/passport.js
// load all the things we need
var db = require('../config/db_connect')();
var LocalStrategy = require('passport-local').Strategy;
// load up the user model
var User = db.model('User');
// expose this function to our app using module.exports
module.exports = function(passport) {
// =========================================================================
// passport session setup ==================================================
// =========================================================================
// required for persistent login sessions
// passport needs ability to serialize and unserialize users out of session
// used to serialize the user for the session
passport.serializeUser(function(user, done) {
done(null, user.id);
});
// used to deserialize the user
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
// =========================================================================
// LOCAL SIGNUP ============================================================
// =========================================================================
// we are using named strategies since we have one for login and one for signup
// by default, if there was no name, it would just be called 'local'
passport.use('local-signup', new LocalStrategy({
// by default, local strategy uses username and password, we will override with email
usernameField : 'email',
passwordField : 'password',
passReqToCallback : true // allows us to pass back the entire request to the callback
},
function(req, email, password, done) {
// asynchronous
// User.findOne wont fire unless data is sent back
process.nextTick(function() {
// find a user whose email is the same as the forms email
// we are checking to see if the user trying to login already exists
User.findOne({ 'local.email' : email }, function(err, user) {
// if there are any errors, return the error
if (err)
return done(err);
// check to see if theres already a user with that email
if (user) {
return done(null, false, req.flash('signupMessage', 'That email is already taken.'));
} else {
// if there is no user with that email
// create the user
var newUser = new User();
// set the user's local credentials
newUser.local.email = email;
newUser.local.password = newUser.generateHash(password);
// save the user
newUser.save(function(err) {
if (err)
throw err;
return done(null, newUser);
});
}
});
});
}));
};
And at least my app.js
var express = require('express')
, load = require('express-load')
, bodyParser = require('body-parser')
, cookieParser = require('cookie-parser')
, passport = require('passport')
, flash = require('connect-flash')
, mongoose = require('mongoose')
, session = require('express-session')
, app = express();
require('./config/passport')(passport);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(cookieParser('blog'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
// required for passport
app.use(session({
secret: 'appsecret',
resave: false,
saveUninitialized: true,
cookie: {
secure: true,
maxAge: new Date(Date.now() + 3600000)
}
}));
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session
app.use(express.static(__dirname + '/public'));
load('models')
.then('controllers')
.then('routes')
.into(app);
require('./routes/login.js')(app, passport);
app.listen(3030, function(){
console.log("Blog no ar.");
});
But when i try to run my app, I got an exception:
/home/caio/workspace/personal-blog/node_modules/mongoose/lib/index.js:323
throw new mongoose.Error.MissingSchemaError(name);
^
MissingSchemaError: Schema hasn't been registered for model "User".
Use mongoose.model(name, schema)
at Mongoose.model (/home/caio/workspace/personal-blog/node_modules/mongoose/lib/index.js:323:13)
at Object.<anonymous> (/home/caio/workspace/personal-blog/config/passport.js:10:15)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object.<anonymous> (/home/caio/workspace/personal-blog/app.js:13:1)
I am registering my user model, but mongoose is not recognizing, anyone can help me?

In your app.js, load mongoose first before express.
var mongoose = require('./config/mongoose'),
express = require('./config/express');
var db = mongoose();
var app = express();
And don't forget to register the model. your code should be
return db.model('User', userSchema);

Okay, a mongoose Model requires a schema.
Instead of:
var User = db.model('User');
Do something like:
var Schema = require('mongoose').Schema
var userSchema = new Schema({
name: {
type: String,
default: 'hahaha'
}
});
var User = db.model('User', userSchema);

Related

passportjs local connectflash not working with ejs

I have a project using passportjs fully working, but not showing flash messages.
The passportjs file looks like this:
passport.use('local-login', new LocalStrategy({
// by default, local strategy uses username and password, we will override with email
usernameField: 'email',
passwordField: 'password',
passReqToCallback: true // allows us to pass in the req from our route (lets us check if a user is logged in or not)
},
function (req, email, password, done) {
if (email) {
email = email.toLowerCase()
} // Use lower-case e-mails to avoid case-sensitive e-mail matching
// asynchronous
process.nextTick(function () {
User.findOne({ 'local.email': email }, function (err, user) {
// if there are any errors, return the error
if (err) {
console.log(err)
return done(err)
}
// if no user is found, return the message
if (!user) {
console.log('No user found')
return done(null, false, req.flash('message', 'No user found'))
}
My routes.js file looks like this:
// Login
app.get('/login', function (req, res) {
console.log('login get')
res.render('pages/login', {message: req.flash('messsage')})
})
my login.ejs file looks like this:
<%if (message) {%>
<%=message%>
<%}%>
I have no idea why it isn't working?
Here comes my server.js if it is any problem related to includes:
var express = require('express')
var mongoose = require('mongoose')
var passport = require('passport')
var path = require('path')
var ejs = require('ejs') // Not used?
var fs = require('fs') // Not used?
const session = require('express-session')
const MongoStore = require('connect-mongo')(session)
// Reads .env variables for encrypted data
require('dotenv').config()
var port = process.env.PORT || 8080
var db = process.env.MONGO_URI
mongoose.connect(db) // connect to our database
var app = express()
app.set('views', './views')
app.set('view engine', 'ejs')
// GET /public/style.css etc.
app.use(express.static(path.join(__dirname, '/public')))
var bodyParser = require('body-parser')
app.use(bodyParser.urlencoded())
app.use(session({
secret: 'hakunamatata',
store: new MongoStore({
mongooseConnection: mongoose.connection,
saveUninitialized: false,
resave: false
})
}))
var flash = require('connect-flash')
app.use(flash())
var initPassport = require('./app/authentication/passport')
initPassport(passport)
app.use(passport.initialize())
app.use(passport.session()) // persistent login sessions
require('./app/routes/routes')(app, passport)
app.listen(port)
console.log('Dev port is: ' + port)
I tested with:
req.flash('loginMessage', 'No user found')
instead of:
req.flash('message', 'No user found')
and on the routes.js file:
{message: req.flash('loginMessage')}
instead of:
{message: req.flash('message')}
And now it works... I dont know what made the difference, but I hope this can help someone else in the future..

How to make API call using API token in Node.js using express, passport-local

I'm a newbie in Node.js and trying to use API token to access Grafana.
And I created one API token by following instruction from Grafana page.
However, I don't know how to make API calls from my code of node.js to access my local server of grafana page. Also, I have a local login-page by using mongoDB to manage users.
How can I make Node.js API calls to access my local server of grafana page?
Please help me out here.. I'm having hard time on this..
If you want me to show code, I can edit here..
EDIT:
This is my whole code for app.js
var io = require('socket.io');
var express = require('express');
var app = express();
var redis = require('redis');
var sys = require('util');
var fs = require('fs');
//Added for connecting login session
var http = require('http');
var server = http.createServer(app);
var path = require('path');
var mongoose = require('mongoose');
var passport = require('passport');
var session = require('express-session');
var flash = require('connect-flash');
var async = require('async');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
//Adding grafana
var request = require('request');
//Connecting Database (MongoDB)
mongoose.connect("my mongoDB private address");
var db = mongoose.connection;
db.once("open",function () {
console.log("DB connected!");
});
db.on("error",function (err) {
console.log("DB ERROR :", err);
});
//Setting bcrypt for password.
var bcrypt = require("bcrypt-nodejs");
//Setting userSchema for MongoDB.
var userSchema = mongoose.Schema({
email: {type:String, required:true, unique:true},
password: {type:String, required:true},
createdAt: {type:Date, default:Date.now}
});
userSchema.pre("save", function (next){
var user = this;
if(!user.isModified("password")){
return next();
} else {
user.password = bcrypt.hashSync(user.password);
return next();
}
});
//setting bcrypt for password.
userSchema.methods.authenticate = function (password) {
var user = this;
return bcrypt.compareSync(password,user.password);
};
//Setting User as userSchema.
var User = mongoose.model('user',userSchema);
io = io.listen(server);
//Setting middleware for login format.
app.set("view engine", 'ejs');
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
app.use(methodOverride("_method"));
app.use(flash());
app.use(session({secret:'MySecret', resave: true, saveUninitialized: true}));
app.use(passport.initialize());
app.use(passport.session());
//Initializing passport.
passport.serializeUser(function(user, done) {
//console.log('serializeUser()', user);
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
//console.log('deserializeUser()', user);
User.findById(id, function(err, user) {
done(err, user);
});
});
var username_tmp = '';
var global_username = ''; //Global variable for username to put in the address
var pass = '';
//Initializing passport-local strategy.
var LocalStrategy = require('passport-local').Strategy;
passport.use('local-login',
new LocalStrategy({
usernameField : 'email',
passwordField : 'password',
passReqToCallback : true
},
function(req, email, password, done) {
User.findOne({ 'email' : email }, function(err, user) {
if (err) return done(err);
if (!user){
req.flash("email", req.body.email);
return done(null, false, req.flash('loginError', 'No user found.'));
}
if (!user.authenticate(password)){
req.flash("email", req.body.email);
return done(null, false, req.flash('loginError', 'Password does not Match.'));
}
var email_address = req.body.email;
username_tmp = email_address;
var username = email_address.substring(0, email_address.lastIndexOf("#"));
global_username = username;
pass = req.body.password;
return done(null, user);
});
}
)
);
//Check whether it is logged in or not.
//If it is not logged in(Session is out), it goes to login page
//If it is logged in(Session is still on), it goes directly to status.html
app.get('/', loggedInCheck);
app.get('/login', function (req, res) {
res.render('login/login',{email:req.flash("email")[0], loginError:req.flash('loginError')});
});
//Accessing to MongoDB to check to login or not
app.post('/login',
function (req,res,next){
next();
}, passport.authenticate('local-login', {
successRedirect : '/status',
failureRedirect : '/login',
failureFlash : true
})
);
//Creating new account
app.get('/users/new', function(req,res){
res.render('users/new', {
formData: req.flash('formData')[0],
emailError: req.flash('emailError')[0],
passwordError: req.flash('passwordError')[0]
}
);
});
//Calling status.html
app.get('/status', isLoggedIn, function(req, res){
var user_temp = {user: ''};
user_temp.user = global_username;
res.render('status/status', user_temp);
//res.redirect('/status.html?channel=' + global_username);
});
app.get('/grafana', isLoggedIn, function(req, res){
console.log('Accessing to grafana');
res.redirect('http://localhost:8080');
});
request.get('http://localhost:8080',{
auth: {
bearer: 'TOKEN HERE'
}
});
server.listen(4000);
Edited more
app.get('/grafana', isLoggedIn, function(req, res){
console.log('Accessing to grafana');
var url = 'http://localhost:8080/api/dashboards/db/test';
request.get(url,{
auth: {
bearer: 'API token from Grafana page'
}
});
res.redirect(url);
});
Thank you..
The API calls are made with HTTP requests. You can use the request package from npm.
From the docs:
You use the token in all requests in the Authorization header, like this:
GET http://your.grafana.com/api/dashboards/db/mydash HTTP/1.1
Accept: application/json
Authorization: Bearer eyJrIjoiT0tTcG1pUlY2RnVKZTFVaDFsNFZXdE9ZWmNrMkZYbk
Example (I'm using request-promise but you can use whatever you want):
let request = require('request-promise');
let url = `http://your.grafana.com/api/dashboards/db/mydash`;
//Obviously replace this with your token
let myToken = `eyJrIjoiT0tTcG1pUlY2RnVKZTFVaDFsNFZXdE9ZWmNrMkZYbk`;
request.get(url).auth(null, null, true, myToken).then(res=> { ... });
// or
request.get(url, {
auth: {
bearer: myToken
}
}).then(res=> { ... });

cannot find module '../app/models/user'

im struggled with this problem like more then 40 hours and sill don't know how to solve this, the problem is a little big to explain but i will try my best, im a little newbie with Node.Js and mongo stuffs so forgive me any stupid mistake.
I followed the book Mean Stack and the problem appears when i started this tutorial to do the autentication with auth, i am at the beginning doing the local authentication without any social at the moment.
folder structure
so basicly i set the server like this:
process.env.NODE_ENV = process.env.NODE_ENV || 'development';
var mongoose = require('./config/mongoose');
var express = require('./config/express');
var db = mongoose();
var app = express();
app.listen(3000);
module.exports = app;
console.log("running at port 3000");
this is the ./config/mongoose
var config = require('./config');
var mongoose = require('mongoose');
var connectionString = "mongodb://localhost:27017/ShareIdea"
module.exports = function(){
mongoose.Promise = global.Promise;
var db = mongoose.connect(connectionString);
require('../app/models/user.server.model');
return db;
};
the required user.server model
var mongoose = require('mongoose');
var bcrypt = require('bcrypt-nodejs');
var Schema = mongoose.Schema;
var UserSchema = new Schema({
local : {
email : String,
password : String,
},
facebook : {
id : String,
token : String,
email : String,
name : String
},
twitter : {
id : String,
token : String,
displayName : String,
username : String
},
google : {
id : String,
token : String,
email : String,
name : String
}
/*firstname:String,
lastname:String,
email:String,
username:String,
password:String,
userChoice: {type: String, possibleValues: ['programmer','inovator']}*/
});
UserSchema.methods.generateHash = function(password) {
return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
};
UserSchema.methods.validPassword = function(password) {
return bcrypt.compareSync(password, this.local.password);
};
mongoose.model('User',UserSchema);
here is the express configuration
var config = require('./config');
var express = require('express');
var passport = require('passport');
var flash = require('connect-flash');
var compress = require('compression');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var bodyParser = require('body-parser');
var morgan = require('morgan');
var methodOverride = require('method-override');
var expressLayouts = require('express-ejs-layouts');
module.exports = function(){
var app = express();
**require('./passport')(passport);**
if(process.env.NODE_ENV === 'development')
{
app.use(morgan('dev'));
}
else if(process.env.NODE_ENV === 'production')
{
app.use(compress());
}
app.use(cookieParser());
app.use(bodyParser.urlencoded({
extended:true
}));
app.use(morgan('dev'));
app.use(bodyParser.json());
app.use(methodOverride());
app.use(session({
saveUninitialized: true,
resave: true,
secret: 'aaaaaaa'
}));
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash());
app.set('views', './app/views');
app.set('view engine','ejs');
app.use(expressLayouts);
require('../app/routes/index.server.routes.js')(app,passport);
require('../app/routes/register.server.routes.js')(app,passport);
require('../app/routes/login.server.routes.js')(app,passport);
require('../app/routes/profile.server.routes.js')(app,passport);
app.use(express.static('./public'));
return app;
}
here in the express is where the problems appear, this line is the main problem at the moment: `require('./passport')(passport);
if i put this code it gives me the problem that i mentioned in the title, if not when i do a POST request with my form it never posts, i have this troubles because i set the structures of my code to a MVC structure like the book and want to adapt the authentication in the tutorial to my code to learn a little,
so basicly im passing the passport to my routes like this:`
register route
var register = require('../../app/controllers/register.server.controller');
module.exports = function(app,passport) {
app.route('/register')
.post(function(req,res){
console.log("HY");
passport.authenticate('local-signup', {
successRedirect : '/profile', // redirect to the secure profile section
failureRedirect : '/register', // redirect back to the signup page if there is an error
failureFlash : true // allow flash messages
})})
.get(register.getPage);
};
Register controller
var User = require('mongoose').model('User');
module.exports = {
getPage: function(req,res){
res.render('./pages/register',{ message: req.flash('signupMessage') });
}
};
and to end here is the passport code:
// config/passport.js
// load all the things we need
var LocalStrategy = require('passport-local').Strategy;
// load up the user model
var User = require('../app/models/user');
// expose this function to our app using module.exports
module.exports = function(passport) {
// =========================================================================
// passport session setup ==================================================
// =========================================================================
// required for persistent login sessions
// passport needs ability to serialize and unserialize users out of session
// used to serialize the user for the session
passport.serializeUser(function(user, done) {
done(null, user.id);
});
// used to deserialize the user
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
// =========================================================================
// LOCAL SIGNUP ============================================================
// =========================================================================
// we are using named strategies since we have one for login and one for signup
// by default, if there was no name, it would just be called 'local'
passport.use('local-signup', new LocalStrategy({
// by default, local strategy uses username and password, we will override with email
usernameField : 'email',
passwordField : 'password',
passReqToCallback : true // allows us to pass back the entire request to the callback
},
function(req, email, password, done) {
// asynchronous
// User.findOne wont fire unless data is sent back
process.nextTick(function() {
// find a user whose email is the same as the forms email
// we are checking to see if the user trying to login already exists
User.findOne({ 'local.email' : email }, function(err, user) {
// if there are any errors, return the error
if (err)
return done(err);
// check to see if theres already a user with that email
if (user) {
return done(null, false, req.flash('signupMessage', 'That email is already taken.'));
} else {
// if there is no user with that email
// create the user
var newUser = new User();
// set the user's local credentials
newUser.local.email = email;
newUser.local.password = newUser.generateHash(password);
// save the user
newUser.save(function(err) {
if (err)
throw err;
return done(null, newUser);
});
}
});
});
}));
};
Ps: Sorry for the long post, i hope i can get a explanation since i want to learn more, when i read the book i felt like the mvc structure adapted by the autor was dificult, but anyways thanks a lot.
if you guys want to not look at this i understand and here is the gitProject:git project
Try this in your user.server.model.js file. Instead of just
mongoose.model('User',UserSchema);
Try this below to have it accessible.
module.exports = {
User : mongoose.model('User', UserSchema)
}

User coming as null while authenticating with passport js

I am new to Node/mongodb/passport, trying to authenticate using passport.
here is my auth.js
var User = require('../models/userModel'),
passport = require('passport'),
BasicStrategy = require('passport-http').BasicStrategy,
jwt = require('jsonwebtoken');
passport.use(new BasicStrategy(function(userid, password, done){
User.findOne({ 'userid': userid }, function(err, user){
if(err){
return done(err);
}
if(!user){
return done(null, false);
}
if(!user.verifyPassword(password)){
return done(null, false);
}
return done(null, user);
})
}));
exports.generateToken = function(req, res, next){
req.token = jwt.sign({ id:req.user.userid },'secret key', { expiresInMinutes:120 });
next();
};
exports.respond = function(req, res){
req.status(200).json({
user: req.user,
token:req.token
});
};
exports.isAuthenticated = passport.authenticate('basic', {session:false});
For database, I simply created a user to test in the following way:
db.UserSchema.insert({"userid": "hm", "password":"mm123"})
here is my userModel.js
var mongoose = require('mongoose'),
bcrypt = require('bcrypt-nodejs');
var UserSchema = new mongoose.Schema({
userid: {
type: String,
unique: true,
required: true
},
password: {
type: String,
required: true
},
access_token: String
});
UserSchema.methods.verifyPassword = function(password, cb) {
bcrypt.compare(password, this.password, function(err, isMatch) {
if (err) return cb(err);
cb(null, isMatch);
});
};
module.exports = mongoose.model('User', UserSchema);
when I send a request using postman and debug using node-inspector, user come as null in auth.js and in console
Runtime.getProperties failed.
Error: No scopes
here is the server.js
var express = require('express'),
mongoose = require('mongoose'),
bodyParser = require('body-parser'),
path = require('path'),
passport =require('passport'),
authentication = require('./auth/auth');
var db;
if (process.env.ENV == 'Test') {
db = mongoose.connect('mongodb://localhost/fxtest');
}else{
db = mongoose.connect('mongodb://localhost/fx');
}
var app = express();
var port = process.env.PORT || 3000;
app.listen(port, function(){
console.log('Running on Port using gulp:', port);
});
app.use(passport.initialize());
app.post('/auth',authentication.isAuthenticated,
authentication.generateToken, authentication.respond);
module.exports = app;
Can anyone give me any leads as to what am I missing here??
You're responding with the request object which you can't do. You need to respond on the response object.
Its also worth pointing out, that unless you have a cleanup procedure that needs to happen after you respond, you should use a return with your res object.
exports.respond = function(req, res){
// This is wrong
req.status(200).json({
user: req.user,
token:req.token
});
// This is correct
return res.status(200).json({
user: req.user,
token: req.token,
});
};
I got it resolved. The problem was I had given the collection name as UserSchema, whereas my model name was User. As stated in mongoose docs here:
Mongoose automatically looks for the plural version of your model
name
and so it was looking for users as a collection.

passportjs validate on signup if user already exists

I am trying to create a sign up where the user if already existing in the db is logged into the system, or else a new user is created in the system.
So far I have come up with the following code.
//filename passport-config
var config = require('./config');
var passport = require('passport');
var User = require('./models/user');
var LocalStrategy = require('passport-local').Strategy;
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);
}
// As with any middleware it is quintessential to call next()
// if the user is authenticated
var isAuthenticated = function (req, res, next) {
if (req.isAuthenticated())
return next();
res.redirect('/');
}
passport.use('signup', new LocalStrategy({
passReqToCallback : true
},
function(req, email, password, done) {
findOrCreateUser = function(){
// find a user in Mongo with provided email
User.findOne({'email':email},function(err, user) {
// In case of any error return
if (err){
console.log('Error in SignUp: '+err);
return done(err);
}
// already exists
if (user) {
User.findOne({ 'email' : email },
function(err, user) {
if (!user){
console.log('User Not Found with email '+email);
return done(null, false);
}
// User exists but wrong password, log the error
if (!isValidPassword(user, password)){
console.log('Invalid Password');
return done(null,false);
}
});
} else {
// if there is no user with that email
// create the user
var newUser = new User();
// set the user's local credentials
newUser.email = email;
newUser.password = createHash(password);
// save the user
newUser.save(function(err) {
if (err){
console.log('Error in Saving user: '+err);
throw err;
}
console.log('User Registration succesful');
return done(null, newUser);
});
}
});
};
// Delay the execution of findOrCreateUser and execute
// the method in the next tick of the event loop
process.nextTick(findOrCreateUser);
})
);
my router
router.post('/signup', passport.authenticate('signup', {
successRedirect: '/timeslot',
failureRedirect: '/'
}));
my server.js file
var express = require('express');
var bodyParser = require('body-parser');
var leisure = require('leisure');
var cors = require('cors');
var passport = require('passport');
var config = require('./config');
var passportConfig = require('./passport-config');
var session = require('express-session')
var expressHbs = require('express-handlebars');
var mediaTypes = [
{ contentType: 'application/hal+json' },
{ contentType: 'application/json' },
{ contentType: 'text/html' }
];
var app = express();
/*Handlebars */
app.engine('handlebars', expressHbs({layout: false}) );
app.set('view engine', 'handlebars');
app.use(express.static(__dirname + '/assets'));
app.use(cors(config.settings.cors));
app.use(bodyParser());
app.use(leisure.accept(mediaTypes));
/*sessions */
app.use(session({
secret: 'keyboardSFS23432##!#!#at'
}));
app.use(passport.initialize());
app.use(passport.session());
var routes = require('./routes');
app.use('/', routes.router);
function start () {
var port = process.env.PORT || 3000;
app.listen(port);
console.log('Appoints service started on port ' + port);
}
exports.app = app;
exports.start = start;
The signup route doesn't work at all and I am pretty confused on how to debug this, any suggestions will be appreciated.
Have a look at the excellent article at
http://scotch.io/tutorials/javascript/easy-node-authentication-setup-and-local
and the sample code at
https://github.com/scotch-io/easy-node-authentication (with MongoDB), or
https://github.com/tobilg/easy-node-authentication-redis (with Redis as backend)

Resources