Y
Y
Yuri Matveenko2018-05-13 18:05:26
Node.js
Yuri Matveenko, 2018-05-13 18:05:26

How to get current user in controller?

There is nodejs ( express.js + passport.js + socket.io )
Authorization and Registration works fine.
passport.js configuration

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

const User = require('../app/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);
        });
    });

    passport.use('signup', new LocalStrategy({
        usernameField : 'email',
        passwordField : 'password',
        passReqToCallback : true // allows us to pass back the entire request to the callback
    },
    function(req, email, password, done) {

        User.findOne({ 'email' :  email }, function(err, user) {
            if (err)
                return done(err);

            if (user) {
                return done(null, false, req.flash('signupMessage', 'That email is already taken.'));
            } else {

                let newUser = new User();

                newUser.email = email;
                newUser.password = newUser.generateHash(password); // use the generateHash function in our user model

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

        });

    }));

    passport.use('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)
                return done(null, false, req.flash('loginMessage', 'No user found.')); // req.flash is the way to set flashdata using connect-flash

            if (!user.validPassword(password))
                return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.')); // create the loginMessage and save it to session as flashdata

            return done(null, user);
        });

    }));

};

I get the user without problems only in routes, for example:
app.get('/chat', isLoggedIn, function(req, res) {
        res.render('chat.ejs', {
            user : req.user
        });
    });

But you need to get the user in the controller.
server.js
const express  = require('express');
const app      = express();
const port     = process.env.PORT || 8558;
const http     = require('http').createServer(app);
const io       = require('socket.io')(http);
const ip       = require('ip');
const mongoose = require('mongoose');
const passport = require('passport');
const flash    = require('connect-flash');
const session  = require('express-session');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const logger = require('express-logger');

app.use(express.static('./'));

mongoose.connect('mongodb://localhost:27017/messenger');

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

if (app.get('env') === 'development') {

    app.use(logger({path: "path/to/logfile.txt"}));
    app.use(cookieParser());
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: true }));

    app.set('view engine', 'ejs'); // set up ejs for templating

    app.use(session({ secret: 'mysecrectkey', cookie: { maxAge: 60000 }, resave: true, saveUninitialized: true }));
    app.use(passport.initialize());
    app.use(passport.session());
    app.use(flash());

}


require('./app/routes.js')(app, passport, io);
require('./app/controller/controller.js')(app, passport, io);


http.listen(port,function(){
    console.log("Node Server установлен и прослушивается на http://"+ip.address()+":"+port);
});

controller.js
const models = require('../models/models.js');
const path = require('path');
const bodyParser = require('body-parser');



module.exports = function (app,passport,io) {



    io.on('connection', function(socket){

        

    });



};

Actually here I need to get a user, I have no idea how. I read the passport.js documentation in full, there is no such information. Google didn't give any results.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
profaller, 2018-05-13
@profaller

I think this will help you - https://github.com/jfromaniello/passport.socketio
Good luck!

E
Egor Zhivagin, 2018-05-14
@Krasnodar_etc

And just throw the user from the route to the appropriate controller, no?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question