Subversion Repositories oidplus

Rev

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