Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

sequelize.js - Sequelize model property undefined Express.js controller after auth with passport-jwt

I am using passport-jwt to verify access to a given route in express.js, and then return a Sequelize model to the final controller. The code looks like:

The auth strategy:

const passportStrategy = passport => {
    const options = {
        jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
        secretOrKey: config.auth.ACCESS_TOKEN_SECRET
    };

    passport.use(
        new Strategy(options, async (payload, done) => {
            try {
                const user = await User.findOne({ where: { email: payload.email }});
                if (user) {
                    return done(null, {
                        user
                    });
                }
                return done(null, false);
            }
            catch (error) {
                return done(error, false)
            }
        })
    );
};

The route with the auth middleware

router.get('/:user_id/psy', passport.authenticate('jwt', { session: false }), patientsController.getPatientPsy);

The controller function

const getPatientPsy = async (req, res) => {
    const authenticatedUser = req.user;

    if (authenticatedUser.userType !== "patient") {
       res.status(500).send("Big time error");
    }
}

If I console.log(authenticatedUser) in the getPatientPsy() controller it successfully prints the Sequelize model with it's dataValues and so on, but when I try to access any property, be it userType or any other it consistently returns undefined.

In the passport-jwt authentication once a User has been found that matches the extracted JWT token, afaik it is returned synchronously and made it available in the req.user object, and I can print it with console.log, but why can't I access the model's properties?

I've tried to make the getPatientPsy() controller a sync function but it doesn't work either.

Thank you.

question from:https://stackoverflow.com/questions/65934642/sequelize-model-property-undefined-express-js-controller-after-auth-with-passpor

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

All right this is embarrassing, by default Passport.js returns the done(null, user) in the req.user property, and since I am returning { user }, I had to access through req.user.user.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...