Update node.JS session

Asked 2 years ago, Updated 2 years ago, 36 views

express, passport, mongoose, express-session is in use.

User.findOne({'_id': req.user._id}, function(err, user){/user document search
    if(err){console.log('findOneError')}else{
        user.profImgHref = /*omitted* /; // Modify DB
        req.session.passport.user.profImgHref = user.profImgHref; // update session
        user.save(); // Modify DB
        req.logIn(user, function(err){
            if(err)return err;
        });
    }
});

The user has been using the mongoose model and is trying to update the user's profileImgHref. In addition to modifying the DB, the session value should also be modified, but passport is linked, and here (https://github.They called com/jaredhanson/passport/issues/208) req.login and told me I had to deserialize it again So at the end, req.I put in login, but there is still no change. Is there a part that I forgot? The session value is res.locals.userSession = req in app.js.I'm calling it up with user;

Additional explanation of questions

Here's the logic of my code.

However, as I checked with Robomongo, the session value has not changed at all. Session req. through passport.I think it's right to send it in user form (req.user was not effective even if I put it directly at the router end.) However, there is only a change in DB value, so if I log in directly, the passport changes in the session during the session reconstruction stage.

Reattach the code on the router side in detail.

router.post('/profImg', function(req, res, next){
    var form = new multiparty.Form({//multiparty module in use)
        maxFilesSize: 512 * 1024
    });
    form.on('error', function(message) {
                res.status = 413;
                res.send (413, 'Problems occurred. Please try again or contact your administrator.');
                res.end();
            });
    form.on('part', function(part) {
        if(part.fileName){ // recheck file type, file size
            var type = part.headers['content-type'];
            var size = part.byteCount - part.byteOffset;
            if(type != 'image/jpeg' && type != 'image/png' && type != 'application/gif' || size == 0) {
                this.emit('error');
            }
        }
    });
    form.on('close', function(){
        res.json();
    });
    form.parse(req, function(err, fields, files){
        function instFile (filesArg){
            //  Take files.profImg[0] as a factor
            var data = fs.readFileSync(filesArg.path),
                fName = filesArg.path.split('/').pop(),
                userID = req.user._id.valueOf(),
                forKey = 'profile/'+userID+'/'+fName,
                params = {
                    Bucket: 'bucketName',
                    ACL: 'public-read',
                    Key: forKey,
                    Body: data
                }
            If (filesArg.size==0){ // delete temporary file if size is 0
                fs.unlinkSync(filesArg.path);
            }else{
                if(req.user.profImgHref){
                    var params2 = {
                        Bucket: 'bucketName',
                        Key: 'profile/'+userID
                    }
                    s3.deleteObject(params2, function(err, data){
                        if(data){
                            console.log ("File Deletion Successful"); // situations where it cannot be deleted. The cause is unknown
                        }else{
                            console.log(err);
                        }
                    });
                }
                s3.putObject(params, function (err, data) {
                    if(err){
                        console.log(err, err.stack);
                        console.log ('putObjectError');
                    }else{
                        User.findOne({'_id': req.user._id}, function(err, user){
                            if(err){console.log('findOneError')}else{
                                //  Modify Image Url
                                user.profImgHref = 'https://bbucketName.s3.amazonaws.com/'+forKey;
                                req.user.profImgHref = user.profImgHref;
                                user.save();
                                    console.log(user);
                                    req.logIn(user, function(err){
                                        if(err)return err;
                                    });
                                console.log(req.session.passport.user.profImgHref);
                            }
                        });
                    }
                });
            }
        }
        instFile(files.profImg[0]);
    });
});

node.js javascript

2022-09-21 18:31

3 Answers

Resave is set to false in the session setting.

Req to reflect in store.session.You can sing "Save" yourself or "resave" to "true".

https://github.com/expressjs/session#sessionsave

If not SPA, req.I don't think you need to log in.


2022-09-21 18:31

Additional answers

If you look at the difference between the code you uploaded and my code, req.session.I think you're using passport.user. For me, req.I sent the user to the view and used it.

https://github.com/tutsplus/passport-mongo I tested it using the code in .

Below is the first answer

https://github.com/jaredhanson/passport/issues/208 If you look at the bottom of the section, there is a story that there is no need to update the session separately because the passport updates the session with the id (a comment from someone named samhuntsocial) Hello I tested it with the login maintained.

router.get('/home', isAuthenticated, function(req, res){

    User.findOne({'_id': req.user._id}, function(err, user){
    if(err){console.log('findOneError')}else{
        user.firstName = user.firstName+"#";
        user.save();
    }
    });

    res.render('home', { user: req.user });
});

When I tried it with this, # was added to the firstName every time I reloaded the page. But if you're going to do it with a single page app without a page reload, I'll have to find another way, but if not, I think you just need to reload the page.


2022-09-21 18:31

It's not Jade, but I'm using handlebars

This is HTml.

<divid="preview"><imgsrc="{{#ifuserSession.profImgHref}{{userSession.profImgHref}}{{/if}}" alt=""></div>

I extracted the code related to the session from app.js.

var express = require ('express'),
    path = require('path'),
    logger = require('morgan'),
    cookieParser = require('cookie-parser'),
    bodyParser = require('body-parser'),
    exphbs = require('express-handlebars'),
    routes = require('./routes/index'),
    newclass = require('./routes/newClassSubmit'),
    mypage = require('./routes/mypage'),
    mongoose = require('mongoose'),
    csurf = require('csurf'),
    filter = require('content-filter');
const session = require('express-session');
const MongoStore = require('connect-mongo')(session);
var app = express();
app.use(session({
    cooke: {
        maxAge: 30 * 24 * 60 * 60 * 1000,
        expires: 7200000,
        httpOnly: true
    },
    resave: false,
    saveUninitialized: false,
    secret: '~~~',
    store: new MongoStore({
        mongooseConnection: mongoose.connection
    })
}));
//  //  passport
var passport = require('./config/passport');
app.use(passport.initialize());
app.use(passport.session());
//  Session forwarding
app.use(function(req, res, next){
    res.locals.userSession = req.user;
    next();
});
//  //  router Setup
app.use('/', routes);
app.use('/newClassSubmit', newclass);
app.use('/mypage', mypage);

config/passport.js

var passport = require('passport'),
    LocalStrategy = require('passport-local').Strategy,
    User = require('../models/User.js'),
    bcrypt = require('bcrypt');

passport.serializeUser(function(user, done){
    done(null, user);
});
passport.deserializeUser(function(user, done){
        done(null, user);
});
passport.use('local-login', //LocalStrategy Setup
             new LocalStrategy({
    usernameField: 'email',
    passwordField: 'password',
    passReqToCallback: true
},
    function(req, email, password, done){
    User.findOne({'email':email}, function(err,user){ // Search for user by entered email
        if(err) return done(err); // error message output
        if(!user){
            return done (null, false, {msg: 'NoID'}); // return NoID if the user is not present
        }
        If(!user.authenticate(password)) { // Mongoose method of matching passwords
            return done (null, false, {msg: 'WrPW'}); // return WrPW if password is different
        }
        return done (null, user);// return user DB if there is no problem
    });
})
);

module.exports = passport;

models/User.js

var mongoose = require ("mongoose"),
    bcrypt = require('bcrypt');

//  Set membership schema
var userSchema = new mongoose.Schema({
    //omitted
    profileImgHref: String // profile image address
});

userSchema.pre('save', function(next){ // Password encryption before modifying user information
    var user = this;
    If(!user.isModified('password'){ // If there is no change in password, next()
        return next();
    }else{
        user.password = bcrypt.hashSync(user.password, bcrypt.genSaltSync())); // Encrypt if there is any change
        return next();
    }
});

//password verification method
userSchema.methods.authenticate = function (password) {
    var user = this;
    return bcrypt.compareSync(password,user.password);
}

var User = mongoose.model('user',userSchema);

module.exports = User;


2022-09-21 18:31

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.