美文网首页
yapi 插件 yapi-plugin-gitlab 添加 ht

yapi 插件 yapi-plugin-gitlab 添加 ht

作者: 天乙_tang | 来源:发表于2020-03-12 19:05 被阅读0次

插件不支持 https 协议,会报 401 “授权失败” 的错误。通过修改插件源码添加 https 协议支持。

1. 修改 controller/oauth2Controller.js 文件

const https = require('https'); // 添加 https 依赖
const fs = require('fs');   // 用于证书文件读取

// 修改 requestInfo 方法,如果配置的 host 地址是 https 的则通过 https 的方式发送请求
requestInfo(ops, path, method) {
    return new Promise((resolve, reject) => {
       let req = '';
       let client = http;   // 默认为 http 请求
       let options = {
           method: method
       };
       if (ops.host.indexOf('https') === 0) {   // 如果 host 以 https 开头
           client = https;  // 将连接设置为 https

           // gitlab 证书是自己生成的不获取证书文件会报 UNABLE_TO_VERIFY_LEAF_SIGNATURE 错误
           // 这个错误可以通过两种方式解决(任选一种即可):
           // 1)options.rejectUnauthorized 设置成 false
           // 2)将 ssl 的根证书文件赋值给 options.ca
           options.ca = fs.readFileSync('[path to our CA cert file]');
       }
       let http_client = clent.request(ops.host + path, 
           options, 
           function(res){
              ...
       });
       ...
    });
}

2. 修改 server.js 文件

const fs = require('fs');   // 用于证书文件读取
module.exports = function (options) {
    const {emailPostfix, emailKey, userKey, host, loginPath, redirectUri} = options;
    this.bindHook('third_login', (ctx) => {
        let token = ctx.request.body.token || ctx.request.query.token;

        // 如果是 https,设置 options.ca 参数,或者将 options.rejectUnauthorized 设置成 false
        let options = host.indexOf("https") === 0 ? {ca: fs.readFileSync('[path to our CA cert file]')} : {};   
        return new Promise((resolve, reject) => {
            // 发送请求时,传递 options 参数
            request(host + loginPath + "?access_token=" + token, 
                options, 
                function (error, response, body) {
                ...
            });
    });
}

相关文章

网友评论

      本文标题:yapi 插件 yapi-plugin-gitlab 添加 ht

      本文链接:https://www.haomeiwen.com/subject/tvxijhtx.html