module.exports = function (app, opts) { async function oauthParseAuthHeader (auth) { if ('isVcmp') { // 去 vcmp 检查 appkey 和 appsecret 是否正确 try { const existRes = await app.fs.vcmpRequest.get(`application/check`, { header: { authorization: auth } }) } catch (error) { throw new Error('应用已禁用或不存在!'); } } if (!auth) { throw new Error('参数无效: 未包含Authorization头'); } const authSplit = auth.split('Basic'); if (authSplit.length != 2) { throw new Error('参数无效: Authorization头格式无效,请检查是否包含了"Basic "'); } const authCode = authSplit[1]; const apikey = Buffer.from(authCode, 'base64').toString(); const keySplit = apikey.split(':'); if (keySplit.length != 2) { throw new Error('参数无效:请检查Authorization头内容是否经过正确Base64编码'); } return keySplit; } async function oauthParseBody (body, type) { let checked = true, token = ''; if (type == 'apply' && body['grant_type'] != 'client_credentials') { checked = false; } else if (type == 'refresh') { if (body['grant_type'] != 'refresh_token' || body['token'] == null) { checked = false; } else { token = body['token']; } } else if (type == 'invalidate') { if (body['token'] == null) { checked = false; } else { token = body['token']; } } if (!checked) { throw new Error('参数无效:请求正文中未包含正确的信息'); } return token; } return { oauthParseAuthHeader, oauthParseBody } }