class TUser //Current user with role name and access
{
constructor() {
//this.name="TUser"; //User name
this.company_id = null;
this.win = null;
this.access = {}; //Associative array
this.isLoadedAccess=false; //Подгрузились ли уровни доступа
this.onUpdate = null; //Listener update access array
this.onLoadSettings = null;
this.timezone = ""; // +06:00:00 временая зона текущего пользователя
this.settings = {'':''}; //ассоциативный массив настроек для текущего пользователя
this.checkSession();
//Так как страница перезагружается после авторизации то пользователь уже должен быть зарегестрирован
this.loadSettings();
}
loadAccess() {
let xs = '\n\
\n\
\n\
\n\
\n\
';
let request = new TRequest(this);
if (request.callServer(ScriptName, xs)) {
//m_winPP.showProgressBar();
}
}
//Сохранить параметр настройки для текущего пользователя в базе данных.
sendSettings(name, value)
{
showProgressBarIco();
this.settings[name]=''+value;
let xs='\n\
\n\
\n\
\n\
\n\
';
$.ajax({
url: ScriptName,
type: "POST",
contentType: 'text/xml; charset=utf-8',
dataType: "text",
data: xs,
success: function(response) {
hideProgressBarIco();
},
error: function(xhr) {
hideProgressBarIco();
}
});
}
//Запросить загрузку параметров настроек
loadSettings()
{
//alert('call loadSettings');
let xs='\n\
\n\
\n\
\n\
\n\
';
let request=new TRequest(this);
if(request.callServer(ScriptName,xs))
{
//m_winPP.showProgressBar();
}
}
//Получить настройку
getSettings(name,def)
{
let rez=this.settings[name];
if(rez === undefined) {
rez=false;
if(def!==undefined) rez=def;
}
return ''+rez;
};
//Записать присланные данные в асоциативный массив
updateSettings(node)
{
this.settings={};
let nodeType=findFirstNode(node, "type");
let nodeRecord = nodeType.firstChild;
while(nodeRecord != null)
{
if(nodeRecord.nodeName=="record")
{
let key='';
let val='';
let i=0; //column number
let cdataNode = nodeRecord.firstChild;
while (cdataNode!=null)
{
if(cdataNode.nodeName=="#cdata-section")
{
if(i==0) key=cdataNode.nodeValue;
if(i==1) val=cdataNode.nodeValue;
i++;
}
cdataNode = cdataNode.nextSibling;
}
/*if(val=='f' || val==0 || val=='false') val=false;
else if(val='t' || val==1 || val=='true') val=true;
else val=null;*/
this.settings[key]=val;
}
nodeRecord = nodeRecord.nextSibling;
}
if(this.onLoadSettings!=null) this.onLoadSettings(this);
return true;
}
applyReq(req, fn, node) {
if (fn == -1) {
alert2(trt("Alert"),findFirstNode(node, '#cdata-section').nodeValue);
} else if (fn == 4) {
var nodeType = findFirstNode(node, "type");
if (nodeType != null) {
if (nodeType.getAttribute("n") == "_ChangePassword") {
if (findFirstNode(node, '#cdata-section').nodeValue == 't') {
alert2(trt("Alert"),trt('Password_changed_successfully'));
//this.win.hideProgressBar();
this.win.Close();
this.win = null;
} else {
alert2(trt("Alert"),trt('Failed_to_change_password') + '\n' + trt('Check_the_entered_data'));
this.win.hideProgressBar();
}
} else {
this.updateAccess(node);
}
}
} else if (fn == 7) {
var nCmd = findFirstNode(node, "cmd");
if (nCmd != null) {
if (findFirstNode(nCmd, '#cdata-section').nodeValue == "1") //Logout
{
location.reload();
} else if (findFirstNode(nCmd, '#cdata-section').nodeValue == "2") //Check if user not logged
{
if (findNode(node, '#cdata-section').nodeValue == "0") //if not logged
{
this.showLoginForm();
} else {
this.name = getCdataValue(findNode(node, 'name'));
this.company_id = getCdataValue(findNode(node, 'company_id'));
//alert2(trt("Alert"),'this.company_id = '+this.company_id);
configGUIbyAccessLevel();
//var shadow=document.getElementById("shadow");
//if(shadow.parentNode!=null) shadow.parentNode.removeChild(shadow);
g_trips.filtering();
g_geofences.filtering();
g_objects.filtering();
g_routes.filtering();
g_detours.filtering();
}
} else if (findFirstNode(nCmd, '#cdata-section').nodeValue == "3") //Login
{
if (findNode(node, '#cdata-section').nodeValue == "0") //if not logged
{
alert2(trt("Alert"),trt('Invalid_username_and_or_password'));
} else {
location.reload();
}
} else if (findFirstNode(nCmd, '#cdata-section').nodeValue == "4") //Register
{
if (findNode(node, '#cdata-section').nodeValue == "1") //if register
{
alert2(trt("Alert"),trt('New_user_is_registered') + '\n' + trt('The_password_has_been_sent_to_you_by_Email'));
location.reload();
}
}
}
} else {
alert2(trt("Alert"),"Unknown function! fn=\"" + fn + "\"");
}
if (this.win != null) this.win.hideProgressBar();
}
updateAccess(node) {
this.access = {};
var nodeType = findFirstNode(node, "type");
var nodeRecord = nodeType.firstChild;
while (nodeRecord != null) {
if (nodeRecord.nodeName == "record") {
var key = '';
var val = '';
i = 0; //column number
var cdataNode = nodeRecord.firstChild;
while (cdataNode != null) {
if (cdataNode.nodeName == "#cdata-section") {
if (i == 0) key = cdataNode.nodeValue;
if (i == 1) val = cdataNode.nodeValue;
i++;
}
cdataNode = cdataNode.nextSibling;
}
if (val == 'f' || val == 0 || val == 'false') val = false;
else if (val = 't' || val == 1 || val == 'true') val = true;
else val = null;
this.access[key] = val;
}
nodeRecord = nodeRecord.nextSibling;
}
if (this.onUpdate != null) this.onUpdate(this);
this.isLoadedAccess=true;
return true;
}
getAccess(name) {
let rez = this.access[name];
if (rez === undefined) {
console.error('Access key "' + name + '" not found!');
return false;
}
if (rez != true) return false;
return rez;
};
changePassword() {
this.win = new TWin();
this.win.BuildGUI(10, 10);
this.win.setCaption(trt('Change_password'));
let str = '
';
this.win.setContent(str);
this.win.setSize("500px", "180px");
this.win.setCenter();
this.win.shadow = true;
this.win.hide(false);
document.getElementById('id_change_pass').onclick = function (thiz) {
return function () {
let data = {
email: document.getElementById('id_ch_login').value,
password: document.getElementById('id_ch_oldpassword').value,
new_password: document.getElementById('id_ch_newpassword').value,
repeat_new_password: document.getElementById('id_ch_newrpassword').value
};
if (data.email == '') {
document.getElementById('id_ch_login').select();
alert2(trt("Alert"),trt('Not_filled_Email_address'));
return;
}
if (!isEmail(data.email)) {
alert2(trt("Alert"),sprintf(trt('The_s_is_not_Email'), data.email));
return;
}
if (data.new_password != data.repeat_new_password) {
alert2(trt("Alert"),trt('Passwords_did_not_match'));
return;
}
thiz.win.showProgressBar();
$.ajax({
url: "/monitoring/pscripts/user.php?fn=3",
type: "POST",
contentType: 'application/json; charset=utf-8',
dataType: "json",
data: JSON.stringify(data),
success: function (win) {
return function (response, status) {
if (status == 'success') {
if (response.errorCode == '0') {
alert2(trt("Alert"),trt('Password_changed_successfully'));
} else {
alert2(trt("Alert"),response.errorMessage);
}
} else {
alert2(trt("Alert"),status);
}
win.hideProgressBar();
}
}(thiz.win)
});
};
}(this);
document.getElementById('exit_pass_' + this.win.uid).onclick = function (win) {
return function () {
win.Close();
};
}(this.win);
}
//logout current user
Logout() {
let xs = '';
let request = new TRequest(this);
if (request.callServer(ScriptName, xs)) {
//m_winPP.showProgressBar();
}
}
//Display login and registration form
showLoginForm() {
if (this.win == null || this.win.closed) {
this.win = new TWin(true);
this.win.disableClosing = true;
this.win.BuildGUI(10, 10);
this.win.setCaption(trt('Authorization') + ' / ' + trt('Registration'));
this.win.setSize("350px", "150px");
/*let str='';
this.win.setContent(str);*/
let str;
var tab = new tcTabs(document.getElementById('TWin_Co_' + this.win.tWinId));
tb = tab.addTab({caption: trt('Authorization')});
str = '';
tb.setConText(str);
tb.setSel();
tb = tab.addTab({caption: trt('Registration')});
str = '';
tb.setConText(str);
//tb.setSel()
//Center the window and display the shadow
this.win.setCenter();
this.win.shadow = true;
this.win.hide(false);
//Clicking on the button login
let obj = null;
obj = document.getElementById(this.win.uid + '_login');
if (obj !== null) {
obj.onclick=()=>
{
let login=document.getElementById('login0').value;
let password=document.getElementById('password0').value;
if(login==''){ alert2(trt("Alert"),trt('Please_fill_in_the_login_field')); return; }
if(password==''){ alert2(trt("Alert"),trt('Please_fill_in_the_password_field')); return; }
let xs = '\
\
\n\
\
\
';
let request = new TRequest(this);
if (request.callServer(ScriptName, xs)) {
this.win.showProgressBar();
}
};
}
//Щелчёк по нажатию Enter
obj = document.getElementById('password0');
if (obj != null) {
obj.onkeypress = function (thiz) {
return function (e) {
if (e.keyCode == 13) {
let xs = '\
\
\n\
\
\
';
let request = new TRequest(thiz);
if (request.callServer(ScriptName, xs)) {
thiz.win.showProgressBar();
}
}
};
}(this);
}
//Регистрация нового пользователя и компании
obj = document.getElementById(this.win.uid + '_registration');
if (obj !== null) {
obj.onclick = function (thiz) {
return function () {
//showProgressBar(document.getElementById('TWin_Co_'+thiz.win.tWinId),thiz.win.uid);
let data = {
lastname: document.getElementById(thiz.win.uid + '_lastname').value,
firstname: document.getElementById(thiz.win.uid + '_firstname').value,
company: document.getElementById(thiz.win.uid + '_company').value,
position: document.getElementById(thiz.win.uid + '_position').value,
phone: document.getElementById(thiz.win.uid + '_phone').value,
email: document.getElementById(thiz.win.uid + '_email').value,
captcha: document.getElementById(thiz.win.uid + '_captcha').value
};
//Check for completeness of the fields
if (data.firstname == '') {
document.getElementById(thiz.win.uid + '_firstname').select();
alert2(trt("Alert"),sprintf(trt('The_s_field_is_empty'), trt('Name')));
return;
}
if (data.email == '') {
document.getElementById(thiz.win.uid + '_email').select();
alert2(trt("Alert"),sprintf(trt('The_s_field_is_empty'), trt('Email')));
return;
}
if (!isEmail(data.email)) {
document.getElementById(thiz.win.uid + '_email').select();
alert2(trt("Alert"),trt('Please_enter_a_valid_email_address'));
return;
}
thiz.win.showProgressBar();
$.ajax({
url: "/monitoring/pscripts/user.php?fn=1",
type: "POST",
contentType: 'application/json; charset=utf-8',
dataType: "json",
data: JSON.stringify(data),
success: function (win) {
return function (response, status) {
if (status == 'success') {
if (response.errorCode == '0') {
alert2(trt("Alert"),trt('New_user_is_registered') + '\n' + trt('The_password_has_been_sent_to_you_by_Email'));
} else {
alert2(trt("Alert"),response.errorMessage);
}
} else {
alert2(trt("Alert"),status);
}
win.hideProgressBar();
}
}(thiz.win)
});
};
}(this);
}
obj = document.getElementById(this.win.uid + '_restore');
if (obj !== null) {
obj.onclick = function (thiz) {
return function () {
thiz.showRestoreForm();
};
}(this);
}
}
/*
log.bind(this, 'Hello world')
let user = {
firstName: "Вася"
};
function func() {
alert2(trt("Alert"),this.firstName);
}
let funcUser = func.bind(user);
funcUser(); // Вася
*/
/*var field1=document.getElementById("lang_1");
if(field1!=null)
{
field1.value=getURLParam("lng");
}
var field2=document.getElementById("lang_2");
if(field2!=null)
{
field2.value=getURLParam("lng");
}*/
}
//Display password recovery form
showRestoreForm() {
let win = new TWin(true);
win.BuildGUI(10, 10);
win.setCaption(trt("Password_recovery"));
let str = '';
document.getElementById('TWin_Co_' + win.tWinId).innerHTML = str;
win.setSize("300px", "170px");
//Центрируем окно и отображаем тень
if (win.tbl.offsetHeight > win.div.offsetHeight) win.div.style.height = win.tbl.offsetHeight + "px";
if (win.tbl.offsetWidth > win.div.offsetWidth) win.div.style.width = win.tbl.offsetWidth + "px";
win.setCenter();
win.shadow = true;
win.hide(false);
//Click on restore button
var obj = null;
obj = document.getElementById(win.uid + '_restore');
if (obj != null) {
obj.onclick = function (win) {
return function () {
let data = {
email: document.getElementById(win.uid + '_email').value,
captcha: document.getElementById(win.uid + '_captcha').value
};
if (data.email == '') {
document.getElementById(win.uid + '_email').select();
alert2(trt("Alert"),trt('Not_filled_Email_address'));
return;
}
if (!isEmail(data.email)) {
document.getElementById(win.uid + '_email').select();
alert2(trt("Alert"),trt('Please_enter_a_valid_email_address'));
return;
}
win.showProgressBar();
$.ajax({
url: "/monitoring/pscripts/user.php?fn=2",
type: "POST",
contentType: 'application/json; charset=utf-8',
dataType: "json",
data: JSON.stringify(data),
success: function (win) {
return function (response, status) {
if (status == 'success') {
if (response.errorCode == '0') {
alert2(trt("Alert"),trt('A_new_password_has_been_sent_to_your_email') + '.');
} else {
alert2(trt("Alert"),response.errorMessage);
}
} else {
alert2(trt("Alert"),status);
}
win.hideProgressBar();
}
}(win)
});
};
}(win);
}
}
//Check whether the already authorized (+ attempt to log in through "hash").
isLogined() {
let xs = '';
//var xs='{"fn":7,"cmd":2}';
let request = new TRequest(this);
if (request.callServer(ScriptName, xs)) {
//m_winPP.showProgressBar();
}
};
//Если список доступов подгрузился то считается что пользователь авторизовался
isLoggedIn(){
if(this.access.length>0)
return true;
else
return false;
}
//Checking the session without its extension, if it is completed, we display the authorization window.
checkSession()
{
let jqxhr = $.getJSON('./session.php',{},(data)=>{
if(data.result=='ERROR'){
this.showLoginForm();
}else
if(data.result=='OK'){
this.id=data.user_id;
}
divsh.style.display='none';
});
jqxhr.fail(function(){divsh.style.display='block';}); //If the server is not available.
setTimeout(()=>this.checkSession(), 10000);
}
}