AdminUser.js
const mongoose = require('mongoose')
const schema = new mongoose.Schema({
username: { type: String },
password: {
type: String,
select: false,
set(val) {
return require('bcryptjs').hashSync(val, 10)
}
}
})
module.exports = mongoose.model('AdminUser', schema)
routes.js
app.post('/admin/api/login', async (req, res) => {
const { username, password } = req.body
const AdminUser = require('../../models/AdminUser')
const user = await AdminUser.findOne({ username })
if (!user) {
return res.status(422).send({
message: '用户不存在'
})
}
const isValid = require('bcryptjs').compareSync(password, user.password)
if (!isValid) {
return res.status(422).send({
message: '密码错误'
})
}
const jwt = require('jsonwebtoken')
const token = jwt.sign({ id: user._id }, app.get('secret'))
res.send({ token })
})