Best JavaScript code snippet using cypress
nginx.js
Source:nginx.js
...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 = {};...
jquery.signalR.core.js
Source:jquery.signalR.core.js
...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,...
WSURI.js
Source:WSURI.js
...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;...
cors.js
Source:cors.js
...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}...
uri.js
Source:uri.js
...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 }...
Using AI Code Generation
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)
Using AI Code Generation
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");
Using AI Code Generation
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()
Using AI Code Generation
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. |
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.
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.
Watch this 3 hours of complete tutorial to learn the basics of Cypress and various Cypress commands with the Cypress testing at LambdaTest.
Get 100 minutes of automation test minutes FREE!!