vendredi 18 mars 2016

Passing down passportjs to individual route file in ES6

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 ?

Aucun commentaire:

Enregistrer un commentaire