1

I have a situation in my route file where in I need to import the instantiated passportjs variable into the route.

const api = express.Router();

function isLoggedIn(req, res, next) {

    // if user is authenticated in the session, carry on 
    if (req.isAuthenticated())
        return next();

    // if they aren't redirect them to the home page
    res.json({ error: 'user is not logged in', status : 404 });
}

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

I want to import the passport variable from the main index.js file to the api module where in I can access passportjs to perform the signup or login operations.

import passport from 'passport';
import mongoose from 'mongoose';
import api from './routes/api';

app.server = http.createServer(app);

mongoose.connect(db);
// 3rd party middleware
require('./config/passport')(passport); 

app.use(compression());
app.use(cors({
    exposedHeaders: ['Link']
}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(logger('dev'));
app.use(cookieParser());
app.use(session({ proxy: true,
                                resave: true,
                                saveUninitialized: true,
                                secret: 's3kr3tk3y' 
                              })
                );      
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(express.static(__dirname + '/../public'));

//router rules
app.set('views', __dirname + '/../public/views');
app.set('view engine', 'jade');

app.get('/', function (req, res) {
    res.render('index');
});

app.use('/api', api);

app.server.listen(port, function () {
    console.log(' Application started on port ' + port);
});

export default app;

How can I achieve this in the current given format ?

Bazinga777
  • 5,140
  • 13
  • 53
  • 92

1 Answers1

0

I may do like this

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

export default apiBuilder;

/** index.js */
import passport from 'passport';
import apiBuilder from './routes/api';
...
app.use('/api', apiBuilder(passport));

Once your app goes more complex, you may like to further modulize the passport library as an authentication module:

/** ./routes/api */
...
function apiBuilder(auth){                                                                                                        
    api.route('/signup')                                                                                                              
       .post(auth.authForSignup);
}                                                                                                                                     

export default apiBuilder;

/** ./path/to/authModule.js */
import passport from 'passport';
...
const auth = {
    authForSignup: passport.authenticate('local-signup', {                                                                                
            successRedirect : '/profile', // redirect to the secure profile section                                                   
            failureRedirect : '/signup', // redirect back to the signup page if there is an error                                     
            failureFlash : true // allow flash messages                                                                               
        })
    // more authentication scenarios can be put here
};

export default auth;

/** index.js */
import auth from './path/to/authModule';
import apiBuilder from './routes/api';
...
app.use('/api', apiBuilder(auth));

I use this kind of pattern as a seed for my app, hope this will help you.

hankchiutw
  • 1,546
  • 1
  • 12
  • 15