Blame view

online-office/src/assets/config/extApiConfig.js 10.1 KB
wangtao authored
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
// var SERVER_PORT = "127.0.0.1:9004";
var SERVER_PORT = (function () {
    var isDev = window.location.search.indexOf("dev=1") !== -1
    if (isDev) {
        return "127.0.0.1:9004";
    }
    return window.location.host;
})();
var API_PREFIX = '';
var BASE_URL = `//${SERVER_PORT}` + API_PREFIX;

window.extApiConfig = {
    SERVER_PORT: SERVER_PORT,
    BASE_URL: BASE_URL,
    API_PREFIX: API_PREFIX,
    // 用户登录配置
    loginConfig: {
        // 开启登录校验
        enable: true,
        // 提交表单,#{x} 替换内容
        formData: {
            username: '#{username}',
            password: '#{password}',
            validCode: '',
            grant_type: 'password',
            scope: 'app',
            client_id: 'webApp',
            client_secret: 'webApp',
            deviceId: '#{uuid}'
        },
        // 第三方用户列表接口(获取全部用户给)
32
        getUser:'http://192.168.0.75:8080/api-user/users?page=1&limit=-1&accessToken=#{tokenKey}&username=&nickname=&enabled=&orgId=&roles=',
wangtao authored
33 34 35 36 37 38 39
        // 用户同步接口 POST [{userId:'',userName:''}]
        syncUser: BASE_URL + '/docmentUser/syncUser',
        // 返回结果中的令牌,获取结果中的【tokenKey】的值,将值存储在缓存中
        tokenKey: 'access_token',
        // 登录地址 POST方法 formData
        loginUrl: 'http://192.168.0.75:8080/api-auth/oauth/token',
        // 获取用户信息
40
        getUserDetail: 'http://192.168.0.75:8080/api-user/users/getUserByToken?accessToken=#{tokenKey}',
wangtao authored
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
        // 获取用户列表
        getUserAll : BASE_URL + '/docmentUser',
        // 保存用户授权
        saveUserAuth: BASE_URL + '/docmentUser/auth',
    },
    // 获取在线用户
    getOnlineUser: BASE_URL + '/docManager/getOnlineUser',
    // 详情查询地址
    documentDetailUrl: BASE_URL + '/docManager/detail',
    // 修改文档标题
    updateDocNameUrl: BASE_URL + '/docManager/rename',
    // 详情查询地址
    documentHistoryUrl: BASE_URL + '/documentLog/history',
    // 文档分享
    documentShare:{
        // 创建分享
        createShareUrl:BASE_URL + '/documentShare/create',
        // 分享确认
        confirmShareUrl:BASE_URL + '/documentShare/confirm',
    },

    // 文档管理配置信息
    docManager: {
        // 获取文档列表
        pageList: BASE_URL + '/docManager',
        // 获取文档唯一编号
        getDocNo: BASE_URL + '/docManager/docNo',
        // POST
        saveOrUpdateDoc: BASE_URL + '/docManager',
        // 删除传id
        deleteDoc: BASE_URL + '/docManager/delete',
        // 获取传id
        getDetail: BASE_URL + '/docManager/getById'
    }
}


/**
 * 获取浏览器参数
 * @param variable
 * @returns {string|boolean|*}
 */
function getUrlVal(variable) {
    var query = window.location.search.substring(1);
    if (query == '') {
        query = document.location.href
        let args = query.split('?');
        let arr = [];
        if (args && args.length > 1) {
            arr = args[1].split('&')
        }
        for (var i = 0; i < arr.length; i++) {
            var pair = arr[i].split("=");
            if (pair[0] == variable) {
                return pair[1];
            }
        }
        return (false);
    }
    var vars = query.split("&");
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        if (pair[0] == variable) {
            return pair[1];
        }
    }
    return (false);
}

/**
 * 展示用户登录弹框
 * @param callback
 */
function showUserLoginModal(callback) {
    //<div class="modal fade" id="userLoginModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="false">
    var html = `<div class="modal fade" id="userLoginModal" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">请登录</h5>
            <!--<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>-->
          </div>
          <div class="modal-body">
            <form class="was-validated">
              <div class="mb-3">
                <label for="userAccount" class="col-form-label">账号:</label>
                <input type="text" class="form-control" id="userAccount" required>
              </div>
              <div class="mb-3">
                <label for="userPassword" class="col-form-label">密码:</label>
                <input type="password" id="userPassword" class="form-control" aria-describedby="passwordHelpInline" required>
              </div>
            </form>
          </div>
          <div class="modal-footer">
            <!--<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>-->
            <button type="button" class="btn btn-primary" id="userLogin">登录</button>
          </div>
        </div>
      </div>
    </div>`;

    $('#userLoginModal').remove();
    $(html).appendTo('body');

    var userLoginModal = new bootstrap.Modal(document.getElementById('userLoginModal'), {
        keyboard: true
    })

    userLoginModal.show();


    // 绑定登录按钮
    $('#userLogin').on('click', function (event) {
        var account = $('#userAccount').val();
        var pwd = $('#userPassword').val()
        if (account && pwd) {
            callback(account, pwd, userLoginModal);
        }

    })
}

window.userLogin = {
    getToken:() =>{
        var config = window.extApiConfig;
        if(config && config.loginConfig.tokenKey){
            return getUrlVal(config.loginConfig.tokenKey);
        }
        return undefined;
    },
    /**
     * 验证用户
     * @param extendsetting
     * @returns {boolean|*}
     */
    checkUser: (extendsetting, showWarning, showSuccess) => {
        const docConfigApi = extendsetting.docConfigApi;
        if (!docConfigApi) {
            // 未配置则返回空账号信息
            return;
        }
        // 是否开启
        var config = docConfigApi.loginConfig;
        // 开启用户验证
        if (config && config.enable === true) {

            var tokenKey = config.tokenKey;
            if (!tokenKey) {
                // 不能获取token
                return;
            }
            // 删除缓存用户
            localStorage.removeItem('userDetail');
            // localStorage.removeItem(tokenKey);

            // 尝试从url获取获取token
            var token = getUrlVal(tokenKey);

            if (!token) {
                showWarning('您还没有登录,清登录!');
                // 获取提交表单配置
                var formData = config.formData;

                // token 为获取到,尝试登录
                showUserLoginModal(function (userAccount, userPasword, userLoginModal) {
                    var params = {};
                    $(Object.keys(formData)).each(function (i, v) {
                        var newVal = formData[v].replace('#{username}', userAccount).replace('#{password}', userPasword).replace('#{uuid}', uuid.v4())
                        params[v] = newVal;
                    })

                    $.post(config.loginUrl, params, function (res) {
                        if (res && res[tokenKey]) {
                            var token = res[tokenKey];
                            localStorage.setItem(tokenKey, res[tokenKey]);
                            localStorage.setItem('userLogin', '1');
                            userLoginModal.hide();
                            var url = window.location.href
                            if (url && window.location.href.indexOf('?') != -1) {
                                url += `&${tokenKey}=${token}`
                            } else {
                                url += `?${tokenKey}=${token}`
                            }
                            window.location.href = url;
                            // window.location.reload();
                        }
                    }).error(function (err) {
                        if (err && err.responseJSON && err.responseJSON.resp_msg) {
                            showDanger(err.responseJSON.resp_msg);
                        }
                    });
                });
                return;
            }


            // 获取用户信息
            var userDetail = localStorage.getItem('userDetail');
            if (!userDetail) {
                // localStorage.setItem('initFlag','1');
                // setTimeout(function (){
                //     localStorage.removeItem('initFlag');
                // },60*60*1000)

                // 获取用户信息
                $.ajaxSettings.async = false;
                $.get(config.getUserDetail.replace('#{tokenKey}', token), {}, function (res) {
                    if (res && res.code === 0) {
                        var userJson = JSON.stringify(res.object);
                        localStorage.setItem('userDetail', userJson);
                        userDetail = userJson;
                        // showSuccess('登录成功!');
                    }
                }).error(function (err) {
                    if (err && err.responseJSON && err.responseJSON.resp_msg) {
                        showWarning("登录超时,请重新登录");
                        localStorage.clear();

                        var url = window.location.href
                        if (url && url.indexOf(tokenKey) != -1) {
                            url = url.substring(0, url.indexOf(tokenKey));
                        }
                        window.location.href = url;
                    }
                });
                $.ajaxSettings.async = true;
            }
            var userId = '';
            var userName = '';
            if (userDetail) {
                var userObj = JSON.parse(userDetail);
                userId = userObj.id;
                userName = userObj.nickname;
            }

            // 获取用户信息
            extendsetting.updateUrl += `?userId=${userId}&nickName=${userName}&${tokenKey}=${token}`
            return userId;
        }
        // 未开启直接跳过
        return true;
    }
}