继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

【金秋打卡】第7天 Node.js+Koa2+MySQL打造前后端分离精品项目《旧岛》

萧萧啊
关注TA
已关注
手记 21
粉丝 1
获赞 0

课程章节: 【构建用户身份系统】通用用户系统与小程序用户系统

课程讲师: 7七月

课程内容:

isOptional 效验

在 api/v1/token.js

const Router = require('koa-router')
const router = new Router({
	prefix: '/v1/token'
})

router.post('/', async (ctx) => {
	
})

在 validators/validtor.js

class TokenValidator extends LinValidator {
	constructor() {
	super()
		this.account = [
	      new Rule('isLength', '不符合账号规则', {
			 min: 4,
			 max: 32
          })
        ]
        this.secret = [
			new Rule('isOptional'),
			new Rule('isLength', '至少6个字符',{
				min: 6,
				max: 128
            })
        ]
    }
}

模拟枚举

因为小程序有很多种登录方式, 我们给小程序一个枚举来表示登录方式
在 app/lib/enum.js

function isThisType(vals) {
	for(let key in this) {
		return true
    }
    return false
}
const LoginType = {
	USER_MINI_PROGRAM: 100,
	USER_EMAIL: 101,
	USER_MOBILE: 102,
	ADMIN_EMAIL: 200
}
module.exports = {
	LoginType
}

在 validators/validtor.js

const LoginType = require('loginType')
validateLoginType(vals) {
	if(!vals.body.type) {
		throw new Error('type必须是参数')
    }
    if(!LoginType.isThisType(vals.body.type)) {
		throw new Error('type参数不合法')
    }
}
// 导出

回到 api/v1/token.js

const {TokenValidator} = require('Validator')
router.post('/', async (ctx) => {
	const v = await new TokenValidator().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:
		default:
		throw new global.errs.ParameterException('没有相应的处理函数')
    }
})
async function emailLogin(account, secret) {
	const res = await User.verifyEmailPassword(account, secret)
}
module.exports = router

models/user.js

class User extends Model {
	static async verifyEmailPassword(email, plainPassword) {
		const user = await User.findOne({
			where: {
		     email
            }
        })
        if(!user){
			throw new global.errs.NotFound('账户不存在')
        }
        const correct = bcrypt.compareSync(plainPassword, user.password)
        if(!correct) {
			throw new global.errs.AuthFailed('密码不正确')
        }
        return user
    }
}

在 core/http-exception.js 中定义错误

class NotFound extends HttpException {
	constructor(msg, error, code) {
		 super()
		 this.msg = msg || '资源未找到'
		 this.errorCode = errorCode || 10000
		 this.code = 404
    }
}

class AuthFailed extends HttpException {
	constructor(msg, error, code) {
		 super()
		 this.msg = msg || '授权失败'
		 this.errorCode = errorCode || 10004
		 this.code = 401
    }
}

课程收获

了解了小程序的登录多重种方式

打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP