gpt4 book ai didi

mysql - 如何解决错误 500-[object SequelizeInstance :users] mysql Authentication

转载 作者:行者123 更新时间:2023-12-03 22:34:29 29 4
gpt4 key购买 nike

我在这里寻求帮助。任何指针或决议将不胜感激。
我正在构建一个 MERN 身份验证/授权应用程序,在身份验证尝试期间我收到此错误 500:[object SequelizeInstance:users]。
我正在使用 Passport、mysql 数据库和 sequelize。
下面是我的构建细节。
模型

const bcrypt = require("bcrypt");
module.exports = (sequelize, Sequelize) => {
const User = sequelize.define("users", {
username: {
type: Sequelize.STRING,
required: true
},
email: {
type: Sequelize.STRING,
required: true
},
firstname: {
type: Sequelize.STRING,
required: true
},
lastname: {
type: Sequelize.STRING,
required: true
},
password: {
type: Sequelize.STRING,
required: true
}
}, {
hooks: {
beforeCreate: async function (user) {
const salt = await bcrypt.genSaltSync(10);
user.password = await bcrypt.hashSync(user.password, salt);
}
},

instanceMethods: {
validPassword: function (password) {
return bcrypt.compareSync(password, this.password, (err, isMatch) => {
if (err)
return cb(err);
else {
if (!isMatch)
return cb(null, isMatch);


return cb(null, this);
}
});
}
}
});


return User;
};

PassportJs

const config = require("./config/auth.config");
const db = require("./models");
const User = db.user;

const cookieExtractor = req => {
let token = null;
if (req && req.cookies) {
token = req.cookies["access_token"];
}
return token;
}

// authorization
passport.use(new JwtStrategy({
jwtFromRequest: cookieExtractor,
secretOrKey: config.secret
}, (payload, done) => {
User.findByPk({
id: payload.sub
}, (err, user) => {
if (err)
return done(err, false);



if (user)
return done(null, user);
else
return done(null, false);



});
}));

// authenticated local strategy using username and password
passport.use(new LocalStrategy((username, password, done) => {
User.findOne({
where: {
username: username
}
}).then((err, user) => { // something went wrong with database
if (err)
return done(err);



// if no user exist
if (!user)
return done(null, false);



// check if password is correct
user.validPassword(password, (err, isMatch) => {
if (err)
return done(err)
if (!isMatch)
return done(null, false)
return done(null, user)


}).catch(e => done(err))
});
}));

登录 Controller

exports.register = (req, res) => {
const {
username,
email,
firstname,
lastname,
password
} = req.body;
User.create({
username: username,
email: email,
firstname: firstname,
lastname: lastname,
password: password
}).then((user) => {
if (req.body.roles) {
Role.findAll({
where: {
name: {
[Op.or]: req.body.roles
}
}
}).then((roles) => {
user.setRoles(roles).then(() => {
res.status(201).json({
message: {
msgBody: "Account successfully created",
msgError: false
}
});
});
});
} else {
user.setRoles([3]).then(() => {
res.status(201).json({
message: {
msgBody: "Account successfully created",
msgError: false
}
});
});
}
}).catch((err) => {
res.status(500).json({
message: {
msgBody: err.message,
msgError: true
}
});
});
};


exports.login = (req, res) => {

if (req.isAuthenticated()) {
const {
id,
username,

} = req.user;
const token = signToken(id);
res.cookie('access_token', token, {
httpOnly: true,
sameSite: true
});
var authorities = [];
user.getRoles().then(roles => {
for (let i = 0; i < roles.length; i++) {
authorities.push("ROLE_" + roles[i].name.toUpperCase());
}
});
res.status(200).json({
isAuthenticated: true,
user: {
username,
roles: authorities
}
});


} else {
User.findOne({
where: {
username: username
}
}),
(err, user) => {
if (err)
res.status(500).json({
message: {
msgBody: "Error has occurred",
msgError: true
}
});


if (user)
res.status(400).json({
message: {
msgBody: "Wrong password!",
msgError: true
}
});
else {
res.status(401).json({
message: {
msgBody: "Please Register",
msgError: true
}
});
}

}
}

}

路线

const controller = require("../controller/auth.controller");
const passport = require('passport')
const requireSignin = passport.authenticate('local', {session: false});

module.exports = function (app) {
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Headers", "access_token, Origin, Content-Type, Accept");
next();
});


app.post("/login", requireSignin, controller.login);


};

最佳答案

我终于能够解决这个问题。

  • 我将 serializeUser 和 deserializeUser 添加到我的passport.js 文件
  • 我还有一个新函数来比较我的用户模型中的密码,随后更新了我的passport.js 中的本地策略代码

  • 用户模型更新

    const bcrypt = require("bcrypt");
    module.exports = (sequelize, Sequelize) => {
    const User = sequelize.define("users", {
    username: {
    type: Sequelize.STRING,
    required: true,
    },
    email: {
    type: Sequelize.STRING,
    required: true,
    },
    firstname: {
    type: Sequelize.STRING,
    required: true,
    },
    lastname: {
    type: Sequelize.STRING,
    required: true,
    },
    password: {
    type: Sequelize.STRING,
    required: true,
    },
    resetPasswordToken: {
    type: Sequelize.STRING,
    },
    resetPasswordExpires: {
    type: Sequelize.STRING,
    },
    });
    User.prototype.comparePassword = function comparePassword(candidatePassword, cb) {
    bcrypt.compare(candidatePassword, this.password, (err, isMatch) => {
    cb(err, isMatch);
    });
    };
    return User;
    };

    我更新的passport.js

    const passport = require("passport");
    const LocalStrategy = require("passport-local").Strategy;
    const JwtStrategy = require("passport-jwt").Strategy;
    const config = require("./config/auth.config");
    const db = require("./models");
    const User = db.user;

    passport.serializeUser((user, done) => {
    console.log('serializing user: ', user.id);
    done(null, user.id);
    });

    passport.deserializeUser((id, done) => {
    User.findById(id).then((user) => {
    done(null, user);
    }).catch(done);
    });

    const cookieExtractor = (req) => {
    let token = null;
    if (req && req.cookies) {
    token = req.cookies["access_token"];
    }
    return token;
    };




    // authorization
    passport.use(
    new JwtStrategy({
    jwtFromRequest: cookieExtractor,
    secretOrKey: config.secret,
    },
    (payload, done) => {
    User.findOne({
    where: {
    id: payload.sub,
    },
    },
    (err, user) => {
    if (err) return done(err, false);

    if (user) return done(null, user);
    else return done(null, false);
    }
    );
    }
    )
    );

    // authenticated local strategy using username and password
    passport.use(new LocalStrategy({ usernameField: 'username' }, (username, password, done) => {
    User.findOne({
    where: { username: username},
    }).then(( user, err) => {
    if(err)
    return done(err);
    if (!user) {
    return done(null, false);
    }
    user.comparePassword(password, (err, isMatch) => {
    if (err) { return done(err); }
    if (isMatch) {
    return done(null, user);
    }
    return done(null, false);
    });
    });
    }));

    关于mysql - 如何解决错误 500-[object SequelizeInstance :users] mysql Authentication,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62982128/

    29 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com