server\routers\index.js 路由
从server\qcloud.js中解构出 Koa 授权中间件&Koa 鉴权中间件
两个中间件,最终都会设置ctx.state.$wxInfo = result
Koa 授权中间件,执行步骤:
1、从req.headers中解构出{code, encryptedData, iv}
2、通过code、appId和appSecret获取openid与session_key
.....(可以使用腾讯云代小程序登录)
3、生成 3rd_session
······加密session_key生成skey
4、解密数据
.....传入(session_key, iv, encryptedData)解密出decryptedData
.....decryptedData={openId:asdfghjkasdfghj'}
5、存储到数据库中(decryptedData, skey, session_key)
.....open_id = decryptedData.openId
.....create_time = moment().format('YYYY-MM-DD HH:mm:ss')
.....uuid = uuidGenerator()
.....user_info = JSON.stringify(userInfo)
.....最后成功:ctx.state.$wxInfo = result={ loginState, userinfo }
数据库:cAuth-表:cSessionInfo*低版本不支持两个时间戳
疑问:code + appId + appSecret = openid + session_key
session_key + iv + encryptedData = userInfo = {openId, ...}
// 从 sdk 中取出中间件
// 这里展示如何使用 Koa 中间件完成登录态的颁发与验证
const { auth: { authorizationMiddleware, validationMiddleware } } = require('../qcloud')
// --- 登录与授权 Demo --- //
// 登录接口
router.get('/login', authorizationMiddleware, controllers.login)
// 用户信息接口(可以用来验证登录态)
router.get('/user', validationMiddleware, controllers.user)
###server\qcloud.js
const qcloud = require('wafer-node-sdk')
// 初始化 SDK
// 将基础配置和 sdk.config 合并传入 SDK 并导出初始化完成的 SDK
//将两个配置文件转对象后合并
//sdkConfig=fs.readFileSync('/data/release/sdk.config.json' )与configs=require('./config')
module.exports = qcloud(Object.assign({}, sdkConfig, configs))
-----
qcloud函接受一个配置对象返回一个对象:
{
config,//深拷贝的对象(配置信息)-->>Object.assign({}, sdkConfig, configs)
mysql: require('./lib/mysql'),
auth: require('./lib/auth'),//!!!!!!!!
uploader: require('./lib/upload'),
tunnel: require('./lib/tunnel'),
message: require('./lib/message'),
ci: require('./lib/ci/ocr'),
voice: require('./lib/voice')
}
###auth: require('./lib/auth')
auth : {//4大模块-func
authorization,//授权模块
validation,//鉴权模块
authorizationMiddleware,//Koa 授权中间件
validationMiddleware//Koa 鉴权中间件
}
/**
* Koa 授权中间件
* 基于 authorization 重新封装
* @param {koa context} ctx koa 请求上下文
* @return {Promise}
*/
function authorizationMiddleware (ctx, next) {
return authorization(ctx.req).then(result => {
ctx.state.$wxInfo = result
return next()
})
}
/**
* Koa 鉴权中间件
* 基于 validation 重新封装
* @param {koa context} ctx koa 请求上下文
* @return {Promise}
*/
function validationMiddleware (ctx, next) {
return validation(ctx.req).then(result => {
ctx.state.$wxInfo = result
return next()
})
}