Subversion Repositories oidplus

Rev

Rev 695 | Rev 706 | Go to most recent revision | View as "text/javascript" | Blame | Compare with Previous | Last modification | View Log | RSS feed

  1. /*
  2.  * OIDplus 2.0
  3.  * Copyright 2019 - 2021 Daniel Marschall, ViaThinkSoft
  4.  *
  5.  * Licensed under the Apache License, Version 2.0 (the "License");
  6.  * you may not use this file except in compliance with the License.
  7.  * You may obtain a copy of the License at
  8.  *
  9.  *     http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17.  
  18. // DEFAULT_LANGUAGE will be set by setup.js.php
  19. // language_messages will be set by setup.js.php
  20. // language_tblprefix will be set by setup.js.php
  21.  
  22. // TODO: Put these settings in a "setup configuration file" (hardcoded)
  23. min_password_length = 10; // see also plugins/viathinksoft/publicPages/092_forgot_password_admin/script.js
  24. password_salt_length = 10;
  25. bcrypt_rounds = 10;
  26.  
  27. function btoa(bin) {
  28.         var tableStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  29.         var table = tableStr.split("");
  30.         for (var i = 0, j = 0, len = bin.length / 3, base64 = []; i < len; ++i) {
  31.                 var a = bin.charCodeAt(j++), b = bin.charCodeAt(j++), c = bin.charCodeAt(j++);
  32.                 if ((a | b | c) > 255) throw new Error(_L('String contains an invalid character'));
  33.                 base64[base64.length] = table[a >> 2] + table[((a << 4) & 63) | (b >> 4)] +
  34.                                        (isNaN(b) ? "=" : table[((b << 2) & 63) | (c >> 6)]) +
  35.                                        (isNaN(b + c) ? "=" : table[c & 63]);
  36.         }
  37.         return base64.join("");
  38. };
  39.  
  40. function hexToBase64(str) {
  41.         return btoa(String.fromCharCode.apply(null,
  42.                     str.replace(/\r|\n/g, "").replace(/([\da-fA-F]{2}) ?/g, "0x$1 ").replace(/ +$/, "").split(" ")));
  43. }
  44.  
  45. function b64EncodeUnicode(str) {
  46.         // first we use encodeURIComponent to get percent-encoded UTF-8,
  47.         // then we convert the percent encodings into raw bytes which
  48.         // can be fed into btoa.
  49.         return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,
  50.         function toSolidBytes(match, p1) {
  51.                 return String.fromCharCode('0x' + p1);
  52.         }));
  53. }
  54.  
  55. function generateRandomString(length) {
  56.         var charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
  57.         retVal = "";
  58.         for (var i = 0, n = charset.length; i < length; ++i) {
  59.                 retVal += charset.charAt(Math.floor(Math.random() * n));
  60.         }
  61.         return retVal;
  62. }
  63.  
  64. String.prototype.replaceAll = function(search, replacement) {
  65.         var target = this;
  66.         return target.replace(new RegExp(search, 'g'), replacement);
  67. };
  68.  
  69. function adminGeneratePassword(password) {
  70.         var salt = generateRandomString(password_salt_length);
  71.         return salt+'$'+hexToBase64(sha3_512(salt+password));
  72. }
  73.  
  74. var bCryptWorker = null;
  75. var g_prevBcryptPw = null;
  76. var g_last_admPwdHash = null;
  77. var g_last_pwComment = null;
  78.  
  79. function rebuild() {
  80.         var pw = $("#admin_password")[0].value;
  81.  
  82.         if (pw != g_prevBcryptPw) {
  83.                 // sync call to calculate SHA3
  84.                 var admPwdHash = adminGeneratePassword(pw);
  85.                 var pwComment = 'salted, base64 encoded SHA3-512 hash';
  86.                 doRebuild(admPwdHash, pwComment);
  87.  
  88.                 // "async" call to calculate bcrypt (via web-worker)
  89.                 if (bCryptWorker != null) {
  90.                         g_prevBcryptPw = null;
  91.                         bCryptWorker.terminate();
  92.                 }
  93.                 bCryptWorker = new Worker('../bcrypt_worker.js');
  94.                 bCryptWorker.postMessage([pw, bcrypt_rounds]);
  95.                 bCryptWorker.onmessage = function (event) {
  96.                         var admPwdHash = event.data;
  97.                         var pwComment = 'bcrypt encoded hash';
  98.                         doRebuild(admPwdHash, pwComment);
  99.                         g_prevBcryptPw = pw;
  100.                 };
  101.         } else {
  102.                 doRebuild(g_last_admPwdHash, g_last_pwComment);
  103.         }
  104. }
  105.  
  106. function doRebuild(admPwdHash, pwComment) {
  107.         g_last_admPwdHash = admPwdHash;
  108.         g_last_pwComment = pwComment;
  109.  
  110.         var error = false;
  111.  
  112.         if ($("#config")[0] == null) return;
  113.  
  114.         // Check 1: Has the password the correct length?
  115.         if ($("#admin_password")[0].value.length < min_password_length)
  116.         {
  117.                 $("#password_warn")[0].innerHTML = '<font color="red">'+_L('Password must be at least %1 characters long',min_password_length)+'</font>';
  118.                 $("#config")[0].innerHTML = '<b>&lt?php</b><br><br><i>// ERROR: Password must be at least '+min_password_length+' characters long</i>'; // do not translate
  119.                 error = true;
  120.         } else {
  121.                 $("#password_warn")[0].innerHTML = '';
  122.         }
  123.  
  124.         // Check 2: Do the passwords match?
  125.         if ($("#admin_password")[0].value != $("#admin_password2")[0].value) {
  126.                 $("#password_warn2")[0].innerHTML = '<font color="red">'+_L('The passwords do not match!')+'</font>';
  127.                 error = true;
  128.         } else {
  129.                 $("#password_warn2")[0].innerHTML = '';
  130.         }
  131.  
  132.         // Check 3: Ask the database or captcha plugins for verification of their data
  133.         for (var i = 0; i < rebuild_callbacks.length; i++) {
  134.                 var f = rebuild_callbacks[i];
  135.                 if (!f()) {
  136.                         error = true;
  137.                 }
  138.         }
  139.  
  140.         // Continue
  141.         if (!error)
  142.         {
  143.                 var e = $("#db_plugin")[0];
  144.                 var strDatabasePlugin = e.options[e.selectedIndex].value;
  145.                 var e = $("#captcha_plugin")[0];
  146.                 var strCaptchaPlugin = e.options[e.selectedIndex].value;
  147.  
  148.                 $("#config")[0].innerHTML = '<b>&lt?php</b><br><br>' +
  149.                         '<i>// To renew this file, please run setup/ in your browser.</i><br>' + // do not translate
  150.                         '<i>// If you don\'t want to run setup again, you can also change most of the settings directly in this file.</i><br>' + // do not translate
  151.                         '<br>' +
  152.                         'OIDplus::baseConfig()->setValue(\'CONFIG_VERSION\',    2.1);<br>' +
  153.                         '<br>' +
  154.                         // Passwords are Base64 encoded to avoid that passwords can be read upon first sight,
  155.                         // e.g. if collegues are looking over your shoulder while you accidently open (and quickly close) userdata/baseconfig/config.inc.php
  156.                         'OIDplus::baseConfig()->setValue(\'ADMIN_PASSWORD\',    \'' + admPwdHash + '\'); // '+pwComment+'<br>' +
  157.                         '<br>' +
  158.                         'OIDplus::baseConfig()->setValue(\'DATABASE_PLUGIN\',   \''+strDatabasePlugin+'\');<br>';
  159.                 for (var i = 0; i < rebuild_config_callbacks.length; i++) {
  160.                         var f = rebuild_config_callbacks[i];
  161.                         var cont = f();
  162.                         if (cont) {
  163.                                 $("#config")[0].innerHTML = $("#config")[0].innerHTML + cont;
  164.                         }
  165.                 }
  166.                 $("#config")[0].innerHTML = $("#config")[0].innerHTML +
  167.                         '<br>' +
  168.                         'OIDplus::baseConfig()->setValue(\'TABLENAME_PREFIX\',  \''+$("#tablename_prefix")[0].value+'\');<br>' +
  169.                         '<br>' +
  170.                         'OIDplus::baseConfig()->setValue(\'SERVER_SECRET\',     \''+generateRandomString(32)+'\');<br>' +
  171.                         '<br>' +
  172.                         'OIDplus::baseConfig()->setValue(\'CAPTCHA_PLUGIN\',    \''+strCaptchaPlugin+'\');<br>';
  173.                 for (var i = 0; i < captcha_rebuild_config_callbacks.length; i++) {
  174.                         var f = captcha_rebuild_config_callbacks[i];
  175.                         var cont = f();
  176.                         if (cont) {
  177.                                 $("#config")[0].innerHTML = $("#config")[0].innerHTML + cont;
  178.                         }
  179.                 }
  180.  
  181.                 $("#config")[0].innerHTML = $("#config")[0].innerHTML +
  182.                         '<br>' +
  183.                         'OIDplus::baseConfig()->setValue(\'ENFORCE_SSL\',       '+$("#enforce_ssl")[0].value+');<br>';
  184.  
  185.                 $("#config")[0].innerHTML = $("#config")[0].innerHTML.replaceAll(' ', '&nbsp;');
  186.         }
  187.  
  188.         // In case something is not good, do not allow the user to continue with the other configuration steps:
  189.         if (error) {
  190.                 $("#step2")[0].style.display = "None";
  191.                 $("#step3")[0].style.display = "None";
  192.                 $("#step4")[0].style.display = "None";
  193.         } else {
  194.                 $("#step2")[0].style.display = "Block";
  195.                 $("#step3")[0].style.display = "Block";
  196.                 $("#step4")[0].style.display = "Block";
  197.         }
  198. }
  199.  
  200. function RemoveLastDirectoryPartOf(the_url) {
  201.         var the_arr = the_url.split('/');
  202.         if (the_arr.pop() == '') the_arr.pop();
  203.         return( the_arr.join('/') );
  204. }
  205.  
  206. function checkAccess(dir) {
  207.         var url = '../' + dir;
  208.         var visibleUrl = RemoveLastDirectoryPartOf(window.location.href) + '/' + dir; // xhr.responseURL not available in IE
  209.  
  210.         var xhr = new XMLHttpRequest();
  211.         xhr.onreadystatechange = function() {
  212.                 if (xhr.readyState === 4) {
  213.                         if (xhr.status === 200) {
  214.                                 $("#systemCheckCaption")[0].style.display = 'block';
  215.                                 $("#dirAccessWarning")[0].innerHTML = $("#dirAccessWarning")[0].innerHTML + _L('Attention: The following directory is world-readable: %1 ! You need to configure your web server to restrict access to this directory! (For Apache see <i>.htaccess</i>, for Microsoft IIS see <i>web.config</i>, for Nginx see <i>nginx.conf</i>).','<a target="_blank" href="'+url+'">'+visibleUrl+'</a>') + '<br>';
  216.                         }
  217.                 }
  218.         };
  219.  
  220.         xhr.open('GET', url);
  221.         xhr.send();
  222. }
  223.  
  224. function dbplugin_changed() {
  225.         var e = $("#db_plugin")[0];
  226.         var strDatabasePlugin = e.options[e.selectedIndex].value;
  227.  
  228.         for (var i = 0; i < plugin_combobox_change_callbacks.length; i++) {
  229.                 var f = plugin_combobox_change_callbacks[i];
  230.                 f(strDatabasePlugin);
  231.         }
  232.  
  233.         rebuild();
  234. }
  235.  
  236. function captchaplugin_changed() {
  237.         var e = $("#captcha_plugin")[0];
  238.         var strCaptchaPlugin = e.options[e.selectedIndex].value;
  239.  
  240.         for (var i = 0; i < captcha_plugin_combobox_change_callbacks.length; i++) {
  241.                 var f = captcha_plugin_combobox_change_callbacks[i];
  242.                 f(strCaptchaPlugin);
  243.         }
  244.  
  245.         rebuild();
  246. }
  247.  
  248. function performAccessCheck() {
  249.         $("#dirAccessWarning")[0].innerHTML = "";
  250.         checkAccess("userdata/index.html");
  251.         checkAccess("res/ATTENTION.TXT");
  252.         checkAccess("dev/index.html");
  253.         checkAccess("includes/index.html");
  254.         checkAccess("setup/includes/index.html");
  255.         //checkAccess("plugins/viathinksoft/publicPages/100_whois/whois/cli/index.html");
  256. }
  257.  
  258. function setupOnLoad() {
  259.         rebuild();
  260.         dbplugin_changed();
  261.         captchaplugin_changed();
  262.         performAccessCheck();
  263. }
  264.  
  265. function getCookie(cname) {
  266.         // Source: https://www.w3schools.com/js/js_cookies.asp
  267.         var name = cname + "=";
  268.         var decodedCookie = decodeURIComponent(document.cookie);
  269.         var ca = decodedCookie.split(';');
  270.         for(var i = 0; i <ca.length; i++) {
  271.                 var c = ca[i];
  272.                 while (c.charAt(0) == ' ') {
  273.                         c = c.substring(1);
  274.                 }
  275.                 if (c.indexOf(name) == 0) {
  276.                         return c.substring(name.length, c.length);
  277.                 }
  278.         }
  279.         return undefined;
  280. }
  281.  
  282. function getCurrentLang() {
  283.         // Note: If the argument "?lang=" is used, PHP will automatically set a Cookie, so it is OK when we only check for the cookie
  284.         var lang = getCookie('LANGUAGE');
  285.         return (typeof lang != "undefined") ? lang : DEFAULT_LANGUAGE;
  286. }
  287.  
  288. function _L() {
  289.         var args = Array.prototype.slice.call(arguments);
  290.         var str = args.shift().trim();
  291.  
  292.         var tmp = "";
  293.         if (typeof language_messages[getCurrentLang()] == "undefined") {
  294.                 tmp = str;
  295.         } else {
  296.                 var msg = language_messages[getCurrentLang()][str];
  297.                 if (typeof msg != "undefined") {
  298.                         tmp = msg;
  299.                 } else {
  300.                         tmp = str;
  301.                 }
  302.         }
  303.  
  304.         tmp = tmp.replace('###', language_tblprefix);
  305.  
  306.         var n = 1;
  307.         while (args.length > 0) {
  308.                 var val = args.shift();
  309.                 tmp = tmp.replace("%"+n, val);
  310.                 n++;
  311.         }
  312.  
  313.         tmp = tmp.replace("%%", "%");
  314.  
  315.         return tmp;
  316. }
  317.  
  318. window.onload = setupOnLoad;
  319.