Subversion Repositories oidplus

Rev

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