- 在token.js中添加對應的處理方法
根據登錄方式的不同對登錄數據進行處理
const Router = require('koa-router')
const {ValidationToken} = require('../../validators/validator')
const {LoginType} = require('../../lib/enum')
const {User} = require('../../models/user')
const {ParameterException} = require('../../../core/http-exception')
const router = new Router({
prefix: '/v1/token'
})
router.post('/', async (ctx)=>{
const v = await new ValidationToken().validate(ctx)
// 根據不同的登錄方式,返回客戶端不同的信息
switch (v.get('body.type')) {
case LoginType.USER_EMAIL:
await emailLogin(v.get('body.account'), v.get('body.secret'))
break;
case LoginType.USER_MINI_PROGRAM:
break;
default:
throw new ParameterException('沒有相關處理函數')
break;
}
})
// 比對客戶端傳遞的用戶名和密碼是否與數據庫中的一致,如果一致就頒佈令牌
async function emailLogin(account, secret){
const user = await User.verifyEmailPassword(account, secret)
}
module.exports = router
- 將數據處理方法編寫在user.js模型中
const {AuthFailed} = require('../../core/http-exception')
class User extends Model{
static async verifyEmailPassword(email, plainPassword){
// 查詢數據中是否存在對應的傳入的用戶
const user = await User.findOne({
where: {
email: email
}
})
// 當用戶不存在
if(!user){
throw new AuthFailed('賬號不存在')
}
// 注意數據表中的密碼是加密過後的,不能直接拿來與用戶傳入的密碼進行對比
const correct = bcrypt.compareSync(plainPassword, user.password)
// 如果密碼不一致
if(!correct){
throw new AuthFailed('密碼不正確')
}
return user
}
}
- 異常處理文件http-exception.js中添加錯誤處理類
// 當查詢結果在數據庫中找不到
class NotFound extends HttpException{
constructor(msg="資源未找到", errorCode="10000"){
super()
this.code = 404
this.msg = msg
this.errorCode = errorCode
}
}
// 當查詢結果在數據庫中找不到
class AuthFailed extends HttpException{
constructor(msg="授權失敗", errorCode="10004"){
super()
this.code = 401
this.msg = msg
this.errorCode = errorCode
}
}
module.exports = {
HttpException,
ParameterException,
Success,
NotFound,
AuthFailed
}