How to use addDefaultPort method in Cypress

Best JavaScript code snippet using cypress

nginx.js

Source:nginx.js Github

copy

Full Screen

...327function check_requestBody(requestBody_json) {328 // リクエストボディのチェック329 var client_id = requestBody_json.client_id;330 var call_api_uri = requestBody_json.call_api;331 call_api_uri = addDefaultPort(call_api_uri);332 var call_api_method = requestBody_json.method;333 var call_api_content_type = requestBody_json["content-type"];334 var call_api_body = requestBody_json.body;335 // client_id336 // key なし337 if (typeof (client_id) === "undefined") {338 // call_api339 // key なし340 if (typeof (call_api_uri) === "undefined") {341 return new EdgeError(400, "This parameter[call_api] is missing.");342 } else if (!call_api_uri.match(new RegExp("^https?://", ""))) {343 // value 不正:http https ではない344 return new EdgeError(400, "This parameter [call_api] must start with \"https\" when the parameter [client_id] is missing.[" + requestBody_json.call_api + "]");345 }346 var domain = call_api_uri.match(/^(https?:\/{2,}.*?)\/.*/)[1];347 var authorized_server_list = config_json["authorized_server_list"];348 var flag = 0;349 authorized_server_list.forEach(function (authorized_server) {350 var authorized_server_domain = addDefaultPort(authorized_server.domain);351 if (domain === authorized_server_domain) {352 requestBody_json.client_id = authorized_server.client_id;353 flag = 1;354 }355 });356 if (flag === 0) {357 return new EdgeError(400, "This domain is not included in Config File(authorized_server_list).[" + domain + "]");358 }359 requestBody_json.call_api = call_api_uri.match(/^https?:\/{2,}.*?(\/.*)/)[1];360 } else {361 // client_id362 // key あり363 if (typeof (call_api_uri) === "undefined") {364 // call_api365 // key なし366 return new EdgeError(400, "This parameter[call_api] is missing.");367 } else if (!call_api_uri.match(new RegExp("^/", ""))) {368 // value 不正:"/"始まりではない369 return new EdgeError(400, "This parameter [call_api] must start with slash when the parameter [client_id] is added.[" + requestBody_json.call_api + "]");370 }371 // 許可されているidか372 var isIncludedAuthorizedServer = false;373 var authorized_server_list = config_json["authorized_server_list"];374 authorized_server_list.forEach(function (authorized_server) {375 if (client_id === authorized_server.client_id) {376 isIncludedAuthorizedServer = true;377 }378 });379 if (!isIncludedAuthorizedServer) {380 return new EdgeError(400, "This parameter[client_id] is not included in Config File(authorized_server_list).");381 }382 }383 // method384 // key なし385 if (typeof (call_api_method) === "undefined") {386 return new EdgeError(400, "This parameter[method] is missing.");387 }388 // header Content-type389 // key なし390 if (call_api_method !== "GET" && typeof (call_api_content_type) === "undefined") {391 return new EdgeError(400, "This header parameter[Content-Type] is missing.");392 }393 // value 不正394 if (call_api_method !== "GET" && !call_api_content_type.match("application/json")) {395 return new EdgeError(400, "This header parameter[Content-Type] is not [application/json].");396 }397 // body398 // key なし399 // GET bodyあり400 if (call_api_method === "GET" && typeof (call_api_body) !== "undefined") {401 return new EdgeError(400, "This method[" + call_api_method + "] does not require HTTP Request body.");402 }403 // GET以外 bodyなし404 if (call_api_method !== "GET" && typeof (call_api_body) === "undefined") {405 return new EdgeError(400, "This method[" + call_api_method + "] requires HTTP Request body.");406 }407 // value 不正408 var call_api_body_json;409 try {410 if (call_api_method !== "GET") {411 call_api_body_json = JSON.parse(call_api_body);412 }413 } catch (error) {414 return new EdgeError(400, "This parameter[body] is not JSON.(" + call_api_body + ")");415 }416 //Binary417 // key ある場合はbinary簡易チェックを行う418 if (call_api_method !== "GET") {419 var binary = call_api_body_json["Binary"];420 if (!(typeof (binary) === "undefined")) {421 var parameterArray = [];422 var i = 0;423 //filename,data,last_modified424 var filename = binary["filename"];425 var data = binary["data"];426 var last_modified = binary["last_modified"];427 // key なし428 if (typeof (filename) === "undefined") {429 parameterArray[i++] = "This body parameter does not include the [filename] key.";430 }431 // value null or 空432 if (isEmpty (filename)) {433 parameterArray[i++] = "The [filename] value contained in this body parameter is empty.";434 }435 // key なし436 if (typeof (data) === "undefined") {437 parameterArray[i++] = "This body parameter does not include the [data] key.";438 }439 // value null or 空440 if (isEmpty (data)) {441 parameterArray[i++] = "The [data] value contained in this body parameter is empty.";442 }443 // key なし444 if (typeof (last_modified) === "undefined") {445 parameterArray[i++] = "This body parameter does not include the [last_modified] key.";446 }447 // value null or 空448 if (isEmpty (last_modified)) {449 parameterArray[i++] = "The [last_modified] value contained in this body parameter is empty.";450 }451 if (parameterArray.length > 0) {452 return new EdgeError(400, parameterArray.join());453 }454 }455 }456 return requestBody_json;457}458/**459 * 日付フォーマット関数460 * @private461 * @param {Date} date462 * @return {string} yyyy/MM/dd HH:mm:ss.SSS463 */464function formatDate(date) {465 var format = 'yyyy/MM/dd HH:mm:ss.SSS';466 format = format.replace(/yyyy/g, date.getFullYear());467 format = format.replace(/MM/g, ('0' + (date.getMonth() + 1)).slice(-2));468 format = format.replace(/dd/g, ('0' + date.getDate()).slice(-2));469 format = format.replace(/HH/g, ('0' + date.getHours()).slice(-2));470 format = format.replace(/mm/g, ('0' + date.getMinutes()).slice(-2));471 format = format.replace(/ss/g, ('0' + date.getSeconds()).slice(-2));472 format = format.replace(/SSS/g, ('00' + date.getMilliseconds()).slice(-3));473 return format;474}475/**476 * 現在のURLを取得477 * @private478 * @param {Object} r479 * @return {string}480 */481function getHostFullUrl(r) {482 return r.variables.scheme + "://" + r.variables.http_host + r.variables.uri;483}484/**485 * APIのURLの取得486 * @private487 * @param {Object} r488 * @return {string}489 */490function getCallAPI(r) {491 return r.variables.scheme + "://" + r.variables.http_host + r.variables.x_call_api_uri;492}493/**494 * 戻り先のURLを取得495 * @private496 * @param {Object} r497 * @return {string}498 */499function getRemoteFullUrl(r) {500 return r.variables.scheme + "://" + r.variables.remote_addr + ":" + r.variables.remote_port + "/";501}502/**503 * イントロスペクションURLを取得504 * @private505 * @return {string}506 */507function getOAuth2TokenIntrospectEndpoint() {508 return config_json.oauth.oauth_token_introspect_endpoint;509}510/**511 * トークンエンドポイントURLを取得512 * @private513 * @return {string}514 */515function getOAuth2TokenEndpoint() {516 return config_json.oauth.oauth_token_endpoint;517}518/**519 * システムのAuthorizationヘッダーに登録する値を取得 520 * @private521 * @return {string} 522 */523function getCallSystemApiAuthorization() {524 return nvl(config_json.call_system_api_headers.authorization, "");525}526/**527 * システムのAPIキーを使用した、独自のヘッダーに登録する値を取得 528 * @private529 * @return {string} 530 */531function getCallSystemApiApiKey() {532 return nvl(config_json.call_system_api_headers.api_key, "");533}534/**535 * アクセスログ出力536 * @private537 * @param {Object} r538 */539function create_log_nginx_variables_str(r) {540 var log_nginx_variables_str = "";541 var log_nginx_variables = config_json.log_nginx_variables;542 if (typeof (log_nginx_variables) === "undefined") {543 throw new SyntaxError('log_nginx_variables null ');544 }545 // 全出力546 log_nginx_variables.forEach(function (log_nginx_variable_obj) {547 // ","は中身によらず追加548 log_nginx_variables_str += ",";549 if (log_nginx_variable_obj["flag"] === true) {550 // trueならば追加551 var log_nginx_variable_name = log_nginx_variable_obj["log_nginx_variable"];552 log_nginx_variables_str += r.variables[log_nginx_variable_name];553 }554 });555 return log_nginx_variables_str;556}557/**558 * アクセスログ出力559 * @private560 * @param {Object} r561 * @param {number} rp_flag API参照側 API提供側 1,2562 * @param {string} from_uri REMOTE or HOST or ACCESS563 * @param {string} to_uri アクセスするURI564 * @param {string} method r.method もしくはcall_api_method565 * @param {string} msg メッセージ566 */567function print_accesslog(r, rp_flag, from_uri, to_uri, method, msg) {568 var arg_len_no_success = 4;569 var arg_len = 6;570 if (arguments.length !== arg_len_no_success && arguments.length !== arg_len) {571 throw new SyntaxError('It was called with ' + arguments.length + ' arguments,but ' + arg_len + ' arguments are required.' + "," + msg);572 }573 if (typeof (from_uri) === "undefined") {574 throw new SyntaxError('from_uri null.');575 }576 if (typeof (to_uri) === "undefined") {577 throw new SyntaxError('to_uri null.');578 }579 // 共通580 // API参照側とAPI提供側で分ける581 var request_id;582 if (rp_flag === RP_FLAG.REFERENCE) {583 request_id = r.variables.request_id;584 } else {585 // API提供側:provision586 request_id = r.variables.http_x_request_id;587 }588 // アクセス元ドメインとポート uriからprotocolとuriを削除589 var from_addr_port = from_uri.replace(/https?:\/\//, "").replace(/\/.*/, "");590 // アクセス先ドメインとポート uriからprotocolとuriを削除591 var to_addr_port = to_uri.replace(/https?:\/\//, "").replace(/\/.*/, "");592 var log_nginx_variables_str = create_log_nginx_variables_str(r);593 // 引数の検査594 if (arguments.length === arg_len_no_success) {595 // 引数4つ目は_access_point(msg)596 r.log(",Info," + request_id + "," + source_client_id + "," + desitination_client_id + "," + formatDate(new Date()) + ",-,-,-,-,\"" + to_uri.replace(/"/g, "\"\"") + "\"" + log_nginx_variables_str);597 } else if (arguments.length === arg_len) {598 // ログ出力599 r.log(",Info," + request_id + "," + source_client_id + "," + desitination_client_id + "," + formatDate(new Date()) + "," + from_addr_port + "," + to_addr_port + "," + to_uri + "," + method + ",\"" + msg.replace(/"/g, "\"\"") + "\"" + log_nginx_variables_str);600 }601}602/**603 * エラーログ出力604 * @private605 * @param {Object} r606 * @param {string} rp_flag API参照側:REFERENCE:1 API提供側:PROVISION:2607 * @param {string} errorName エラー名608 */609function print_warnlog(r, rp_flag, msg) {610 // 共通611 // API参照側とAPI提供側で分ける612 var request_id;613 if (rp_flag === RP_FLAG.REFERENCE) {614 // API参照側:reference615 request_id = r.variables.request_id;616 } else {617 // API提供側:provision618 request_id = r.variables.http_x_request_id;619 }620 var log_nginx_variables_str = create_log_nginx_variables_str(r);621 r.warn(",Warn," + request_id + "," + source_client_id + "," + desitination_client_id + "," + formatDate(new Date()) + ",-,-,-,-,\"" + msg.replace(/"/g, "\"\"") + "\"" + log_nginx_variables_str);622}623/**624 * エラーログ出力625 * @private626 * @param {Object} r627 * @param {string} rp_flag API参照側:REFERENCE:1 API提供側:PROVISION:2628 * @param {string} errorName エラー名629 * @param {string} errorDetail エラー詳細 stacktraceや説明(description)630 */631function print_errorlog(r, rp_flag, errorName, errorDetail) {632 //accessログと同じように633 // API提供側:provision634 var request_id;635 if (rp_flag === RP_FLAG.REFERENCE) {636 // API参照側:reference637 request_id = r.variables.request_id;638 } else {639 // API提供側:provision640 request_id = r.variables.http_x_request_id;641 }642 var log_nginx_variables_str = create_log_nginx_variables_str(r);643 r.error(",Error," + request_id + "," + source_client_id + "," + desitination_client_id + "," + formatDate(new Date()) + ",-,-,-,-," + "\"Error:[" + errorName + "]" + "," + "Description:[" + errorDetail.replace(/"/g, "\"\"") + "]\"" + log_nginx_variables_str);644}645/**646 * アクセストークンaud,idの妥当性検証647 * @private648 * @param {Object} config_json 設定ファイル649 * @param {string} request_uri call_api_url650 * @param {string} request_method call_api_method651 * @param {Object} introspection_response introspection_response652 * @return {obj|EdgeError}\{"check_flag":boolean,"message":string"}653 */654function checkGbizidAndCorpid(r, introspection_response) {655 var i = 0;656 var ErrorArray = [];657 var arg_gbizid = r.args.gbizid;658 var arg_corpid = r.args.corpid;659 var gbizid_sub = introspection_response.gbizid_sub;660 var gbizid_corporate_number = introspection_response.gbizid_corporate_number;661 if (!(typeof (arg_corpid) === "undefined") && !(arg_corpid === gbizid_corporate_number)) {662 ErrorArray[i++] = "The value of the parameter [ corpid ] does not match the registered value . ";663 }664 if (!(typeof (arg_gbizid) === "undefined") && !(arg_gbizid === gbizid_sub)) {665 ErrorArray[i++] = "The value of the parameter [ gbizid ] does not match the registered value . ";666 }667 if (ErrorArray.length > 0) {668 return new EdgeError(403, ErrorArray.join());669 }670}671/**672 * アクセストークンaud,idの妥当性検証673 * @private674 * @param {Object} config_json 設定ファイル675 * @param {string} request_uri call_api_url676 * @param {string} request_method call_api_method677 * @param {Object} introspection_response introspection_response678 * @return {obj|EdgeError}\{"check_flag":boolean,"message":string"}679 */680function checkIdAud(config_json, request_uri, request_method, introspection_response) {681 var result_obj = {};682 // 1. アクセストークンのaudのチェック683 // aud と 自分のクライアントID684 if (introspection_response["aud"] !== config_json.client_id) {685 // 一致しないとき686 return new EdgeError(403, "Client ID does not match with aud.(aud:" + introspection_response["aud"] + ")");687 }688 // マップから利用許可したクライアントIDのリストを取得689 var authorized_client_list = config_json.authorized_client_list;690 // 2. アクセストークンのclient_idのチェック691 if (introspection_response["azp"]) {692 // azpから取得693 source_client_id = introspection_response["azp"];694 } else {695 return new EdgeError(403, "Could not get Client ID from access token.");696 }697 var client_id_exist = false;698 var authorized_client_obj;699 for (var i = 0; i < authorized_client_list.length; i++) {700 var tmp_authorized_client_obj = authorized_client_list[i];701 // 利用許可されているクライアントIDかどうか702 if (tmp_authorized_client_obj["client_id"] === source_client_id) {703 // 一致するならば、エンドポイントを比較するためいったん退避704 authorized_client_obj = tmp_authorized_client_obj;705 client_id_exist = true;706 break;707 }708 }709 // 返却用JSON作成710 if (client_id_exist !== true) {711 return new EdgeError(403, "Unpermitted Client ID.(" + source_client_id + ")");712 }713 // 3. 利用許可したAPIかチェック714 var endpoint_exist = false;715 // 退避したエンドポイントからメソッドとURIの一致をみる716 authorized_client_obj.endpoint.forEach(function (endpoint_obj) {717 var endpoint_obj_uri = addDefaultPort(endpoint_obj.uri);718 if (request_uri.match(endpoint_obj_uri) && endpoint_obj.method === request_method) {719 endpoint_exist = true;720 }721 });722 // 返却用JSON作成723 if (endpoint_exist !== true) {724 return new EdgeError(403, "Unpermitted URI.(" + request_uri + "," + request_method + ")");725 }726 // 正常な場合のみここへ到達する727 result_obj.check_flag = true;728 return result_obj;729}730/**731 * 732 * @param {reply} reply733 * @param {orgObj} obj 734 * @param {introspection_response} obj 735 * @rturn736 */737function addMetadata(reply, orgObj, introspection_response) {738 var editJson = JSON.parse("{}");739 if (config_json.meta.add_flag) {740 source_client_id = introspection_response["azp"];741 desitination_client_id = config_json.client_id;742 var system_name;743 system_name = config_json.system_name;744 var scope;745 var scopes = [];746 scope = introspection_response.scope;747 if (!(typeof (scope) === "undefined")) {748 var scopesArray = scope.split(" ");749 for (var i = 0; i < scopesArray.length; i++) {750 scopes.push(scopesArray[i]);751 }752 }753 var time;754 time = reply.variables.request_time;755 editJson["meta"] = JSON.parse("{}");756 editJson["meta"]["source_client_id"] = source_client_id;757 editJson["meta"]["desitination_client_id"] = desitination_client_id;758 editJson["meta"]["system_name"] = system_name;759 editJson["meta"]["scopes"] = scopes;760 editJson["meta"]["request_time"] = time;761 editJson["meta"]["timestamp"] = formatDate(new Date());762 }763 editJson["data"] = JSON.parse(orgObj);764 return JSON.stringify(editJson, undefined, "\t");765}766/**767 * オブジェクトの最下層の値の取得768 * @private769 * @param {Object} obj 取得用オブジェクト770 * @param {Array<string>} array "."で分割した配列771 * @param {Object} r リクエストオブジェクト772 * @return {Map<string,string>} retrunMap773 */774function getEndValues(obj, array, r) {775 var deepNum = 0;776 var tempObj = obj;777 var indexMap = {};778 var index = 0;779 var returnMap = {};780 var fullkey = "";781 while (true) {782 var key = array[deepNum];783 key = key.replace(/\[\]$/, "");784 fullkey += key;785 // 末端を登録786 if (deepNum === array.length - 1) {787 if (!(typeof (tempObj[key]) === "undefined")) {788 returnMap[fullkey] = tempObj[key];789 }790 delNum = fullkey.lastIndexOf("[");791 if (delNum === -1) {792 return returnMap;793 } else {794 fullkey = fullkey.substring(0, delNum);795 index = indexMap[fullkey];796 index++;797 indexMap[fullkey] = index;798 }799 // tempObj他、リセット800 deepNum = 0;801 tempObj = obj;802 fullkey = "";803 continue;804 }805 var isArrayValue = Array.isArray(tempObj[key]);806 // 末端でなければ、一つ階層を落とす807 if (isArrayValue) {808 if (!(indexMap.hasOwnProperty(fullkey))) {809 // 最初810 indexMap[fullkey] = 0;811 }812 index = indexMap[fullkey];813 if (index >= tempObj[key].length) {814 var delNum = fullkey.lastIndexOf("[");815 if (delNum === -1) {816 return returnMap;817 } else {818 fullkey = fullkey.substring(0, delNum);819 index = indexMap[fullkey];820 index++;821 indexMap[fullkey] = index;822 }823 // tempObj他、リセット824 deepNum = 0;825 tempObj = obj;826 fullkey = "";827 continue;828 }829 fullkey += "[" + index + "]";830 tempObj = tempObj[key][index];831 } else {832 tempObj = tempObj[key];833 }834 if (typeof (tempObj) === "undefined") {835 delNum = fullkey.lastIndexOf("[");836 if (delNum === -1) {837 return returnMap;838 } else {839 fullkey = fullkey.substring(0, delNum);840 index = indexMap[fullkey];841 index++;842 indexMap[fullkey] = index;843 }844 // tempObj他、リセット845 deepNum = 0;846 tempObj = obj;847 fullkey = "";848 continue;849 }850 fullkey += ".";851 deepNum++;852 }853}854/**855 * オブジェクトの最下層の値への登録856 * @private857 * @param {Object} obj 登録用オブジェクト858 * @param {Map<string,string>} map 登録用キーMap859 * @param {Object} r リクエストオブジェクト860 */861function setEndValues(obj, map, r) {862 Object.entries(map).forEach(function (entry) {863 // entry = [key , value]864 var keyArray = entry[0].split(".");865 setEndValue(entry[1], obj, keyArray, r);866 });867}868/**869 * オブジェクトの最下層の値への登録870 * @private871 * @param {string} value セットする値872 * @param {Object} obj 登録用オブジェクト873 * @param {Array<string>} array "."で分割した配列874 * @param {Object} r リクエストオブジェクト875 */876function setEndValue(value, obj, array, r) {877 if (typeof (value) === "undefined") {878 return;879 }880 var deepNum = 0;881 var nextKey;882 var nextKeySize;883 var nextKeyArray;884 var nextKeyArrayStr;885 var isArrayNextKey;886 var match = /([^[]*)\[([0-9]+)\]$/;887 while (deepNum < array.length - 1) {888 nextKey = array[deepNum];889 isArrayNextKey = nextKey.match(match);890 if (isArrayNextKey) {891 nextKeyArrayStr = nextKey.replace(match, function (str, p1, p2) {892 var obj = { "nextKey": p1, "nextKeySize": parseInt(p2) };893 return JSON.stringify(obj);894 });895 nextKeyArray = JSON.parse(nextKeyArrayStr);896 nextKey = nextKeyArray["nextKey"];897 nextKeySize = nextKeyArray["nextKeySize"];898 }899 if (typeof (obj[nextKey]) === "undefined") {900 // 現在のeditJSONに存在しないなら新規作成901 if (isArrayNextKey) {902 obj[nextKey] = [];903 } else {904 obj[nextKey] = {};905 }906 }907 // 配列分作成908 if (isArrayNextKey) {909 for (var i = 0; i < nextKeySize + 1; i++) {910 if (typeof (obj[nextKey][i]) === "undefined") {911 obj[nextKey][i] = {};912 }913 }914 }915 // 階層を一つ進める916 if (isArrayNextKey) {917 obj = obj[nextKey][nextKeySize];918 } else {919 obj = obj[nextKey];920 }921 deepNum++;922 }923 // 現在の階層へ値を登録.924 nextKey = array[deepNum];925 isArrayNextKey = nextKey.match(match);926 if (isArrayNextKey) {927 nextKeyArrayStr = nextKey.replace(match, function (str, p1, p2) {928 var obj = { "nextKey": p1, "nextKeySize": parseInt(p2) };929 return JSON.stringify(obj);930 });931 nextKeyArray = JSON.parse(nextKeyArrayStr);932 nextKey = nextKeyArray["nextKey"];933 nextKeySize = nextKeyArray["nextKeySize"];934 }935 if (isArrayNextKey) {936 obj[nextKey][nextKeySize] = value;937 } else {938 obj[nextKey] = value;939 }940 return;941}942/**943 * URI変換944 * @private945 * @param {Map<string,string>} map URI変換前キーMap946 * @param {string} extrUri 抽出URI947 * @param {string} replUri 置換URI948 * @param {Object} r リクエストオブジェクト949 */950function convertUri(map, extrUri, replUri, r) {951 var mapUri = Object.keys(map)[0];952 if (typeof (mapUri) === "undefined") {953 print_warnlog(r, RP_FLAG.PROVISION, "レスポンスデータに[" + extrUri + "]に該当するキーは存在しないため変換しません。");954 return;955 }956 extrUri = extrUri.replace(/\[\]$/, "");957 replUri = replUri.replace(/\[\]$/, "");958 var arrayExtrUri = extrUri.split(/\[\]./);959 var arrayReplUri = replUri.split(/\[\]./);960 var arraymapUri = mapUri.split(/\[[0-9]*\]./);961 if (arrayExtrUri.length === arrayReplUri.length && arrayReplUri.length === arraymapUri.length) {962 // 同じ場合置換963 Object.entries(map).forEach(function (p) {964 // entry = [key , value]965 var p_value = p[1];966 var p_key = p[0];967 delete map[p_key];968 var new_key = p[0];969 Object.keys(arrayExtrUri).forEach(function (index) {970 new_key = new_key.replace(arrayExtrUri[index], arrayReplUri[index]);971 });972 map[new_key] = p_value;973 });974 } else {975 // 抽出の方が大きい場合976 // 置換の方が大きい場合977 print_warnlog(r, RP_FLAG.PROVISION, "JSON変換ルールに配列の個数誤りがあるため変換できません。[" + replUri + "],[" + extrUri + "]");978 Object.entries(map).forEach(function (p) {979 delete map[p[0]];980 });981 }982}983/**984 * マッピング985 * @private986 * @param {Object} obj987 * @param {Array<Object>} json_convert_mappings988 * @param {number} get_set_flag989 * @param {number} r990 * @return {Object} edit_obj991 */992function mapping(obj, json_convert_mappings, get_set_flag, r) {993 var edit_obj = {};994 var methodNum = 0;995 if (get_set_flag === GET_SET_FLAG.GET) {996 methodNum++;997 }998 var j = 0;999 for (var i = 0; i < json_convert_mappings.length; i++) {1000 var mapping = json_convert_mappings[i];1001 var uriArray = [mapping.datastore, mapping.response];1002 var array_datastore = mapping.datastore.split(".");1003 var array_response = mapping.response.split(".");1004 var arrayArray = [array_datastore, array_response];1005 // XOR GET 1^1->0 1^0->1 ^GET 0^1->1 0^0->01006 var map = getEndValues(obj, arrayArray[methodNum ^ 1], r);1007 convertUri(map, uriArray[methodNum ^ 1], uriArray[methodNum ^ 0], r);1008 setEndValues(edit_obj, map, r);1009 }1010 return edit_obj;1011}1012/**1013 * オブジェクトの最下層の値の取得1014 * @private1015 * @param {Object} obj 取得用オブジェクト1016 * @param {Array<string>} array "."で分割した配列1017 * @return {Object} obj1018 */1019function getEndValue(obj, array) {1020 var deepNum = 0;1021 while (deepNum < array.length) {1022 if (typeof (obj[array[deepNum]]) === "undefined") {1023 // 存在しないKeyは取得しない1024 return;1025 } else {1026 // 階層を一つ進める1027 obj = obj[array[deepNum]];1028 }1029 deepNum++;1030 }1031 // 現在の階層の値をreturn1032 return obj;1033}1034/**1035 * JSONから配列へのマッピング1036 * @private1037 * @param {Object} obj1038 * @param {Array<Object>} arrayConvertMappings1039 * @param {number} get_set_flag1040 * @return {Object} editObj1041 */1042function arrayMapping(obj, arrayConvertMappings, get_set_flag) {1043 if (get_set_flag === GET_SET_FLAG.GET) {1044 var editObj;1045 } else {1046 return obj;1047 }1048 for (var i = 0; i < arrayConvertMappings.length; i++) {1049 var mapping = arrayConvertMappings[i];1050 var listDatastore = mapping.datastore.split(".");1051 var endValue = getEndValue(obj, listDatastore);1052 editObj = endValue;1053 if (editObj != null) {1054 return editObj;1055 } else {1056 return;1057 }1058 }1059 return editObj;1060}1061/**1062 * XML変換1063 * @private1064 * @param {Object} r1065 * @param {string} orgJsonStr1066 * @param {number} getSetFlag1067 * @return {Object}1068 */1069function convertXml(r, orgJsonStr, getSetFlag) {1070 var callApiUri = r.variables.request_uri;1071 var callApiMethod = r.method;1072 var xmlConverts = config_json.xml_converts;1073 //configファイルにxml変換の記述がない場合、xml変換は行わない1074 if (!xmlConverts) {1075 return orgJsonStr;1076 }1077 for (var i = 0; i < xmlConverts.length; i++) {1078 var xmlConvert = xmlConverts[i];1079 if (callApiUri.match(xmlConvert.xml_convert_uri)1080 && callApiMethod.match(xmlConvert.xml_convert_method)) {1081 //xml変換フラグの取得1082 var xmlFlag;1083 if (getSetFlag === GET_SET_FLAG.GET) {1084 if (callApiMethod.match("GET")) {1085 xmlFlag = xmlConvert.xml_convert_get_flag;1086 }1087 }1088 //xmlFlag=falseもしくはundefinedのときXML変換は行わない1089 if (!xmlFlag) {1090 return orgJsonStr;1091 }1092 if (getSetFlag === GET_SET_FLAG.GET) {1093 //JSONの"xml":キーにxmlを丸める1094 if (!callApiMethod.match("GET")) {1095 return orgJsonStr;1096 } else {1097 return "{\"xml\"\: \"" + orgJsonStr.replace(/\n/g, "") + "\"}";1098 }1099 } else {1100 return orgJsonStr;1101 }1102 }1103 }1104 return orgJsonStr;1105}1106/**1107 * JSON変換1108 * @private1109 * @param {Object} r1110 * @param {string} org_json_str1111 * @param {number} get_set_flag1112 * @return {Object}1113 */1114function convert_json(r, org_json_str, get_set_flag) {1115 var call_api_uri = r.variables.request_uri;1116 var call_api_method = r.method;1117 // json_converts1118 var json_converts = config_json.json_converts;1119 for (var i = 0; i < json_converts.length; i++) {1120 var json_convert = json_converts[i];1121 if (call_api_uri.match(json_convert.json_convert_uri)1122 && call_api_method.match(json_convert.json_convert_method)) {1123 // arrayFlagの取得1124 var arrayFlag;1125 if (get_set_flag === GET_SET_FLAG.GET) {1126 arrayFlag = json_convert.array_convert_get_flag;1127 }1128 if (arrayFlag === true) {1129 var arrayConvertRule = json_convert.array_convert_rule;1130 var arrayConvertRules = config_json.array_convert_rules;1131 var arrayConvertMappings = arrayConvertRules[arrayConvertRule];1132 if (typeof (arrayConvertMappings) === "undefined") {1133 // ルールがないときは変換しない1134 print_warnlog(r, RP_FLAG.PROVISION, "array_convert_mappings variable is undefined.");1135 break;1136 }1137 } else {1138 // json_flagの取得1139 var json_flag;1140 if (get_set_flag === GET_SET_FLAG.GET) {1141 json_flag = json_convert.json_convert_get_flag;1142 } else {1143 json_flag = json_convert.json_convert_set_flag;1144 }1145 // json_flag=falseもしくはundefinedのときJSON変換は行わない1146 if (!json_flag) {1147 return org_json_str;1148 }1149 var json_convert_rule = json_convert.json_convert_rule;1150 var json_convert_rules = config_json.json_convert_rules;1151 var json_convert_mappings = json_convert_rules[json_convert_rule];1152 if (typeof (json_convert_mappings) === "undefined") {1153 // ルールがないときは変換しない1154 print_warnlog(r, RP_FLAG.PROVISION, "json_convert_mappings variable is undefined.");1155 break;1156 }1157 }1158 // 編集するためにオブジェクトに変換1159 var tmpJson = JSON.parse(org_json_str);1160 var edit_json;1161 if (Array.isArray(tmpJson)) {1162 edit_json = [];1163 for (var num = 0; num < tmpJson.length; num++) {1164 if (!arrayFlag) {1165 var edit_obj = mapping(tmpJson[num], json_convert_mappings, get_set_flag, r);1166 edit_json.push(edit_obj);1167 } else {1168 var edit_obj = arrayMapping(tmpJson[num], arrayConvertMappings, get_set_flag);1169 if (edit_obj) {1170 edit_json.push(edit_obj);1171 }1172 }1173 }1174 } else {1175 if (!arrayFlag) {1176 edit_json = mapping(tmpJson, json_convert_mappings, get_set_flag, r);1177 } else {1178 edit_json = arrayMapping(tmpJson, arrayConvertMappings, get_set_flag);1179 }1180 }1181 // 編集したデータをJSON形式に変換1182 var edit_json_str = JSON.stringify(edit_json, undefined, "\t");1183 return edit_json_str;1184 }1185 }1186 // URIが一致しない場合、JSON変換はしない1187 print_warnlog(r, RP_FLAG.PROVISION, "This API can not perform JSON conversion.");1188 return org_json_str;1189}1190/**1191 * スコープマッピング1192 * @private1193 * @param {string} tmpJson1194 * @param {Array<string>} requestScopes1195 * @return {Object}1196 */1197function scopeMapping(tmpJson, requestScopes) {1198 var edit_json = {};1199 // 対象APPのスコープ一覧ごとに、requestScopes、responseBody に含まれる場合のみ追加1200 for (var i = 0; i < SCOPE_MAPPINGS.length; i++) {1201 var scopeMapping = SCOPE_MAPPINGS[i];1202 //scopeMapping.scope がrequestScopesに含まれ1203 //scopeMapping.data_itemがObject.keys(tmpJson) に含まれる場合1204 if (requestScopes.includes(scopeMapping.scope)1205 && Object.keys(tmpJson).includes(scopeMapping.data_item)) {1206 //返却用jsonのみ取り出し1207 edit_json[scopeMapping.data_item] = tmpJson[scopeMapping.data_item];1208 }1209 }1210 return edit_json;1211}1212/**1213 * スコープ絞り込み1214 * @private1215 * @param {string} responseBody1216 * @param {string} scope1217 * @return {Object}1218 */1219function scopeFiltering(responseBody, scope) {1220 //1.スコープが指定されているかチェック1221 //設定ファイルから対象APPのスコープ一覧を取り出す1222 var scopes = [];1223 for (var i = 0; i < SCOPE_MAPPINGS.length; i++) {1224 scopes.push(SCOPE_MAPPINGS[i].scope);1225 }1226 //scope を取り出す " "でsplit1227 var requestScopes = scope.split(" ");1228 //スコープが指定されているかいないか1229 var is_scope_specified = false;1230 for (var i = 0; i < requestScopes.length; i++) {1231 if (scopes.includes(requestScopes[i])) {1232 is_scope_specified = true;1233 break;1234 }1235 }1236 //スコープが指定されていない場合、全データを返却する1237 if (!is_scope_specified) {1238 return responseBody;1239 }1240 //2.スコープを絞り込む1241 // 編集するためにオブジェクトに変換1242 var tmpJson = JSON.parse(responseBody);1243 var edit_json;1244 // 配列の場合1245 if (Array.isArray(tmpJson)) {1246 edit_json = [];1247 for (var num = 0; num < tmpJson.length; num++) {1248 var edit_obj = scopeMapping(tmpJson[num], requestScopes);1249 edit_json.push(edit_obj);1250 }1251 } else {1252 edit_json = scopeMapping(tmpJson, requestScopes);1253 }1254 var edit_json_str = JSON.stringify(edit_json, undefined, "\t");1255 return edit_json_str;1256}1257/**1258 * バイナリデータのリクエストボディに送信元クライアントIDを追加する1259 * @private1260 * @param {Object} r1261 * @param {string} requestBody1262 * @param {Object} introspection_response1263 * @return {string}1264 */1265function addClientIdForBinary(r, requestBody, introspection_response) {1266 if (isEmpty(requestBody)) {1267 return requestBody;1268 }1269 var tmpRequestBody = JSON.parse(requestBody);1270 if (isEmpty(tmpRequestBody["Binary"])) {1271 return requestBody;1272 } else {1273 tmpRequestBody["Binary"]["source_client_id"] = introspection_response["azp"];1274 return JSON.stringify(tmpRequestBody);1275 }1276}1277/**1278 * 空判定1279 * value =undefined true1280 * value ="" true1281 * @private1282 * @param {string} value1283 * @return {boolean}1284 */1285function isEmpty(value) {1286 return (typeof (value) === "undefined") || (value === "")|| (value === null);1287}1288/**1289 * 式 expr1 が NULL もしくは undefined なら expr2 の値を戻す。1290 * nullValueLogic *1291 * @private1292 * @param {string} expr11293 * @param {string} expr21294 * @return {boolean}1295 */1296function nvl(expr1, expr2) {1297 return (typeof (expr1) === "undefined" || expr1 === null) ? expr2 : expr1;1298}1299/**1300 * URLにデフォルトポートを付ける1301 * @private1302 * @param {string} uri1303 * @return {boolean}1304 */1305function addDefaultPort(uri) {1306 if (typeof (uri) === "undefined") {1307 return uri;1308 } else if (uri.match(new RegExp("^.?http://", ""))) {1309 var domain = uri.match(/^.?(http:\/\/[^\/]+).*/)[1];1310 if (!domain.match(new RegExp(":[0-9]+$", ""))) {1311 var domainWithDefaultPort = domain + ":80"1312 uri = uri.replace(domain, domainWithDefaultPort)1313 }1314 } else if (uri.match(new RegExp("^.?https://", ""))) {1315 var domain = uri.match(/^.?(https:\/\/[^\/]+).*/)[1];1316 if (!domain.match(new RegExp(":[0-9]+$", ""))) {1317 var domainWithDefaultPort = domain + ":443"1318 uri = uri.replace(domain, domainWithDefaultPort)1319 }1320 }1321 return uri;1322}1323/**1324 * アクセストークンの取得 (事前同意)1325 * BASE64エンコードおよびアクセストークンの取得1326 * @param {Object} r1327 */1328function get_access_token(r) {1329 // 設定ファイルの不正はリターン1330 if (config_json instanceof EdgeError) {1331 print_errorlog(r, RP_FLAG.REFERENCE, "Config File Error", config_json.getLogMessage());1332 r.return(config_json.getStatus(), config_json.getJsonResponse());1333 return;1334 }1335 source_client_id = config_json.client_id;1336 var basicAuthPlaintext = config_json["client_id"] + ":" + config_json["client_secret"];1337 // base64変換1338 var authHeader = "Basic " + basicAuthPlaintext.toBytes().toString('base64');1339 // リクエストボディをデコード1340 var requestBody_json = decode_requestBody(r);1341 if (requestBody_json instanceof EdgeError || (requestBody_json = check_requestBody(requestBody_json)) instanceof EdgeError) {1342 print_errorlog(r, RP_FLAG.REFERENCE, "HTTP Request Error", requestBody_json.getLogMessage());1343 r.return(requestBody_json.getStatus(), requestBody_json.getJsonResponse());1344 return;1345 }1346 desitination_client_id = requestBody_json.client_id;1347 print_accesslog(r, RP_FLAG.REFERENCE, getRemoteFullUrl(r), getHostFullUrl(r), r.method, "Succeeded in calling the Internal API.");1348 // scope組み立て1349 // aud に client_id を含める1350 var scope = desitination_client_id;1351 // scope1352 if (typeof (requestBody_json.scope) !== "undefined") {1353 scope += " " + requestBody_json.scope;1354 }1355 print_accesslog(r, RP_FLAG.REFERENCE, getHostFullUrl(r), getOAuth2TokenEndpoint(), r.method, "Called Authorization Server.");1356 var uri = "/_oauth2_client_credentials_request";1357 r.subrequest(uri,1358 { method: r.method, body: "grant_type=client_credentials" + "&scope=" + scope, args: "authorization=" + authHeader },1359 function (reply) {1360 var response;1361 if (200 <= reply.status && reply.status < 300) {1362 try {1363 response = JSON.parse(reply.responseBody);1364 // 認証の成功を確認する1365 if (typeof (response.access_token) !== "undefined") {1366 // 認証に成功している場合1367 print_accesslog(r, RP_FLAG.REFERENCE, getOAuth2TokenEndpoint(), getHostFullUrl(r), r.method, "Succeeded in calling Authorization Server.");1368 // 法人データモジュール へリクエストを投げる1369 call_edgemodule(r, response.access_token, requestBody_json);1370 } else {1371 // 認証に失敗している場合1372 print_accesslog(r, RP_FLAG.REFERENCE, getOAuth2TokenEndpoint(), getHostFullUrl(r), r.method, "Invalid error.");1373 print_errorlog(r, RP_FLAG.REFERENCE, "Authorization Error", reply.responseBody);1374 r.return(reply.status, reply.responseBody);1375 return;1376 }1377 } catch (e) {1378 print_accesslog(r, RP_FLAG.REFERENCE, getOAuth2TokenEndpoint(), getHostFullUrl(r), r.method, "Failed to call Authorization Server.");1379 print_errorlog(r, RP_FLAG.REFERENCE, "Authorization Error", reply.responseBody);1380 r.return(reply.status, reply.responseBody);1381 return;1382 }1383 } else {1384 // 成功レスポンス以外1385 print_accesslog(r, RP_FLAG.REFERENCE, getOAuth2TokenEndpoint(), getHostFullUrl(r), r.method, "Failed to call Authorization Server.");1386 print_errorlog(r, RP_FLAG.REFERENCE, "Authorization Error", reply.responseBody);1387 r.return(reply.status, toJSON(reply.status, reply.responseBody));1388 return;1389 }1390 }1391 );1392}1393/**1394 * ログを出した後、luaへ接続(都度同意)1395 * @param {Object} r1396 */1397function checkAuthorizationServer(r) {1398 // 設定ファイルの不正はリターン1399 if (config_json instanceof EdgeError) {1400 print_errorlog(r, RP_FLAG.REFERENCE, "Config File Error", config_json.getLogMessage());1401 r.return(config_json.getStatus(), config_json.getJsonResponse());1402 return;1403 }1404 var basicAuthPlaintext = config_json["client_id"] + ":" + config_json["client_secret"];1405 // base64変換1406 var authHeader = "Basic " + basicAuthPlaintext.toBytes().toString('base64');1407 var uri = "/_oauth2_client_credentials_request";1408 r.subrequest(uri,1409 { method: r.method, body: "grant_type=client_credentials", args: "authorization=" + authHeader },1410 function (reply) {1411 if (200 == reply.status) {1412 var returnStr = "{\"message\":\"認可サーバへアクセスできています。\"}";1413 r.return(reply.status, jsonStringifyFromJsonString(returnStr));1414 return;1415 } else {1416 r.return(reply.status, createErrorResponseForCheckAuthorizationServer(reply.status, reply.responseBody));1417 return;1418 }1419 }1420 );1421}1422/**1423 * 認可サーバのレスポンスのうちerror_descriptionがあるかどうか1424 */1425function checkErrorResponseFromAuthorizationServer(status, responseBody) {1426 //ステータスが400番台かつ1427 // 以下の形式で返却される場合はauthenticationからの応答1428 // {1429 // "error" : "...."1430 // "error_description" : "...."1431 // }1432 return (400 <= status && status < 500) && responseBody.hasOwnProperty("error_description");1433}1434/**1435 * Nodeで作ったエラーレスポンスかどうか1436 */1437function checkErrorResponseFromHTTPStatusCodeOnly(responseBody) {1438 // 以下の形式で返却される場合は,Nodeで作られたエラーレスポンス1439 // {1440 // "error" : {1441 // "message":"...." //errorMessages1442 // }1443 // }1444 var errorMessages = Object.values(CLIENT_ERROR_CODE_MESSAGES).concat(Object.values(SERVER_ERROR_CODE_MESSAGES));1445 return responseBody.hasOwnProperty("error")1446 && (errorMessages.includes(responseBody["error"]["message"]));1447}1448/**1449 */1450function createErrorResponseForCheckAuthorizationServer(status, responseBody_str) {1451 var responseBody;1452 try {1453 responseBody = JSON.parse(responseBody_str);1454 } catch (error) {1455 return new EdgeError(status, responseBody_str).getJsonResponse();1456 }1457 if (checkErrorResponseFromAuthorizationServer(status, responseBody)) {1458 //error_descriptionが含まれる場合1459 var response = {}1460 response["message"] = "認可サーバへアクセスできています。Gビズコネクトポータルからダウンロードしたノード設定ファイルをノードに反映してください。";1461 response["authorization_server_error_response"] = responseBody;1462 return jsonStringifyFromObject(response)1463 } else if (checkErrorResponseFromHTTPStatusCodeOnly(responseBody)) {1464 //ノードで作ったレスポンスの場合1465 //ステータスコードのみのレスポンスの場合、URIを追加1466 //typeを変更する1467 var rtnJson = responseBody1468 rtnJson["error"]["status"] = rtnJson["error"]["message"]1469 rtnJson["error"]["message"] = "認可サーバへアクセスできません。";1470 rtnJson["error"]["uri"] = getOAuth2TokenEndpoint();1471 rtnJson["error"]["type"] = undefined;1472 return jsonStringifyFromObject(rtnJson);1473 } else {1474 //それ以外の場合1475 var response = {}1476 response["message"] = "認可サーバからのエラーレスポンスを確認してください。";1477 response["authorization_server_error_response"] = responseBody;1478 return jsonStringifyFromObject(response)1479 }1480}1481/**1482 * ログを出した後、luaへ接続(都度同意)1483 * @param {Object} r1484 */1485function redirect_authorized(r) {1486 print_accesslog(r, RP_FLAG.REFERENCE, getRemoteFullUrl(r), getHostFullUrl(r), r.method, "Succeeded in calling the Internal API.");1487 print_accesslog(r, RP_FLAG.REFERENCE, getHostFullUrl(r), getRemoteFullUrl(r), r.method, "Requested Authentication screen.");1488 var uri = "/authorized";1489 r.internalRedirect(uri);1490}1491/**1492 * モジュールへ接続 (都度、事前共通)1493 * @private1494 * @param {Object} r1495 * @param {string} access_token1496 * @param {Object} requestBody_json1497 */1498function call_edgemodule(r, access_token, requestBody_json) {1499 var client_id = requestBody_json.client_id;1500 var call_api = requestBody_json.call_api;1501 var call_api_method = requestBody_json.method;1502 var call_api_accept = typeof (requestBody_json.accept) === "undefined" ? "" : requestBody_json.accept;1503 var call_api_contentType = typeof (requestBody_json["content-type"]) === "undefined" ? "" : requestBody_json["content-type"];1504 var call_api_body = requestBody_json.body;1505 // client_idからdomainを取ってきてcall_uriを作成1506 var domain;1507 var authorized_server_list = config_json["authorized_server_list"];1508 authorized_server_list.forEach(function (authorized_server) {1509 if (client_id === authorized_server.client_id) {1510 domain = authorized_server.domain;1511 }1512 });1513 var call_uri = domain + call_api;1514 print_accesslog(r, RP_FLAG.REFERENCE, getHostFullUrl(r), call_uri, call_api_method, "Called the External API.");1515 // &call_uri=[call_uri]?key=value1516 //->&call_uri=[call_uri]&key=value1517 call_uri = call_uri.replace(/\?/, "&");1518 var uri = "/_call_edgemodule";1519 var args = "access_token=" + access_token + "&call_uri=" + call_uri + "&contentType=" + call_api_contentType + "&accept=" + call_api_accept;1520 r.subrequest(uri,1521 { method: call_api_method, args: args, body: call_api_body },1522 function (reply) {1523 if (200 <= reply.status && reply.status < 300) {1524 // 正常1525 print_accesslog(r, RP_FLAG.REFERENCE, call_api, getHostFullUrl(r), r.method, "Succeeded in calling the External API.(request_time:" + reply.variables.request_time + "s)");1526 } else {1527 // エラーログのメッセージ1528 print_accesslog(r, RP_FLAG.REFERENCE, call_api, getHostFullUrl(r), r.method, "Failed to call the External API.");1529 print_errorlog(r, RP_FLAG.REFERENCE, "Call Node API Error", reply.responseBody);1530 }1531 // 上記以外のステータスはログ1532 // 共通1533 print_accesslog(r, RP_FLAG.REFERENCE, getHostFullUrl(r), getRemoteFullUrl(r), r.method, "Called the Internal API.");1534 // そのまま返却する1535 r.return(reply.status, toJSON(reply.status, reply.responseBody));1536 return;1537 }1538 );1539}1540/**1541 * 都度同意1542 * 取得1543 * @param {Object} r1544 */1545function tsudodoi(r) {1546 print_accesslog(r, RP_FLAG.REFERENCE, getRemoteFullUrl(r), getHostFullUrl(r), r.method, "Succeeded in calling the Internal API.");1547 print_accesslog(r, RP_FLAG.REFERENCE, getHostFullUrl(r), getRemoteFullUrl(r), r.method, "Requested Authentication screen.");1548 print_accesslog(r, RP_FLAG.REFERENCE, getHostFullUrl(r), getOAuth2TokenEndpoint(), r.method, "Called Authorization Server.");1549 print_accesslog(r, RP_FLAG.REFERENCE, getOAuth2TokenEndpoint(), getHostFullUrl(r), r.method, "Succeeded in calling Authorization Server.");1550 // リクエストボディをデコード1551 var requestBody_json = decode_requestBody(r);1552 // リクエストボディをチェック1553 if (requestBody_json instanceof EdgeError || (requestBody_json = check_requestBody(requestBody_json)) instanceof EdgeError) {1554 print_errorlog(r, RP_FLAG.REFERENCE, "HTTP Request Error", requestBody_json.getLogMessage());1555 r.return(requestBody_json.getStatus(), requestBody_json.getJsonResponse());1556 return;1557 }1558 // 法人データモジュール へリクエストを投げる1559 call_edgemodule(r, r.variables.http_x_access_token, requestBody_json);1560}1561/**1562 * イントロスペクション1563 * @param {Object} r1564 */1565function introspectAccessToken(r) {1566 // 設定ファイルの不正はリターン1567 if (config_json instanceof EdgeError) {1568 print_errorlog(r, RP_FLAG.PROVISION, "Config File Error", config_json.getLogMessage());1569 r.return(config_json.getStatus(), config_json.getJsonResponse());1570 return;1571 }1572 desitination_client_id = config_json.client_id;1573 try {1574 if (!isEmpty(r.variables.access_token)) {1575 var payloadStr = r.variables.access_token.split(".")[1];1576 //base64デコード1577 var payloadBase64decode = String.bytesFrom(payloadStr, 'base64');1578 var payload = JSON.parse(payloadBase64decode);1579 source_client_id = payload.azp;1580 } else {1581 throw new Error("Access token is missing or invalid.");1582 }1583 } catch (e) {1584 print_errorlog(r, RP_FLAG.PROVISION, "Authorization Error", e.stack);1585 r.return(401);// 401 Authorization Required1586 return;1587 }1588 // イントロスペクションリクエストのAuthorizationヘッダーを準備する1589 var basicAuthPlaintext = config_json["client_id"] + ":" + config_json["client_secret"];1590 // base64変換1591 var authHeader = "Basic " + basicAuthPlaintext.toBytes().toString('base64');1592 var call_api_method = r.variables.call_api_method;1593 print_accesslog(r, RP_FLAG.PROVISION, getRemoteFullUrl(r), getCallAPI(r), call_api_method, "Succeeded in calling the External API.");1594 print_accesslog(r, RP_FLAG.PROVISION, getHostFullUrl(r), getOAuth2TokenIntrospectEndpoint(), call_api_method, "Called Authorization Server.");1595 // Make the OAuth 2.0 Token Introspection request1596 r.subrequest("/_oauth2_send_introspection_request", "token=" + r.variables.access_token + "&authorization=" + authHeader,1597 function (reply) {1598 if (reply.status !== 200) {1599 print_accesslog(r, RP_FLAG.PROVISION, getOAuth2TokenIntrospectEndpoint(), getCallAPI(r), call_api_method, "Failed to call Authorization Server.");1600 print_errorlog(r, RP_FLAG.PROVISION, "Authorization Error", reply.responseBody);1601 r.return(401);// 401 Authorization Required1602 return;1603 }1604 // We have a response from authorization server, validate it has expected JSON schema1605 try {1606 var response = JSON.parse(reply.responseBody);1607 // We have a valid introspection response1608 // Check for validation success1609 if (response.active === true) {1610 print_accesslog(r, RP_FLAG.PROVISION, getOAuth2TokenIntrospectEndpoint(), getCallAPI(r), call_api_method, "Succeeded in calling Authorization Server.");1611 // Iterate over all members of the response and return them as response headers1612 r.headersOut['token-response'] = reply.responseBody;1613 r.status = 204;1614 r.sendHeader();1615 r.finish();1616 return;1617 } else {1618 print_accesslog(r, RP_FLAG.PROVISION, getOAuth2TokenIntrospectEndpoint(), getCallAPI(r), call_api_method, "OAuth token introspection found inactive token.");1619 print_errorlog(r, RP_FLAG.PROVISION, "Authorization Error", reply.responseBody);1620 r.return(403);1621 return;1622 }1623 } catch (e) {1624 print_accesslog(r, RP_FLAG.PROVISION, getOAuth2TokenIntrospectEndpoint(), getCallAPI(r), call_api_method, "OAuth token introspection response is not JSON: " + reply.body);1625 print_errorlog(r, RP_FLAG.PROVISION, "Authorization Error", reply.responseBody);1626 r.return(401);// 401 Authorization Required1627 return;1628 }1629 }1630 );1631}1632/**1633 * データ提供システムを呼び出す1634 * @param {Object} r1635 */1636function call_system_api_init(r) {1637 desitination_client_id = config_json.client_id;1638 // 有効なイントロスペクション応答があるか確認します1639 var introspection_response_str = r.variables.token_response;1640 var introspection_response = JSON.parse(introspection_response_str);1641 // デコード1642 var call_api = getCallAPI(r);1643 var call_api_method = r.method;1644 call_api = addDefaultPort(call_api);1645 // アクセストークンaud,idの妥当性検証1646 var check = checkIdAud(config_json, call_api, call_api_method, introspection_response);1647 if (check instanceof EdgeError) {1648 r.return(check.getStatus(), check.getJsonResponse());1649 print_errorlog(r, RP_FLAG.PROVISION, "Validation Error", check.getLogMessage());1650 return;1651 }1652 // 内部のsystemAPIへの変更はここ1653 // methodは各APIを引き継ぐ1654 var call_system_api_method = call_api_method;1655 // call_system_api のURL設定1656 // nginxのjs_setディレクティブからメソッドを呼び出すためここでは処理なし1657 // パラメータ1658 var param_obj = {};...

Full Screen

Full Screen

jquery.signalR.core.js

Source:jquery.signalR.core.js Github

copy

Full Screen

...169 else if (protocol === "https:") {170 return 443;171 }172 }173 function addDefaultPort(protocol, url) {174 // Remove ports from url. We have to check if there's a / or end of line175 // following the port in order to avoid removing ports such as 8080.176 if(url.match(/:\d+$/)) {177 return url;178 } else {179 return url + ":" + getDefaultPort(protocol);180 }181 }182 signalR.fn = signalR.prototype = {183 init: function (url, qs, logging) {184 this.url = url;185 this.qs = qs;186 this._ = {};187 if (typeof (logging) === "boolean") {188 this.logging = logging;189 } 190 },191 isCrossDomain: function (url, against) {192 /// <summary>Checks if url is cross domain</summary>193 /// <param name="url" type="String">The base URL</param>194 /// <param name="against" type="Object">195 /// An optional argument to compare the URL against, if not specified it will be set to window.location.196 /// If specified it must contain a protocol and a host property.197 /// </param>198 var link;199 url = $.trim(url);200 if (url.indexOf("http") !== 0) {201 return false;202 }203 against = against || window.location;204 // Create an anchor tag.205 link = window.document.createElement("a");206 link.href = url;207 // When checking for cross domain we have to special case port 80 because the window.location will remove the 208 return link.protocol + addDefaultPort(link.protocol, link.host) !== against.protocol + addDefaultPort(against.protocol, against.host);209 },210 ajaxDataType: "json",211 contentType: "application/json; charset=UTF-8",212 logging: false,213 state: signalR.connectionState.disconnected,214 keepAliveData: {},215 reconnectDelay: 2000,216 disconnectTimeout: 30000, // This should be set by the server in response to the negotiate request (30s default)217 keepAliveWarnAt: 2 / 3, // Warn user of slow connection if we breach the X% mark of the keep alive timeout218 start: function (options, callback) {219 /// <summary>Starts the connection</summary>220 /// <param name="options" type="Object">Options map</param>221 /// <param name="callback" type="Function">A callback function to execute when the connection has started</param>222 var connection = this,...

Full Screen

Full Screen

WSURI.js

Source:WSURI.js Github

copy

Full Screen

...26 var uri = new URI(location);27 if (isValidScheme(uri.scheme)) {28 this._uri = uri;29 if (uri.port == undefined) {30 this._uri = new URI(WSURI.addDefaultPort(location));31 }32 }33 else {34 throw new Error("WSURI - invalid scheme: " + location);35 }36 };37 function isValidScheme(scheme) {38 return "ws" == scheme || "wss" == scheme;39 }40 function duplicate(uri) {41 try {42 return new WSURI(uri);43 } catch (e) {44 throw e;...

Full Screen

Full Screen

cors.js

Source:cors.js Github

copy

Full Screen

...71 return lodash_1.default.isEqual(parsedUrl, props);72}73exports.urlMatchesOriginPolicyProps = urlMatchesOriginPolicyProps;74function urlMatchesOriginProtectionSpace(urlStr, origin) {75 var normalizedUrl = uri.addDefaultPort(urlStr).format();76 var normalizedOrigin = uri.addDefaultPort(origin).format();77 return lodash_1.default.startsWith(normalizedUrl, normalizedOrigin);78}...

Full Screen

Full Screen

uri.js

Source:uri.js Github

copy

Full Screen

...57 }58 return parsed;59}60exports.removeDefaultPort = removeDefaultPort;61function addDefaultPort(urlToCheck) {62 const parsed = parseClone(urlToCheck);63 if (!parsed.port) {64 // unset host...65 // see above for reasoning66 /* @ts-ignore */67 delete parsed.host;68 if (parsed.protocol) {69 parsed.port = DEFAULT_PROTOCOL_PORTS[parsed.protocol];70 }71 else {72 /* @ts-ignore */73 delete parsed.port;74 }75 }...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1Cypress.Commands.add('addDefaultPort', (url) => {2 if (url.indexOf(':') === -1) {3 url = url + ':443';4 }5 return url;6});7Cypress.Commands.add('addDefaultPort', (url) => {8 if (url.indexOf(':') === -1) {9 url = url + ':443';10 }11 return url;12});13Cypress.Commands.add('addDefaultPort', (url) => {14 if (url.indexOf(':') === -1) {15 url = url + ':443';16 }17 return url;18});19Cypress.Commands.add('addDefaultPort', (url) => {20 if (url.indexOf(':') === -1) {21 url = url + ':443';22 }23 return url;24});25Cypress.Commands.add('addDefaultPort', (url) => {26 if (url.indexOf(':') === -1) {27 url = url + ':443';28 }29 return url;30});31Cypress.Commands.add('addDefaultPort', (url) => {32 if (url.indexOf(':') === -1) {33 url = url + ':443';34 }35 return url;36});37Cypress.Commands.add('addDefaultPort', (url) => {38 if (url.indexOf(':') === -1)

Full Screen

Using AI Code Generation

copy

Full Screen

1Cypress.Commands.add("addDefaultPort", (url) => {2 if (Cypress.config("baseUrl")) {3 return url;4 } else {5 return Cypress.config("defaultCommandTimeout", 10000);6 }7});8import "./commands";9Cypress.on("uncaught:exception", (err, runnable) => {10 return false;11});12Cypress.Commands.add("addDefaultPort", (url) => {13 if (Cypress.config("baseUrl")) {14 return url;15 } else {16 return Cypress.config("defaultCommandTimeout", 10000);17 }18});19describe("TC01_Login", () => {20 beforeEach(() => {21 cy.visit("/");22 cy.server();23 cy.route("POST", "/api/Account/Login").as("login");24 });25 it("Login to the application", () => {26 cy.get("#UserName").type("admin");27 cy.get("#Password").type("admin");28 cy.get("input[type=submit]").click();29 cy.wait("@login");30 cy.get(".alert-success").should("be.visible");31 cy.url().should("include", "/Home/Index");32 });33});34describe("TC02_Logout", () => {35 beforeEach(() => {36 cy.visit("/");37 cy.server();38 cy.route("POST", "/api/Account/Login").as("login");39 cy.get("#UserName").type("admin");40 cy.get("#Password").type("admin");41 cy.get("input[type=submit]").click();42 cy.wait("@login");

Full Screen

Using AI Code Generation

copy

Full Screen

1const server = new CypressServer();2server.addDefaultPort(8080);3describe('Test', () => {4 it('should load', () => {5 });6});7addDefaultPort(port: number)8removeDefaultPort(port: number)9resetDefaultPorts()10getDefaultPorts()11getPort()12releasePort(port: number)13getPort()14getPort()15start()16stop()17isRunning()18isStopped()19isPortInUse(port: number)20getBaseUrl()

Full Screen

Using AI Code Generation

copy

Full Screen

1describe("Test to add default port", function () {2 it("Test to add default port", function () {3 cy.addDefaultPort();4 });5});6| `addDefaultPort(portNumber)` | This command adds default port to the url. |

Full Screen

Using AI Code Generation

copy

Full Screen

1it('Verify default port', () => {2 cy.addDefaultPort()3 cy.contains('Welcome to Cypress')4})5Cypress.Commands.add('addDefaultPort', () => {6})7{8}

Full Screen

Cypress Tutorial

Cypress is a renowned Javascript-based open-source, easy-to-use end-to-end testing framework primarily used for testing web applications. Cypress is a relatively new player in the automation testing space and has been gaining much traction lately, as evidenced by the number of Forks (2.7K) and Stars (42.1K) for the project. LambdaTest’s Cypress Tutorial covers step-by-step guides that will help you learn from the basics till you run automation tests on LambdaTest.

Chapters:

  1. What is Cypress? -
  2. Why Cypress? - Learn why Cypress might be a good choice for testing your web applications.
  3. Features of Cypress Testing - Learn about features that make Cypress a powerful and flexible tool for testing web applications.
  4. Cypress Drawbacks - Although Cypress has many strengths, it has a few limitations that you should be aware of.
  5. Cypress Architecture - Learn more about Cypress architecture and how it is designed to be run directly in the browser, i.e., it does not have any additional servers.
  6. Browsers Supported by Cypress - Cypress is built on top of the Electron browser, supporting all modern web browsers. Learn browsers that support Cypress.
  7. Selenium vs Cypress: A Detailed Comparison - Compare and explore some key differences in terms of their design and features.
  8. Cypress Learning: Best Practices - Take a deep dive into some of the best practices you should use to avoid anti-patterns in your automation tests.
  9. How To Run Cypress Tests on LambdaTest? - Set up a LambdaTest account, and now you are all set to learn how to run Cypress tests.

Certification

You can elevate your expertise with end-to-end testing using the Cypress automation framework and stay one step ahead in your career by earning a Cypress certification. Check out our Cypress 101 Certification.

YouTube

Watch this 3 hours of complete tutorial to learn the basics of Cypress and various Cypress commands with the Cypress testing at LambdaTest.

Run Cypress automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful