Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use passport middleware in a controller

Trying to set up passport-local. Used this guide as inspiration.

The problem I'm having is that when I call on the function from the routes-file, to the controller-file it wont work. If I put the code from controller-file in the routes-file it works.

This is my app.js

const express       = require('express');
const bodyParser    = require('body-parser');
const passport      = require('passport');
const flash         = require('connect-flash');
const morgan        = require('morgan');
const cookieParser  = require('cookie-parser');
const session       = require('express-session');

const Data = require('./app/models/data.js');
const User = require('./app/models/user.js');

require('./config/passport')(passport)

// create express app
const app = express();

// set the view engine to ejs
app.set('view engine', 'ejs');

// parse requests of content-type - application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }))

// parse requests of content-type - application/json
app.use(bodyParser.json())

// Configuring the database
const dbConfig = require('./config/database.js');
const mongoose = require('mongoose');

mongoose.Promise = global.Promise;

// Connecting to the database
mongoose.connect(dbConfig.url)
.then(() => {
    console.log("Successfully connected to the database");    
}).catch(err => {
    console.log('Could not connect to the database. Exiting now...');
    process.exit();
});

// log every request to the console
app.use(morgan(':remote-user :referrer :method :url :status :res[content-length] - :response-time ms :req[header] :res[header]')); 

// read cookies (needed for auth)
app.use(cookieParser()); 

// required for passport
app.use(session({ 
    secret: 'ilovescotchscotchyscotchscotch',
    resave: false,
    saveUninitialized: false 
})); // session secret

app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions

// use connect-flash for flash messages stored in session
app.use(flash()); 


// Define start route <url>'/'
app.get('/', (req, res) => {
    res.render('pages/index');
});



// Require routes
require('./app/routes/routes.data.js')(app);
require('./app/routes/routes.user.js')(app, passport);


// All loaded, start server
// listen for requests
app.listen(3000, () => {
    console.log("Server is listening on port 3000");
});

This is the routes.user.js

module.exports = (app) => {
const user = require('../controllers/controller.user.js');
const passport      = require('passport');

// Visa Logga in-sidan
app.get('/login', user.login)

// Visa registreringssidan
app.get('/signup', user.signup)

// Skapa user
app.post('/signup', user.createUser)

}

And this is the controller.user.js

const User          = require('../models/user.js');
const passport      = require('passport');

require('../../config/passport')(passport)

exports.login = (req, res) => {
    res.render('pages/login', { message: req.flash('loginMessage') });     
};

exports.signup = (req, res) => {
    res.render('pages/signup', { message: req.flash('signupMessage') });     
};

exports.createUser = (req, res) => {
    passport.authenticate('local-signup', {
        successRedirect : '/all', // redirect to the secure profile section
       failureRedirect : '/signup', // redirect back to the signup page if there is an error
       failureFlash : true // allow flash messages
   });    
};

When I try to register a user it times out. Nothing more, just times out.

But if I move this part from the controller.user.js ...

passport.authenticate('local-signup', {
        successRedirect : '/all', // redirect to the secure profile section
       failureRedirect : '/signup', // redirect back to the signup page if there is an error
       failureFlash : true // allow flash messages
   });

... to the routes.user.js

    // Skapa user
    app.post('/signup', passport.authenticate('local-signup', {
        successRedirect : '/all', // redirect to the secure profile section
       failureRedirect : '/signup', // redirect back to the signup page if there is an error
       failureFlash : true // allow flash messages
   }));

.. everything works.

Why doesnt it work in the controller.user.js-file?

like image 238
ANorseDude Avatar asked Mar 07 '23 05:03

ANorseDude


1 Answers

Found this; Passport Authenticate doesn't redirect

It was the same solution that @IdanDagan posted.

I changed the this part in the controller.user.js

exports.createUser = (req, res, next) => {
    passport.authenticate('local-signup', {
        successRedirect : '/all', // redirect to the secure profile section
        failureRedirect : '/signup', // redirect back to the signup page if there is an error
        failureFlash : true // allow flash messages
    });
};

to the following

exports.createUser = (req, res, next) => {
    passport.authenticate('local-signup', {
        successRedirect : '/all', // redirect to the secure profile section
        failureRedirect : '/signup', // redirect back to the signup page if there is an error
        failureFlash : true // allow flash messages
    })(req, res, next);
};

... And now it works as a charm!

Thanks for the help. Hope this can help other people too.

like image 62
ANorseDude Avatar answered Apr 01 '23 03:04

ANorseDude