Subversion Repositories oidplus

Rev

Rev 635 | Rev 702 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
5 daniel-mar 1
/*
2
 * OIDplus 2.0
511 daniel-mar 3
 * Copyright 2019 - 2021 Daniel Marschall, ViaThinkSoft
5 daniel-mar 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
 
362 daniel-mar 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
 
695 daniel-mar 22
// TODO: Put these settings in a "setup configuration file" (hardcoded)
635 daniel-mar 23
min_password_length = 10; // see also plugins/viathinksoft/publicPages/092_forgot_password_admin/script.js
421 daniel-mar 24
password_salt_length = 10;
695 daniel-mar 25
bcrypt_rounds = 10;
80 daniel-mar 26
 
2 daniel-mar 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++);
362 daniel-mar 32
                if ((a | b | c) > 255) throw new Error(_L('String contains an invalid character'));
2 daniel-mar 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
 
421 daniel-mar 69
function adminGeneratePassword(password) {
70
        var salt = generateRandomString(password_salt_length);
71
        return salt+'$'+hexToBase64(sha3_512(salt+password));
72
}
73
 
456 daniel-mar 74
var bCryptWorker = null;
75
var g_prevBcryptPw = null;
76
var g_last_admPwdHash = null;
77
var g_last_pwComment = null;
78
 
2 daniel-mar 79
function rebuild() {
561 daniel-mar 80
        var pw = $("#admin_password")[0].value;
456 daniel-mar 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
                }
599 daniel-mar 93
                bCryptWorker = new Worker('../bcrypt_worker.js');
695 daniel-mar 94
                bCryptWorker.postMessage([pw, bcrypt_rounds]);
456 daniel-mar 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
 
2 daniel-mar 110
        var error = false;
111
 
561 daniel-mar 112
        if ($("#config")[0] == null) return;
150 daniel-mar 113
 
81 daniel-mar 114
        // Check 1: Has the password the correct length?
561 daniel-mar 115
        if ($("#admin_password")[0].value.length < min_password_length)
81 daniel-mar 116
        {
561 daniel-mar 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
81 daniel-mar 119
                error = true;
120
        } else {
561 daniel-mar 121
                $("#password_warn")[0].innerHTML = '';
81 daniel-mar 122
        }
123
 
124
        // Check 2: Do the passwords match?
561 daniel-mar 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>';
2 daniel-mar 127
                error = true;
128
        } else {
561 daniel-mar 129
                $("#password_warn2")[0].innerHTML = '';
2 daniel-mar 130
        }
131
 
150 daniel-mar 132
        // Check 3: Ask the database 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
                }
2 daniel-mar 138
        }
81 daniel-mar 139
 
149 daniel-mar 140
        // Continue
81 daniel-mar 141
        if (!error)
142
        {
561 daniel-mar 143
                var e = $("#db_plugin")[0];
150 daniel-mar 144
                var strPlugin = e.options[e.selectedIndex].value;
145
 
561 daniel-mar 146
                $("#config")[0].innerHTML = '<b>&lt?php</b><br><br>' +
362 daniel-mar 147
                        '<i>// To renew this file, please run setup/ in your browser.</i><br>' + // do not translate
148
                        '<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
2 daniel-mar 149
                        '<br>' +
261 daniel-mar 150
                        'OIDplus::baseConfig()->setValue(\'CONFIG_VERSION\',    2.1);<br>' +
2 daniel-mar 151
                        '<br>' +
150 daniel-mar 152
                        // Passwords are Base64 encoded to avoid that passwords can be read upon first sight,
294 daniel-mar 153
                        // e.g. if collegues are looking over your shoulder while you accidently open (and quickly close) userdata/baseconfig/config.inc.php
456 daniel-mar 154
                        'OIDplus::baseConfig()->setValue(\'ADMIN_PASSWORD\',    \'' + admPwdHash + '\'); // '+pwComment+'<br>' +
2 daniel-mar 155
                        '<br>' +
261 daniel-mar 156
                        'OIDplus::baseConfig()->setValue(\'DATABASE_PLUGIN\',   \''+strPlugin+'\');<br>';
150 daniel-mar 157
                for (var i = 0; i < rebuild_config_callbacks.length; i++) {
158
                        var f = rebuild_config_callbacks[i];
159
                        var cont = f();
160
                        if (cont) {
561 daniel-mar 161
                                $("#config")[0].innerHTML = $("#config")[0].innerHTML + cont;
150 daniel-mar 162
                        }
163
                }
561 daniel-mar 164
                $("#config")[0].innerHTML = $("#config")[0].innerHTML +
2 daniel-mar 165
                        '<br>' +
561 daniel-mar 166
                        'OIDplus::baseConfig()->setValue(\'TABLENAME_PREFIX\',  \''+$("#tablename_prefix")[0].value+'\');<br>' +
2 daniel-mar 167
                        '<br>' +
261 daniel-mar 168
                        'OIDplus::baseConfig()->setValue(\'SERVER_SECRET\',     \''+generateRandomString(32)+'\');<br>' +
2 daniel-mar 169
                        '<br>' +
561 daniel-mar 170
                        'OIDplus::baseConfig()->setValue(\'RECAPTCHA_ENABLED\', '+($("#recaptcha_enabled")[0].checked ? 'true' : 'false')+');<br>' +
171
                        'OIDplus::baseConfig()->setValue(\'RECAPTCHA_PUBLIC\',  \''+$("#recaptcha_public")[0].value+'\');<br>' +
172
                        'OIDplus::baseConfig()->setValue(\'RECAPTCHA_PRIVATE\', \''+$("#recaptcha_private")[0].value+'\');<br>' +
80 daniel-mar 173
                        '<br>' +
561 daniel-mar 174
                        'OIDplus::baseConfig()->setValue(\'ENFORCE_SSL\',       '+$("#enforce_ssl")[0].value+');<br>';
2 daniel-mar 175
 
561 daniel-mar 176
                $("#config")[0].innerHTML = $("#config")[0].innerHTML.replaceAll(' ', '&nbsp;');
2 daniel-mar 177
        }
178
 
179
        // In case something is not good, do not allow the user to continue with the other configuration steps:
180
        if (error) {
561 daniel-mar 181
                $("#step2")[0].style.display = "None";
182
                $("#step3")[0].style.display = "None";
183
                $("#step4")[0].style.display = "None";
2 daniel-mar 184
        } else {
561 daniel-mar 185
                $("#step2")[0].style.display = "Block";
186
                $("#step3")[0].style.display = "Block";
187
                $("#step4")[0].style.display = "Block";
2 daniel-mar 188
        }
189
}
362 daniel-mar 190
 
191
function RemoveLastDirectoryPartOf(the_url) {
192
        var the_arr = the_url.split('/');
193
        if (the_arr.pop() == '') the_arr.pop();
194
        return( the_arr.join('/') );
195
}
196
 
197
function checkAccess(dir) {
198
        var url = '../' + dir;
199
        var visibleUrl = RemoveLastDirectoryPartOf(window.location.href) + '/' + dir; // xhr.responseURL not available in IE
200
 
201
        var xhr = new XMLHttpRequest();
202
        xhr.onreadystatechange = function() {
203
                if (xhr.readyState === 4) {
204
                        if (xhr.status === 200) {
561 daniel-mar 205
                                $("#systemCheckCaption")[0].style.display = 'block';
206
                                $("#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>';
362 daniel-mar 207
                        }
208
                }
209
        };
210
 
211
        xhr.open('GET', url);
212
        xhr.send();
213
}
214
 
215
function dbplugin_changed() {
561 daniel-mar 216
        var e = $("#db_plugin")[0];
362 daniel-mar 217
        var strPlugin = e.options[e.selectedIndex].value;
218
 
219
        for (var i = 0; i < plugin_combobox_change_callbacks.length; i++) {
220
                var f = plugin_combobox_change_callbacks[i];
221
                f(strPlugin);
222
        }
223
 
224
        rebuild();
225
}
226
 
227
function performAccessCheck() {
561 daniel-mar 228
        $("#dirAccessWarning")[0].innerHTML = "";
362 daniel-mar 229
        checkAccess("userdata/index.html");
476 daniel-mar 230
        checkAccess("res/ATTENTION.TXT");
362 daniel-mar 231
        checkAccess("dev/index.html");
232
        checkAccess("includes/index.html");
448 daniel-mar 233
        checkAccess("setup/includes/index.html");
635 daniel-mar 234
        //checkAccess("plugins/viathinksoft/publicPages/100_whois/whois/cli/index.html");
362 daniel-mar 235
}
236
 
237
function setupOnLoad() {
238
        rebuild();
239
        dbplugin_changed();
240
        performAccessCheck();
241
}
242
 
243
function getCookie(cname) {
244
        // Source: https://www.w3schools.com/js/js_cookies.asp
245
        var name = cname + "=";
246
        var decodedCookie = decodeURIComponent(document.cookie);
247
        var ca = decodedCookie.split(';');
248
        for(var i = 0; i <ca.length; i++) {
249
                var c = ca[i];
250
                while (c.charAt(0) == ' ') {
251
                        c = c.substring(1);
252
                }
253
                if (c.indexOf(name) == 0) {
254
                        return c.substring(name.length, c.length);
255
                }
256
        }
257
        return undefined;
258
}
259
 
260
function getCurrentLang() {
261
        // Note: If the argument "?lang=" is used, PHP will automatically set a Cookie, so it is OK when we only check for the cookie
262
        var lang = getCookie('LANGUAGE');
263
        return (typeof lang != "undefined") ? lang : DEFAULT_LANGUAGE;
264
}
265
 
266
function _L() {
267
        var args = Array.prototype.slice.call(arguments);
506 daniel-mar 268
        var str = args.shift().trim();
362 daniel-mar 269
 
270
        var tmp = "";
271
        if (typeof language_messages[getCurrentLang()] == "undefined") {
272
                tmp = str;
273
        } else {
274
                var msg = language_messages[getCurrentLang()][str];
275
                if (typeof msg != "undefined") {
276
                        tmp = msg;
277
                } else {
278
                        tmp = str;
279
                }
280
        }
281
 
282
        tmp = tmp.replace('###', language_tblprefix);
283
 
284
        var n = 1;
285
        while (args.length > 0) {
286
                var val = args.shift();
287
                tmp = tmp.replace("%"+n, val);
288
                n++;
289
        }
290
 
370 daniel-mar 291
        tmp = tmp.replace("%%", "%");
292
 
362 daniel-mar 293
        return tmp;
294
}
295
 
296
window.onload = setupOnLoad;