Friday 21 April 2017

Local signup strategy not working - redirecting to failure route but cannot work out what the issue is

I'm trying to set up authentication using passport and am starting with my local strategy. However, for some reason signup is failing and I cannot work out what the issue is with my code. Here's my server file:

var express             =       require('express'),
app                     =       express(),
bodyParser              =       require('body-parser'),
mongoose                =       require('mongoose'),
expressSanitizer        =       require('express-sanitizer'),
methodOverride          =       require('method-override'),
passport                =       require('passport'),
flash                   =       require('connect-flash'),
Blog                    =       require('./models/blog'),
Comment                 =       require('./models/comment'),
moment                  =       require('moment'),
session                 =       require('express-session'),
cookieParser            =       require('cookie-parser'),
port                    =       process.env.PORT || 8080;

mongoose.connect('mongodb://localhost/NUFC_blog2');

require('./config/passport')(passport); // pass passport for  configuration

app.use(bodyParser());
app.use(express.static(__dirname + '/public'));
app.use(methodOverride('_method'));
app.use(cookieParser()); // read cookies (needed for auth)

app.set('view engine', 'ejs');

// passport config
app.use(session({ secret: 'toonaresocool'})); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // messages

// routes
require('./routes.js')(app, passport); // load our routes and pass in our app and fully configured passport

// Listening route
app.listen(port);
console.log('Listening on port ' + port);

And here's my signup route:

module.exports = function(app, passport) {

// route for home page
app.get('/', function(req, res) {
    res.render('landing.ejs');
});

// show signup form

app.get('/signup', function(req, res) {
res.render('register.ejs', { message: req.flash('signupMessage') });
});

// process user signup

app.post('/signup', passport.authenticate('local-signup', {
successRedirect     :   '/blogs',
failureRedirect     :   '/signup',
failureFlash        :   true
}));
};

Local strategy:

var LocalStrategy = require('passport-local').Strategy;

var User = require('../models/user');

module.exports = function(passport) {

passport.serializeUser(function(user, done) {
done(null, user.id);
});

passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
    done(err, user);
});
});

// LOCAL SIGNUP STRATEGY

passport.use('local-signup', new LocalStrategy({
usernameField   :'username', 
passwordField   : 'password',
passReqToCallback: true 
},
function(req, username, password, done) {
// asynchronous
// user.findOne won't work unless data is sent back
process.nextTick(function() {
    // find user whose username is same as on form
    // check to see if the user trying to log in already exists
User.findOne({ 'local.username' : username }, function(err, user){
    // if errors return the error
if(err)
    return done(err);
// check to see if there's a user with that username already
if (user) {
    return done(null, false, req.flash('signupMessage', 'That username is already in use'))
} else {
    // if there is no user with the email
    // create new user
    var newUser     = User();
    newUser.local.username = username;
    newUser.local.password = newUser.generateHash(password);

    // save user
    newUser.save(function(err) {
        if(err)
            throw err;
        return done(null, newUser);
    });
}
});     
});
}));
};

Here's my user model:

var mongoose        =           require('mongoose'),
bcrypt                  =           require('bcrypt-nodejs');

var userSchema = mongoose.Schema({

local           : {
    username    : String, 
    password    : String,
    image       : String,
    email       : String
},
});

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);
};
module.exports = mongoose.model('User', userSchema);

And finally my signup form! :

<!doctype html>
<html>
<head>
<title>Node Authentication</title>
<link rel="stylesheet"   href="//netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css">    <!-- load bootstrap css -->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css"> <!-- load fontawesome -->
<style>
    body        { padding-top:80px; }
</style>
</head>
<body>
<div class="container">

<div class="col-sm-6 col-sm-offset-3">

<h1><span class="fa fa-sign-in"></span> Signup</h1>
<!-- show any messages that come back with authentication -->
<% if (message.length > 0) { %>
    <div class="alert alert-danger"><%= message %></div>
<% } %>

<!-- LOGIN FORM -->
<form action="/signup" method="post">
    <div class="form-group">
        <label>Email</label>
        <input type="text" class="form-control" name="email">
    </div>
    <div class="form-group">
        <label>Password</label>
        <input type="password" class="form-control" name="password">
    </div>

    <button type="submit" class="btn btn-warning btn-lg">Signup</button>
</form>

<hr>

<p>Already have an account? <a href="/login">Login</a></p>
<p>Or go <a href="/">home</a>.</p>

</div>

</div>
</body>
</html>

When I try to signup nothing is being added to the db and I just get redirected back to signup, which is my redirect for failure. Any ideas??



via DaveB1

No comments:

Post a Comment