1 #include "otsdaq/WebUsersUtilities/WebUsers.h"
2 #include "otsdaq/XmlUtilities/HttpXmlDocument.h"
4 #include <openssl/sha.h>
18 #define WEB_LOGIN_BKUP_DB_PATH "bkup/"
20 #define SECURITY_FILE_NAME std::string(__ENV__("SERVICE_DATA_PATH")) + "/OtsWizardData/security.dat"
22 #define USERS_ACTIVE_SESSIONS_FILE USERS_DB_PATH + "/activeSessions.sv"
24 #define HASHES_DB_FILE HASHES_DB_PATH + "/hashes.xml"
25 #define USERS_DB_FILE USERS_DB_PATH + "/users.xml"
26 #define USERS_GLOBAL_HISTORY_FILE "__global"
27 #define USERS_LOGIN_HISTORY_FILETYPE "hist"
28 #define USERS_PREFERENCES_FILETYPE "pref"
29 #define SYSTEM_PREFERENCES_PREFIX "system.preset"
30 #define USER_WITH_LOCK_FILE WEB_LOGIN_DB_PATH + "/user_with_lock.dat"
31 #define IP_BLACKLIST_FILE WEB_LOGIN_DB_PATH + "/ip_generated_blacklist.dat"
32 #define IP_REJECT_FILE WEB_LOGIN_DB_PATH + "/ip_reject.dat"
33 #define IP_ACCEPT_FILE WEB_LOGIN_DB_PATH + "/ip_accept.dat"
35 #define SILENCE_ALL_TOOLTIPS_FILENAME "silenceTooltips"
37 #define HASHES_DB_GLOBAL_STRING "hashData"
38 #define HASHES_DB_ENTRY_STRING "hashEntry"
39 #define USERS_DB_GLOBAL_STRING "userData"
40 #define USERS_DB_ENTRY_STRING "userEntry"
41 #define USERS_DB_NEXT_UID_STRING "nextUserId"
44 #define PREF_XML_BGCOLOR_FIELD "pref_bgcolor"
45 #define PREF_XML_DBCOLOR_FIELD "pref_dbcolor"
46 #define PREF_XML_WINCOLOR_FIELD "pref_wincolor"
47 #define PREF_XML_LAYOUT_FIELD "pref_layout"
48 #define PREF_XML_SYSLAYOUT_FIELD "pref_syslayout"
49 #define PREF_XML_ALIAS_LAYOUT_FIELD "pref_aliaslayout"
50 #define PREF_XML_SYSALIAS_LAYOUT_FIELD "pref_sysalias_layout"
51 #define PREF_XML_PERMISSIONS_FIELD "desktop_user_permissions"
52 #define PREF_XML_USERLOCK_FIELD "username_with_lock"
53 #define PREF_XML_USERNAME_FIELD "pref_username"
54 #define PREF_XML_OTS_OWNER_FIELD "ots_owner"
56 #define PREF_XML_BGCOLOR_DEFAULT "rgb(0,76,151)"
57 #define PREF_XML_DBCOLOR_DEFAULT "rgb(0,40,85)"
58 #define PREF_XML_WINCOLOR_DEFAULT "rgba(196,229,255,0.9)"
59 #define PREF_XML_LAYOUT_DEFAULT "0;0;0;0"
60 #define PREF_XML_SYSLAYOUT_DEFAULT "0;0"
62 #define PREF_XML_ACCOUNTS_FIELD "users_accounts"
63 #define PREF_XML_LOGIN_HISTORY_FIELD "login_entry"
66 const std::string WebUsers::DEFAULT_ADMIN_USERNAME =
"admin";
67 const std::string WebUsers::DEFAULT_ADMIN_DISPLAY_NAME =
"Administrator";
68 const std::string WebUsers::DEFAULT_ADMIN_EMAIL =
"root@otsdaq.fnal.gov";
69 const std::string WebUsers::DEFAULT_ITERATOR_USERNAME =
"iterator";
70 const std::string WebUsers::DEFAULT_STATECHANGER_USERNAME =
"statechanger";
71 const std::string WebUsers::DEFAULT_USER_GROUP =
"allUsers";
73 const std::string WebUsers::REQ_NO_LOGIN_RESPONSE =
"NoLogin";
74 const std::string WebUsers::REQ_NO_PERMISSION_RESPONSE =
"NoPermission";
75 const std::string WebUsers::REQ_USER_LOCKOUT_RESPONSE =
"UserLockout";
76 const std::string WebUsers::REQ_LOCK_REQUIRED_RESPONSE =
"LockRequired";
77 const std::string WebUsers::REQ_ALLOW_NO_USER =
"AllowNoUser";
79 const std::string WebUsers::SECURITY_TYPE_NONE =
"NoSecurity";
80 const std::string WebUsers::SECURITY_TYPE_DIGEST_ACCESS =
"DigestAccessAuthentication";
81 const std::string WebUsers::SECURITY_TYPE_DEFAULT = WebUsers::SECURITY_TYPE_NONE;
83 const std::vector<std::string> WebUsers::HashesDatabaseEntryFields_ = {
"hash",
"lastAccessTime"};
84 const std::vector<std::string> WebUsers::UsersDatabaseEntryFields_ = {
"username",
"displayName",
"salt",
85 "uid",
"permissions",
"lastLoginAttemptTime",
"accountCreatedTime",
86 "loginFailureCount",
"lastModifiedTime",
"lastModifierUsername",
"useremail"};
89 #define __MF_SUBJECT__ "WebUsers"
92 volatile bool WebUsers::CareAboutCookieCodes_ =
true;
102 usersNextUserId_ = 0;
103 usersUsernameWithLock_ =
"";
122 mkdir(((std::string)WEB_LOGIN_DB_PATH).c_str(), 0755);
123 mkdir(((std::string)WEB_LOGIN_DB_PATH +
"bkup/" + USERS_DB_PATH).c_str(), 0755);
124 mkdir(((std::string)WEB_LOGIN_DB_PATH + HASHES_DB_PATH).c_str(), 0755);
125 mkdir(((std::string)WEB_LOGIN_DB_PATH + USERS_DB_PATH).c_str(), 0755);
126 mkdir(((std::string)WEB_LOGIN_DB_PATH + USERS_LOGIN_HISTORY_PATH).c_str(), 0755);
127 mkdir(((std::string)WEB_LOGIN_DB_PATH + USERS_PREFERENCES_PATH).c_str(), 0755);
130 __COUT__ <<
"FATAL USER DATABASE ERROR - failed to load!!!" << __E__;
132 loadSecuritySelection();
136 std::string user = DEFAULT_ADMIN_USERNAME;
137 if((i = searchUsersDatabaseForUsername(user)) == NOT_FOUND_IN_DATABASE)
139 __SS__ <<
"user: " << user <<
" is not found. This should be impossible!"
141 __COUT_ERR__ << ss.str();
144 else if(Users_[i].salt_ ==
146 securityType_ == SECURITY_TYPE_DIGEST_ACCESS)
152 [](
const std::string& nac,
const std::string& user) {
153 WebUsers::NACDisplayThread(nac, user);
155 Users_[i].getNewAccountCode(),
169 __COUT__ <<
"Done with Web Users initialization!" << __E__;
178 std::ostringstream* out,
182 std::lock_guard<std::mutex> lock(webUserMutex_);
190 userInfo.cookieCode_,
191 &userInfo.groupPermissionLevelMap_,
194 !userInfo.automatedCommand_ ,
198 &userInfo.usernameWithLock_,
201 *out << userInfo.cookieCode_;
202 goto HANDLE_ACCESS_FAILURE;
208 i = searchUsersDatabaseForUserId(userInfo.uid_);
209 if(i >= Users_.size())
211 __SS__ <<
"Illegal uid encountered in cookie codes!? " << i << __E__;
212 ss <<
"User size = " << Users_.size() << __E__;
216 userInfo.username_ = Users_[i].username_;
217 userInfo.displayName_ = Users_[i].displayName_;
220 goto HANDLE_ACCESS_FAILURE;
224 HANDLE_ACCESS_FAILURE:
226 if(!userInfo.automatedCommand_)
227 __COUT_ERR__ <<
"Failed request (requestType = " << userInfo.requestType_
228 <<
"): " << out->str() << __E__;
239 userInfo.ip_ = cgi.getEnvironment().getRemoteAddr();
242 userInfo.username_ =
"";
243 userInfo.displayName_ =
"";
244 userInfo.usernameWithLock_ =
"";
258 std::ostringstream* out,
262 const std::string& wizardModeSequence )
268 if(userInfo.requireSecurity_ && userInfo.permissionsThreshold_ > 1)
274 if(isWizardMode && wizardModeSequence.size() < 8)
277 *out << WebUsers::REQ_NO_PERMISSION_RESPONSE;
278 __COUT__ <<
"User (@" << userInfo.ip_ <<
") has attempted requestType '"
279 << userInfo.requestType_
280 <<
"' which requires sufficient security enabled. Please enable the "
282 " sequence of at least 8 characters."
287 else if(!isWizardMode &&
288 (userInfo.username_ == WebUsers::DEFAULT_ADMIN_USERNAME ||
289 userInfo.username_ == WebUsers::DEFAULT_ITERATOR_USERNAME ||
290 userInfo.username_ == WebUsers::DEFAULT_STATECHANGER_USERNAME))
293 *out << WebUsers::REQ_NO_PERMISSION_RESPONSE;
294 __COUT__ <<
"User (@" << userInfo.ip_ <<
") has attempted requestType '"
295 << userInfo.requestType_
296 <<
"' which requires sufficient security enabled. Please enable "
298 " logins (Note: the user admin is disallowed in an attempt to "
299 "force personal accountability for edits)."
307 if(!userInfo.automatedCommand_)
309 __COUTT__ <<
"requestType ==========>>> " << userInfo.requestType_ << __E__;
310 __COUTTV__((
unsigned int)userInfo.permissionLevel_);
311 __COUTTV__((
unsigned int)userInfo.permissionsThreshold_);
315 if(!isWizardMode && !userInfo.allowNoUser_ &&
316 userInfo.cookieCode_.length() != WebUsers::COOKIE_CODE_LENGTH &&
318 userInfo.cookieCode_ ==
322 __COUT__ <<
"User (@" << userInfo.ip_
323 <<
") has invalid cookie code: " << userInfo.cookieCode_ << std::endl;
324 *out << WebUsers::REQ_NO_LOGIN_RESPONSE;
328 if(!userInfo.allowNoUser_ &&
329 (userInfo.permissionLevel_ == 0 ||
330 userInfo.permissionsThreshold_ == 0 ||
331 userInfo.permissionLevel_ < userInfo.permissionsThreshold_))
334 *out << WebUsers::REQ_NO_PERMISSION_RESPONSE;
335 __COUT_INFO__ <<
"User (@" << userInfo.ip_
336 <<
") has insufficient permissions for requestType '"
337 << userInfo.requestType_ <<
"' : user level is "
338 << (
unsigned int)userInfo.permissionLevel_ <<
", "
339 << (
unsigned int)userInfo.permissionsThreshold_ <<
" required."
347 userInfo.username_ = WebUsers::DEFAULT_ADMIN_USERNAME;
348 userInfo.displayName_ =
"Admin";
349 userInfo.usernameWithLock_ = userInfo.username_;
357 if(userInfo.allowNoUser_)
358 xmldoc->setHeader(WebUsers::REQ_ALLOW_NO_USER);
360 xmldoc->setHeader(userInfo.cookieCode_);
363 if(userInfo.allowNoUser_)
365 if(userInfo.automatedCommand_)
366 __COUTT__ <<
"Allowing anonymous access." << __E__;
377 if((userInfo.checkLock_ || userInfo.requireLock_) &&
378 userInfo.usernameWithLock_ !=
"" &&
379 userInfo.usernameWithLock_ != userInfo.username_)
381 *out << WebUsers::REQ_USER_LOCKOUT_RESPONSE;
382 __COUT_INFO__ <<
"User '" << userInfo.username_ <<
"' is locked out. '"
383 << userInfo.usernameWithLock_ <<
"' has lock." << std::endl;
387 if(userInfo.requireLock_ && userInfo.usernameWithLock_ != userInfo.username_)
389 *out << WebUsers::REQ_LOCK_REQUIRED_RESPONSE;
390 __COUT_INFO__ <<
"User '" << userInfo.username_
391 <<
"' must have lock to proceed. ('" << userInfo.usernameWithLock_
392 <<
"' has lock.)" << std::endl;
407 fn = (std::string)WEB_LOGIN_DB_PATH + (std::string)USERS_ACTIVE_SESSIONS_FILE;
408 __COUT__ << fn << __E__;
410 FILE* fp = fopen(fn.c_str(),
"w");
413 __COUT_ERR__ <<
"Error! Persistent active sessions could not be saved to file: "
419 fprintf(fp,
"%d\n", version);
420 for(
unsigned int i = 0; i < ActiveSessions_.size(); ++i)
428 fprintf(fp,
"%s\n", ActiveSessions_[i].cookieCode_.c_str());
429 fprintf(fp,
"%s\n", ActiveSessions_[i].ip_.c_str());
430 fprintf(fp,
"%lu\n", ActiveSessions_[i].userId_);
431 fprintf(fp,
"%lu\n", ActiveSessions_[i].sessionIndex_);
432 fprintf(fp,
"%ld\n", ActiveSessions_[i].startTime_);
435 __COUT__ <<
"Active Sessions saved with size " << ActiveSessions_.size() << __E__;
447 fn = (std::string)WEB_LOGIN_DB_PATH + (std::string)USERS_ACTIVE_SESSIONS_FILE;
448 __COUT__ << fn << __E__;
449 FILE* fp = fopen(fn.c_str(),
"r");
453 <<
"Persistent active sessions were not found to be loaded at file: " << fn
460 const int LINELEN = 1000;
462 fgets(line, LINELEN, fp);
463 sscanf(line,
"%d", &version);
466 __COUT__ <<
"Extracting active sessions..." << __E__;
468 while(fgets(line, LINELEN, fp))
471 line[strlen(line) - 1] =
'\0';
472 if(strlen(line) != COOKIE_CODE_LENGTH)
474 __COUT__ <<
"Illegal cookie code found: " << line << __E__;
480 ActiveSessions_.back().cookieCode_ = line;
482 fgets(line, LINELEN, fp);
484 line[strlen(line) - 1] =
'\0';
485 ActiveSessions_.back().ip_ = line;
487 fgets(line, LINELEN, fp);
488 sscanf(line,
"%lu", &(ActiveSessions_.back().userId_));
490 fgets(line, LINELEN, fp);
491 sscanf(line,
"%lu", &(ActiveSessions_.back().sessionIndex_));
493 fgets(line, LINELEN, fp);
494 sscanf(line,
"%ld", &(ActiveSessions_.back().startTime_));
497 __COUT__ <<
"Active Sessions loaded with size " << ActiveSessions_.size() << __E__;
501 fp = fopen(fn.c_str(),
"w");
510 bool WebUsers::loadDatabases()
515 const unsigned int LINE_LEN = 1000;
517 unsigned int i, si, c, len, f;
528 fn = (std::string)WEB_LOGIN_DB_PATH + (std::string)HASHES_DB_FILE;
529 __COUT__ << fn << __E__;
530 fp = fopen(fn.c_str(),
"r");
533 mkdir(((std::string)WEB_LOGIN_DB_PATH + (std::string)HASHES_DB_PATH).c_str(),
535 __COUT__ << ((std::string)WEB_LOGIN_DB_PATH + (std::string)HASHES_DB_PATH).c_str()
537 fp = fopen(fn.c_str(),
"w");
540 __COUT__ <<
"Hashes database created: " << fn << __E__;
542 saveToDatabase(fp, HASHES_DB_GLOBAL_STRING,
"", DB_SAVE_OPEN);
543 saveToDatabase(fp, HASHES_DB_GLOBAL_STRING,
"", DB_SAVE_CLOSE);
550 while(fgets(line, LINE_LEN, fp))
552 if(strlen(line) < SHA512_DIGEST_LENGTH)
558 for(i = 0; i < len; ++i)
566 while(i < len && line[i] !=
'<')
578 Hashes_.push_back(Hash());
579 Hashes_.back().hash_ = &line[si];
582 sscanf(&line[si],
"%ld", &Hashes_.back().accessTime_);
585 __COUT__ << Hashes_.size() <<
" Hashes found." << __E__;
599 fn = (std::string)WEB_LOGIN_DB_PATH + (std::string)USERS_DB_FILE;
600 fp = fopen(fn.c_str(),
"r");
603 mkdir(((std::string)WEB_LOGIN_DB_PATH + (std::string)USERS_DB_PATH).c_str(),
605 __COUT__ << ((std::string)WEB_LOGIN_DB_PATH + (std::string)USERS_DB_PATH).c_str()
607 fp = fopen(fn.c_str(),
"w");
610 __COUT__ <<
"Users database created: " << fn << __E__;
612 saveToDatabase(fp, USERS_DB_GLOBAL_STRING,
"", DB_SAVE_OPEN);
614 sprintf(nidStr,
"%lu", usersNextUserId_);
615 saveToDatabase(fp, USERS_DB_NEXT_UID_STRING, nidStr, DB_SAVE_OPEN_AND_CLOSE);
616 saveToDatabase(fp, USERS_DB_GLOBAL_STRING,
"", DB_SAVE_CLOSE);
620 DEFAULT_ADMIN_DISPLAY_NAME,
621 DEFAULT_ADMIN_EMAIL);
625 __COUT__ <<
"Users database: " << fn << __E__;
629 char salt[] =
"nextUserId";
630 while(fgets(line, LINE_LEN, fp))
632 if(strlen(line) < strlen(salt) * 2)
635 for(i = 0; i < strlen(salt); ++i)
636 if(line[i + 1] != salt[i])
639 if(i == strlen(salt))
644 while(i < LINE_LEN && line[i] !=
'\0' && line[i] !=
'<')
647 sscanf(&line[si],
"%lu", &usersNextUserId_);
652 __COUT__ <<
"Found Users database next user Id: " << usersNextUserId_ << __E__;
656 while(fgets(line, LINE_LEN, fp))
658 if(strlen(line) < 30)
666 __COUT__ <<
"Line buffer too small: " << len << __E__;
672 for(i = 0; i < len; ++i)
676 if(c == 0 || c % 2 == 1)
680 while(i < len && line[i] !=
'<')
692 Users_.push_back(User());
693 Users_.back().username_ = &line[si];
696 Users_.back().displayName_ = &line[si];
698 Users_.back().salt_ = &line[si];
700 sscanf(&line[si],
"%lu", &Users_.back().userId_);
703 std::map<std::string, permissionLevel_t>& lastPermissionsMap =
704 Users_.back().permissions_;
705 StringMacros::getMapFromString<permissionLevel_t>(
706 &line[si], lastPermissionsMap);
714 if(lastPermissionsMap.find(WebUsers::DEFAULT_USER_GROUP) ==
715 lastPermissionsMap.end())
718 <<
"User '" << Users_.back().username_
719 <<
"' is not a member of the default user group '"
720 << WebUsers::DEFAULT_USER_GROUP
721 <<
".' Assuming user account is inactive (permission "
723 << WebUsers::PERMISSION_LEVEL_INACTIVE <<
")." << __E__;
724 lastPermissionsMap[WebUsers::DEFAULT_USER_GROUP] =
725 WebUsers::PERMISSION_LEVEL_INACTIVE;
728 if(Users_.back().username_ == DEFAULT_ADMIN_USERNAME)
732 std::map<std::string ,
733 WebUsers::permissionLevel_t>
734 initPermissions = {{WebUsers::DEFAULT_USER_GROUP,
737 Users_.back().permissions_ = initPermissions;
741 sscanf(&line[si],
"%ld", &Users_.back().lastLoginAttempt_);
743 sscanf(&line[si],
"%ld", &Users_.back().accountCreationTime_);
745 sscanf(&line[si],
"%hhu", &Users_.back().loginFailureCount_);
747 sscanf(&line[si],
"%ld", &Users_.back().accessModifierTime());
749 Users_.back().loadModifierUsername(&line[si]);
751 Users_.back().email_ = &line[si];
758 __COUT__ << Users_.size() <<
" Users found." << __E__;
759 for(
size_t ii = 0; ii < Users_.size(); ++ii)
762 "User [" << Users_[ii].userId_ <<
"] \tName: " << std::left
763 << std::setfill(
' ') << std::setw(20) << Users_[ii].username_
764 <<
"\tDisplay Name: " << std::left << std::setfill(
' ') << std::setw(30)
765 << Users_[ii].displayName_ <<
"\tEmail: " << std::left
766 << std::setfill(
' ') << std::setw(30) << Users_[ii].email_
767 <<
"\tNAC: " << std::left << std::setfill(
' ') << std::setw(5)
768 << Users_[ii].getNewAccountCode()
769 <<
"\tFailedCount: " << (int)Users_[ii].loginFailureCount_
788 void WebUsers::saveToDatabase(FILE* fp,
789 const std::string& field,
790 const std::string& value,
797 std::string newLine = addNewLine ?
"\n" :
"";
799 if(type == DB_SAVE_OPEN_AND_CLOSE)
806 else if(type == DB_SAVE_OPEN)
807 fprintf(fp,
"<%s>%s%s", field.c_str(), value.c_str(), newLine.c_str());
808 else if(type == DB_SAVE_CLOSE)
809 fprintf(fp,
"</%s>%s", field.c_str(), newLine.c_str());
818 bool WebUsers::saveDatabaseToFile(uint8_t db)
823 (std::string)WEB_LOGIN_DB_PATH +
824 ((db == DB_USERS) ? (std::string)USERS_DB_FILE : (std::string)HASHES_DB_FILE);
826 __COUT__ <<
"Save Database Filename: " << fn << __E__;
832 sprintf(dayAppend,
".%lu.bkup", time(0) / (3600 * 24));
833 std::string bkup_fn = (std::string)WEB_LOGIN_DB_PATH +
834 (std::string)WEB_LOGIN_BKUP_DB_PATH +
835 ((db == DB_USERS) ? (std::string)USERS_DB_FILE
836 : (std::string)HASHES_DB_FILE) +
837 (std::string)dayAppend;
839 __COUT__ <<
"Backup file: " << bkup_fn << __E__;
841 std::string shell_command =
"mv " + fn +
" " + bkup_fn;
842 system(shell_command.c_str());
845 FILE* fp = fopen(fn.c_str(),
"wb");
853 saveToDatabase(fp, USERS_DB_GLOBAL_STRING,
"", DB_SAVE_OPEN);
855 sprintf(fldStr,
"%lu", usersNextUserId_);
856 saveToDatabase(fp, USERS_DB_NEXT_UID_STRING, fldStr, DB_SAVE_OPEN_AND_CLOSE);
858 __COUT__ <<
"Saving " << Users_.size() <<
" Users." << __E__;
860 for(uint64_t i = 0; i < Users_.size(); ++i)
864 saveToDatabase(fp, USERS_DB_ENTRY_STRING,
"", DB_SAVE_OPEN,
false);
866 for(
unsigned int f = 0; f < WebUsers::UsersDatabaseEntryFields_.size(); ++f)
871 WebUsers::UsersDatabaseEntryFields_[f],
873 DB_SAVE_OPEN_AND_CLOSE,
877 WebUsers::UsersDatabaseEntryFields_[f],
878 Users_[i].displayName_,
879 DB_SAVE_OPEN_AND_CLOSE,
883 WebUsers::UsersDatabaseEntryFields_[f],
885 DB_SAVE_OPEN_AND_CLOSE,
889 sprintf(fldStr,
"%lu", Users_[i].userId_);
891 WebUsers::UsersDatabaseEntryFields_[f],
893 DB_SAVE_OPEN_AND_CLOSE,
898 WebUsers::UsersDatabaseEntryFields_[f],
902 DB_SAVE_OPEN_AND_CLOSE,
906 sprintf(fldStr,
"%lu", Users_[i].lastLoginAttempt_);
908 WebUsers::UsersDatabaseEntryFields_[f],
910 DB_SAVE_OPEN_AND_CLOSE,
915 sprintf(fldStr,
"%lu", Users_[i].accountCreationTime_);
917 WebUsers::UsersDatabaseEntryFields_[f],
919 DB_SAVE_OPEN_AND_CLOSE,
924 sprintf(fldStr,
"%hhu", Users_[i].loginFailureCount_);
926 WebUsers::UsersDatabaseEntryFields_[f],
928 DB_SAVE_OPEN_AND_CLOSE,
933 sprintf(fldStr,
"%lu", Users_[i].getModifierTime());
935 WebUsers::UsersDatabaseEntryFields_[f],
937 DB_SAVE_OPEN_AND_CLOSE,
942 WebUsers::UsersDatabaseEntryFields_[f],
943 Users_[i].getModifierUsername(),
944 DB_SAVE_OPEN_AND_CLOSE,
948 WebUsers::UsersDatabaseEntryFields_[f],
950 DB_SAVE_OPEN_AND_CLOSE,
954 saveToDatabase(fp, USERS_DB_ENTRY_STRING,
"", DB_SAVE_CLOSE);
957 saveToDatabase(fp, USERS_DB_GLOBAL_STRING,
"", DB_SAVE_CLOSE);
961 saveToDatabase(fp, HASHES_DB_GLOBAL_STRING,
"", DB_SAVE_OPEN);
963 __COUT__ <<
"Saving " << Hashes_.size() <<
" Hashes." << __E__;
964 for(uint64_t i = 0; i < Hashes_.size(); ++i)
966 __COUT__ <<
"Saving " << Hashes_[i].hash_ <<
" Hash." << __E__;
967 saveToDatabase(fp, HASHES_DB_ENTRY_STRING,
"", DB_SAVE_OPEN,
false);
968 for(
unsigned int f = 0; f < WebUsers::HashesDatabaseEntryFields_.size(); ++f)
972 WebUsers::HashesDatabaseEntryFields_[f],
974 DB_SAVE_OPEN_AND_CLOSE,
978 sprintf(fldStr,
"%lu", Hashes_[i].accessTime_);
980 WebUsers::HashesDatabaseEntryFields_[f],
982 DB_SAVE_OPEN_AND_CLOSE,
986 saveToDatabase(fp, HASHES_DB_ENTRY_STRING,
"", DB_SAVE_CLOSE);
989 saveToDatabase(fp, HASHES_DB_GLOBAL_STRING,
"", DB_SAVE_CLOSE);
1005 const std::string& displayName,
1006 const std::string& email)
1008 __COUT__ <<
"Creating account: " << username << __E__;
1011 if((i = searchUsersDatabaseForUsername(username)) != NOT_FOUND_IN_DATABASE ||
1012 username == WebUsers::DEFAULT_ITERATOR_USERNAME ||
1013 username == WebUsers::DEFAULT_STATECHANGER_USERNAME)
1016 __SS__ <<
"Username '" << username
1017 <<
"' already exists! Please choose a unique username." << __E__;
1022 if((i = searchUsersDatabaseForDisplayName(displayName)) != NOT_FOUND_IN_DATABASE)
1025 __SS__ <<
"Display Name '" << displayName
1026 <<
"' already exists! Please choose a unique display name." << __E__;
1031 Users_.push_back(
User());
1033 Users_.back().username_ = username;
1034 Users_.back().displayName_ = displayName;
1035 Users_.back().email_ = email;
1038 std::map<std::string , WebUsers::permissionLevel_t> initPermissions = {
1039 {WebUsers::DEFAULT_USER_GROUP,
1040 (Users_.size() ? WebUsers::PERMISSION_LEVEL_NOVICE
1043 Users_.back().permissions_ = initPermissions;
1044 Users_.back().userId_ = usersNextUserId_++;
1045 if(usersNextUserId_ >= ACCOUNT_ERROR_THRESHOLD)
1047 __SS__ <<
"usersNextUserId_ wrap around!! Too many users??? Notify Admins."
1050 usersNextUserId_ = 1;
1054 Users_.back().accountCreationTime_ = time(0);
1056 if(!saveDatabaseToFile(DB_USERS))
1058 __SS__ <<
"Failed to save User DB!" << __E__;
1069 bool WebUsers::deleteAccount(
const std::string& username,
const std::string& displayName)
1071 uint64_t i = searchUsersDatabaseForUsername(username);
1072 if(i == NOT_FOUND_IN_DATABASE)
1074 if(Users_[i].displayName_ != displayName)
1079 Users_.erase(Users_.begin() + i);
1082 return saveDatabaseToFile(DB_USERS);
1086 unsigned int WebUsers::hexByteStrToInt(
const char* h)
1089 char hs[3] = {h[0], h[1],
'\0'};
1090 sscanf(hs,
"%X", &rv);
1095 void WebUsers::intToHexStr(
unsigned char i,
char* h) { sprintf(h,
"%2.2X", i); }
1108 std::string& jumbledUser,
1109 const std::string& jumbledPw,
1110 std::string& newAccountCode,
1111 const std::string& ip)
1116 __COUT_ERR__ <<
"rejected ip: " << ip << __E__;
1117 return ACCOUNT_BLACKLISTED;
1122 if(!CareAboutCookieCodes_)
1126 newAccountCode = genCookieCode();
1133 if((i = searchLoginSessionDatabaseForUUID(uuid)) == NOT_FOUND_IN_DATABASE)
1135 __COUT_ERR__ <<
"uuid: " << uuid <<
" is not found" << __E__;
1136 newAccountCode =
"1";
1138 incrementIpBlacklistCount(ip);
1140 return NOT_FOUND_IN_DATABASE;
1142 ++LoginSessions_[i].loginAttempts_;
1144 std::string user = dejumble(jumbledUser, LoginSessions_[i].id_);
1146 std::string pw = dejumble(jumbledPw, LoginSessions_[i].id_);
1149 if((i = searchUsersDatabaseForUsername(user)) == NOT_FOUND_IN_DATABASE)
1151 __COUT_ERR__ <<
"user: " << user <<
" is not found" << __E__;
1153 incrementIpBlacklistCount(ip);
1155 return NOT_FOUND_IN_DATABASE;
1158 ipBlacklistCounts_[ip] = 0;
1160 Users_[i].lastLoginAttempt_ = time(0);
1162 if(isInactiveForGroup(Users_[i].permissions_))
1164 __COUT_ERR__ <<
"User '" << user
1165 <<
"' account INACTIVE (could be due to failed logins)" << __E__;
1166 return ACCOUNT_INACTIVE;
1169 if(Users_[i].salt_ ==
"")
1171 __COUT__ <<
"First login attempt for user: " << user << __E__;
1173 if(newAccountCode != Users_[i].getNewAccountCode())
1175 __COUT__ <<
"New account code did not match: "
1176 << Users_[i].getNewAccountCode() <<
" != " << newAccountCode
1178 saveDatabaseToFile(DB_USERS);
1179 return NOT_FOUND_IN_DATABASE;
1185 while(!addToHashesDatabase(
1186 sha512(user, pw, Users_[i].salt_)))
1191 Users_[i].salt_ =
"";
1194 __COUT__ <<
"\tHash added: " << Hashes_.back().hash_ << __E__;
1198 std::string salt = Users_[i].salt_;
1200 if(searchHashesDatabaseForHash(sha512(user, pw, salt)) == NOT_FOUND_IN_DATABASE)
1202 __COUT__ <<
"Failed login for " << user <<
" with permissions "
1206 if(++Users_[i].loginFailureCount_ != (
unsigned char)-1)
1207 ++Users_[i].loginFailureCount_;
1209 if(Users_[i].loginFailureCount_ >= USERS_MAX_LOGIN_FAILURES)
1210 Users_[i].permissions_[WebUsers::DEFAULT_USER_GROUP] =
1211 WebUsers::PERMISSION_LEVEL_INACTIVE;
1213 __COUT_INFO__ <<
"User/pw for user '" << user
1214 <<
"' was not correct (Failed Attempt #"
1215 << (int)Users_[i].loginFailureCount_ <<
" of "
1216 << (
int)USERS_MAX_LOGIN_FAILURES <<
" allowed)." << __E__;
1218 __COUTV__(isInactiveForGroup(Users_[i].permissions_));
1219 if(isInactiveForGroup(Users_[i].permissions_))
1220 __COUT_INFO__ <<
"Account '" << user
1221 <<
"' has been marked inactive due to too many failed "
1222 "login attempts (Failed Attempt #"
1223 << (int)Users_[i].loginFailureCount_
1224 <<
")! Note only admins can reactivate accounts." << __E__;
1226 saveDatabaseToFile(DB_USERS);
1227 return NOT_FOUND_IN_DATABASE;
1231 __COUT_INFO__ <<
"Login successful for: " << user << __E__;
1233 Users_[i].loginFailureCount_ = 0;
1236 for(
int h = 0; h < 2; ++h)
1238 std::string fn = (std::string)WEB_LOGIN_DB_PATH +
1239 (std::string)USERS_LOGIN_HISTORY_PATH +
1240 (h ? USERS_GLOBAL_HISTORY_FILE : Users_[i].username_) +
"." +
1241 (std::string)USERS_LOGIN_HISTORY_FILETYPE;
1248 (h ? USERS_GLOBAL_HISTORY_SIZE : USERS_LOGIN_HISTORY_SIZE))
1252 __COUT__ <<
"No previous login history found." << __E__;
1258 "Time=%lu Username=%s Permissions=%s UID=%lu",
1260 Users_[i].username_.c_str(),
1265 "Time=%lu displayName=%s Permissions=%s UID=%lu",
1267 Users_[i].displayName_.c_str(),
1270 histXml.addTextElementToData(PREF_XML_LOGIN_HISTORY_FIELD, entryStr);
1277 saveDatabaseToFile(DB_USERS);
1278 jumbledUser = Users_[i].displayName_;
1279 newAccountCode = createNewActiveSession(Users_[i].userId_,
1282 __COUTTV__(ActiveSessions_.size());
1284 if(ActiveSessions_.size() == 1)
1286 __COUT__ <<
"Attempting to auto-lock for first login user '"
1287 << Users_[i].username_ <<
"'... " << __E__;
1291 return Users_[i].userId_;
1302 std::string& cookieCode,
1304 const std::string& ip)
1308 __COUT_ERR__ <<
"rejected ip: " << ip << __E__;
1309 return NOT_FOUND_IN_DATABASE;
1314 if(!CareAboutCookieCodes_)
1318 cookieCode = genCookieCode();
1324 __COUT__ <<
"Rejecting cert logon with blank fingerprint" << __E__;
1326 incrementIpBlacklistCount(ip);
1328 return NOT_FOUND_IN_DATABASE;
1334 if((i = searchLoginSessionDatabaseForUUID(uuid)) == NOT_FOUND_IN_DATABASE)
1336 __COUT__ <<
"uuid: " << uuid <<
" is not found" << __E__;
1339 incrementIpBlacklistCount(ip);
1341 return NOT_FOUND_IN_DATABASE;
1343 ++LoginSessions_[i].loginAttempts_;
1345 email = getUserEmailFromFingerprint(email);
1346 __COUT__ <<
"DejumbledEmail = " << email << __E__;
1349 __COUT__ <<
"Rejecting logon with unknown fingerprint" << __E__;
1351 incrementIpBlacklistCount(ip);
1353 return NOT_FOUND_IN_DATABASE;
1357 if((i = searchUsersDatabaseForUserEmail(email)) == NOT_FOUND_IN_DATABASE)
1359 __COUT__ <<
"email: " << email <<
" is not found" << __E__;
1361 incrementIpBlacklistCount(ip);
1363 return NOT_FOUND_IN_DATABASE;
1366 ipBlacklistCounts_[ip] = 0;
1370 Users_[i].lastLoginAttempt_ = time(0);
1371 if(isInactiveForGroup(Users_[i].permissions_))
1373 __COUT__ <<
"User '" << user
1374 <<
"' account INACTIVE (could be due to failed logins)." << __E__;
1375 return NOT_FOUND_IN_DATABASE;
1378 if(Users_[i].salt_ ==
"")
1380 return NOT_FOUND_IN_DATABASE;
1383 __COUT__ <<
"Login successful for: " << user << __E__;
1385 Users_[i].loginFailureCount_ = 0;
1388 for(
int h = 0; h < 2; ++h)
1390 std::string fn = (std::string)WEB_LOGIN_DB_PATH +
1391 (std::string)USERS_LOGIN_HISTORY_PATH +
1392 (h ? USERS_GLOBAL_HISTORY_FILE : Users_[i].username_) +
"." +
1393 (std::string)USERS_LOGIN_HISTORY_FILETYPE;
1400 (h ? USERS_GLOBAL_HISTORY_SIZE : USERS_LOGIN_HISTORY_SIZE))
1404 __COUT__ <<
"No previous login history found." << __E__;
1410 "Time=%lu Username=%s Permissions=%s UID=%lu",
1412 Users_[i].username_.c_str(),
1417 "Time=%lu displayName=%s Permissions=%s UID=%lu",
1419 Users_[i].displayName_.c_str(),
1422 histXml.addTextElementToData(PREF_XML_LOGIN_HISTORY_FIELD, entryStr);
1429 saveDatabaseToFile(DB_USERS);
1430 email = Users_[i].displayName_;
1431 cookieCode = createNewActiveSession(Users_[i].userId_,
1433 return Users_[i].userId_;
1439 uint64_t WebUsers::searchActiveSessionDatabaseForCookie(
1440 const std::string& cookieCode)
const
1443 for(; i < ActiveSessions_.size(); ++i)
1444 if(ActiveSessions_[i].cookieCode_ == cookieCode)
1446 return (i == ActiveSessions_.size()) ? NOT_FOUND_IN_DATABASE : i;
1464 uint64_t WebUsers::checkRemoteLoginVerification(std::string& cookieCode,
1467 const std::string& ip)
1469 __COUTVS__(2, cookieCode);
1470 remoteLoginVerificationEnabledBlackoutTime_ = 0;
1471 if(!remoteLoginVerificationSocket_)
1476 <<
"Illegal remote login verification port found in remote destination "
1478 <<
". Please check remote settings." << __E__;
1481 __COUT_INFO__ <<
"Instantiating Remote Gateway login verification socket! "
1482 "Validation requests will go to "
1486 remoteLoginVerificationSocket_ =
1487 std::make_unique<TransceiverSocket>(remoteLoginVerificationIP_);
1488 remoteLoginVerificationSocket_->initialize();
1490 remoteLoginVerificationSocketTarget_ = std::make_unique<Socket>(
1496 auto lockHandling = [
this, refresh](std::string username,
1497 uint64_t verifiedUserId) -> uint64_t {
1498 __COUTT__ <<
"lambda lockHandling()" << __E__;
1499 __COUTTV__(ActiveSessions_.size());
1500 __COUTTV__(RemoteSessions_.size());
1502 if((!CareAboutCookieCodes_)
1504 (usersUsernameWithLock_ == DEFAULT_ADMIN_USERNAME ||
1505 usersUsernameWithLock_ ==
"") &&
1506 usersUsernameWithLock_ != username)
1508 __COUT_INFO__ <<
"Overriding local user-with-lock '" << usersUsernameWithLock_
1509 <<
"' with remote user-with-lock 'Remote:" << username <<
"'"
1511 usersUsernameWithLock_ =
1515 getUserWithLock() +
" has locked REMOTE ots (overriding anonymous " +
1516 DEFAULT_ADMIN_USERNAME +
" user).");
1518 else if((ActiveSessions_.size() == 0 &&
1519 RemoteSessions_.size() == 1)
1520 && refresh && (usersUsernameWithLock_ ==
"") &&
1521 usersUsernameWithLock_ != username)
1523 __COUT_INFO__ <<
"Overriding local user-with-lock '" << usersUsernameWithLock_
1524 <<
"' with remote user-with-lock 'Remote:" << username <<
"'"
1526 usersUsernameWithLock_ =
1530 getUserWithLock() +
" has locked REMOTE ots (which was unlocked).");
1532 return verifiedUserId;
1537 __COUTTV__(cookieCode);
1538 __COUTTV__(RemoteSessions_.size());
1539 auto it = RemoteSessions_.find(cookieCode);
1540 if(it != RemoteSessions_.end())
1542 __COUTT__ <<
"cookieCode still active locally!" << __E__;
1543 __COUTV__(it->second.userId_);
1544 uint64_t j = searchUsersDatabaseForUserId(it->second.userId_);
1545 if(j == NOT_FOUND_IN_DATABASE)
1547 __SS__ <<
"Could not find cache entry for remote user ID '"
1548 << it->second.userId_ <<
"' - notify admins." << __E__;
1551 __COUTV__(Users_[j].username_);
1554 return lockHandling(Users_[j].username_, it->second.userId_);
1559 __COUTTV__(doNotGoRemote);
1561 return NOT_FOUND_IN_DATABASE;
1572 std::string request =
"loginVerify," + cookieCode +
"," + (refresh ?
"1" :
"0") +
1578 std::string requestResponseString = remoteLoginVerificationSocket_->sendAndReceive(
1579 *remoteLoginVerificationSocketTarget_, request, 10 );
1580 __COUTV__(requestResponseString);
1583 std::vector<std::string> rxParams =
1587 if(rxParams.size() != 6)
1589 __COUT__ <<
"Remote login response indicates rejected: " << rxParams.size()
1591 return NOT_FOUND_IN_DATABASE;
1603 __COUTTV__(rxParams[2]);
1604 __COUTTV__(usersUsernameWithLock_);
1607 std::string username = rxParams[3];
1608 __COUTTV__(username);
1609 uint64_t j = searchUsersDatabaseForUsername(username);
1610 if(j == NOT_FOUND_IN_DATABASE)
1612 __COUT_INFO__ <<
"Creating User entry for remote user '" << username
1613 <<
"' in local user list to track user preferences." << __E__;
1617 j = Users_.size() - 1;
1620 Users_[j].lastLoginAttempt_ = time(0);
1621 Users_[j].setModifier(
"REMOTE_GATEWAY");
1626 .permissions_.clear();
1628 Users_[j].permissions_);
1630 __COUTV__(Users_[j].username_);
1631 __COUTV__(Users_[j].userId_);
1635 cookieCode = rxParams[0];
1636 __COUTTV__(cookieCode);
1637 ActiveSession& newRemoteSession =
1638 RemoteSessions_[cookieCode];
1639 newRemoteSession.cookieCode_ = cookieCode;
1640 newRemoteSession.ip_ = ip;
1641 newRemoteSession.userId_ = Users_[j].userId_;
1642 sscanf(rxParams[5].c_str(),
"%lu", &newRemoteSession.sessionIndex_);
1643 newRemoteSession.startTime_ = time(0);
1646 return lockHandling(Users_[j].username_, Users_[j].userId_);
1655 if((u = searchUsersDatabaseForUsername(username)) == NOT_FOUND_IN_DATABASE)
1665 __COUTT__ <<
"isUserIdActive? " << uid << __E__;
1668 for(
const auto& remoteSession : RemoteSessions_)
1669 if(remoteSession.second.userId_ == uid)
1674 for(; i < ActiveSessions_.size(); ++i)
1675 if(ActiveSessions_[i].userId_ == uid)
1683 uint64_t WebUsers::searchUsersDatabaseForUsername(
const std::string& username)
const
1686 for(; i < Users_.size(); ++i)
1687 if(Users_[i].username_ == username)
1689 return (i == Users_.size()) ? NOT_FOUND_IN_DATABASE : i;
1695 uint64_t WebUsers::searchUsersDatabaseForDisplayName(
const std::string& displayName)
const
1698 for(; i < Users_.size(); ++i)
1699 if(Users_[i].displayName_ == displayName)
1701 return (i == Users_.size()) ? NOT_FOUND_IN_DATABASE : i;
1707 uint64_t WebUsers::searchUsersDatabaseForUserEmail(
const std::string& useremail)
const
1710 for(; i < Users_.size(); ++i)
1711 if(Users_[i].email_ == useremail)
1713 return (i == Users_.size()) ? NOT_FOUND_IN_DATABASE : i;
1719 uint64_t WebUsers::searchUsersDatabaseForUserId(uint64_t uid)
const
1722 for(; i < Users_.size(); ++i)
1723 if(Users_[i].userId_ == uid)
1725 return (i == Users_.size()) ? NOT_FOUND_IN_DATABASE : i;
1731 uint64_t WebUsers::searchLoginSessionDatabaseForUUID(
const std::string& uuid)
const
1734 for(; i < LoginSessions_.size(); ++i)
1735 if(LoginSessions_[i].uuid_ == uuid)
1737 return (i == LoginSessions_.size()) ? NOT_FOUND_IN_DATABASE : i;
1743 uint64_t WebUsers::searchHashesDatabaseForHash(
const std::string& hash)
1747 for(; i < Hashes_.size(); ++i)
1748 if(Hashes_[i].hash_ == hash)
1753 if(i < Hashes_.size())
1754 Hashes_[i].accessTime_ =
1755 ((time(0) + (rand() % 2 ? 1 : -1) * (rand() % 30 * 24 * 60 * 60)) &
1756 0x0FFFFFFFFFE000000);
1761 return (i == Hashes_.size()) ? NOT_FOUND_IN_DATABASE : i;
1768 bool WebUsers::addToHashesDatabase(
const std::string& hash)
1770 if(searchHashesDatabaseForHash(hash) != NOT_FOUND_IN_DATABASE)
1772 __COUT__ <<
"Hash collision: " << hash << __E__;
1775 Hashes_.push_back(Hash());
1776 Hashes_.back().hash_ = hash;
1777 Hashes_.back().accessTime_ =
1778 ((time(0) + (rand() % 2 ? 1 : -1) * (rand() % 30 * 24 * 60 * 60)) &
1779 0x0FFFFFFFFFE000000);
1782 return saveDatabaseToFile(DB_HASHES);
1787 std::string WebUsers::genCookieCode()
1790 std::string cc =
"";
1791 for(uint32_t i = 0; i < COOKIE_CODE_LENGTH / 2; ++i)
1793 intToHexStr(rand(), hexStr);
1803 std::string WebUsers::createNewActiveSession(uint64_t uid,
1804 const std::string& ip,
1808 ActiveSessions_.push_back(ActiveSession());
1809 ActiveSessions_.back().cookieCode_ = genCookieCode();
1810 ActiveSessions_.back().ip_ = ip;
1811 ActiveSessions_.back().userId_ = uid;
1812 ActiveSessions_.back().startTime_ = time(0);
1815 ActiveSessions_.back().sessionIndex_ = asIndex;
1820 for(uint64_t j = 0; j < ActiveSessions_.size(); ++j)
1821 if(ActiveSessions_[j].userId_ == uid &&
1822 max < ActiveSessions_[j].sessionIndex_)
1823 max = ActiveSessions_[j].sessionIndex_;
1825 ActiveSessions_.back().sessionIndex_ = (max ? max + 1 : 1);
1828 return ActiveSessions_.back().cookieCode_;
1855 std::string WebUsers::refreshCookieCode(
unsigned int i,
bool enableRefresh)
1858 for(uint64_t j = ActiveSessions_.size() - 1; j != (uint64_t)-1;
1860 if(ActiveSessions_[j].userId_ == ActiveSessions_[i].userId_ &&
1861 ActiveSessions_[j].sessionIndex_ ==
1862 ActiveSessions_[i].sessionIndex_)
1867 if(enableRefresh && (time(0) - ActiveSessions_[j].startTime_ >
1868 ACTIVE_SESSION_EXPIRATION_TIME / 2))
1872 ActiveSessions_[j].startTime_ =
1873 time(0) - ACTIVE_SESSION_EXPIRATION_TIME +
1874 ACTIVE_SESSION_COOKIE_OVERLAP_TIME;
1880 return createNewActiveSession(ActiveSessions_[i].userId_,
1881 ActiveSessions_[i].ip_,
1882 ActiveSessions_[i].sessionIndex_);
1885 return ActiveSessions_[j].cookieCode_;
1897 std::string& cookieCode,
1898 std::string& username)
1900 if(!CareAboutCookieCodes_)
1907 if(!ActiveSessions_.size())
1908 return NOT_FOUND_IN_DATABASE;
1913 if((i = searchLoginSessionDatabaseForUUID(uuid)) == NOT_FOUND_IN_DATABASE)
1915 __COUT__ <<
"uuid not found: " << uuid << __E__;
1916 return NOT_FOUND_IN_DATABASE;
1920 dejumble(username, LoginSessions_[i].id_);
1923 if((i = searchActiveSessionDatabaseForCookie(cookieCode)) == NOT_FOUND_IN_DATABASE)
1925 __COUT__ <<
"Cookie code not found" << __E__;
1926 return NOT_FOUND_IN_DATABASE;
1930 if((j = searchUsersDatabaseForUserId(ActiveSessions_[i].userId_)) ==
1931 NOT_FOUND_IN_DATABASE)
1933 __COUT__ <<
"User ID not found" << __E__;
1934 return NOT_FOUND_IN_DATABASE;
1938 if(Users_[j].username_ != username)
1940 __COUT__ <<
"cookieCode: " << cookieCode <<
" was.." << __E__;
1941 __COUT__ <<
"username: " << username <<
" is not found" << __E__;
1942 return NOT_FOUND_IN_DATABASE;
1945 username = Users_[j].displayName_;
1946 cookieCode = refreshCookieCode(i);
1947 return Users_[j].userId_;
1956 std::vector<uint64_t> uniqueAsi;
1959 for(i = 0; i < ActiveSessions_.size(); ++i)
1960 if(ActiveSessions_[i].userId_ == uid)
1965 for(j = 0; j < uniqueAsi.size(); ++j)
1966 if(uniqueAsi[j] == ActiveSessions_[i].sessionIndex_)
1973 uniqueAsi.push_back(ActiveSessions_[i].sessionIndex_);
1976 __COUT__ <<
"Found " << uniqueAsi.size() <<
" active sessions for uid " << uid
1979 return uniqueAsi.size();
1995 if(time(0) > ipSecurityLastLoadTime_ +
1998 ipSecurityLastLoadTime_ = time(0);
1999 loadIPAddressSecurity();
2002 for(
const auto& acceptIp : ipAccessAccept_)
2005 __COUTV__(acceptIp);
2008 for(
const auto& rejectIp : ipAccessReject_)
2011 __COUTV__(rejectIp);
2014 for(
const auto& blacklistIp : ipAccessBlacklist_)
2017 __COUTV__(blacklistIp);
2027 void WebUsers::incrementIpBlacklistCount(
const std::string& ip)
2029 if(ipAccessBlacklist_.find(ip) != ipAccessBlacklist_.end())
2033 auto it = ipBlacklistCounts_.find(ip);
2034 if(it == ipBlacklistCounts_.end())
2036 __COUT__ <<
"First error for ip '" << ip <<
"'" << __E__;
2037 ipBlacklistCounts_[ip] = 1;
2043 if(it->second >= IP_BLACKLIST_COUNT_THRESHOLD)
2045 __COUT_WARN__ <<
"Adding IP '" << ip <<
"' to blacklist!" << __E__;
2047 ipAccessBlacklist_.emplace(ip);
2048 __COUTV__(ipAccessBlacklist_.size());
2051 FILE* fp = fopen((IP_BLACKLIST_FILE).c_str(),
"a");
2054 __COUT_ERR__ <<
"IP black list file '" << IP_BLACKLIST_FILE
2055 <<
"' could not be opened." << __E__;
2058 fprintf(fp,
"%s\n", ip.c_str());
2069 if((i = searchUsersDatabaseForUserId(uid)) == NOT_FOUND_IN_DATABASE)
2071 return Users_[i].displayName_;
2079 if((i = searchUsersDatabaseForUserId(uid)) == NOT_FOUND_IN_DATABASE)
2081 return Users_[i].username_;
2096 bool logoutOtherUserSessions,
2098 const std::string& ip)
2103 if((i = searchActiveSessionDatabaseForCookie(cookieCode)) == NOT_FOUND_IN_DATABASE)
2105 __COUT__ <<
"Cookie code not found" << __E__;
2107 incrementIpBlacklistCount(ip);
2109 return NOT_FOUND_IN_DATABASE;
2112 ipBlacklistCounts_[ip] = 0;
2115 if(ActiveSessions_[i].ip_ != ip)
2117 __COUT__ <<
"IP does not match active session" << __E__;
2118 return NOT_FOUND_IN_DATABASE;
2127 uint64_t asi = ActiveSessions_[i].sessionIndex_;
2128 uint64_t uid = ActiveSessions_[i].userId_;
2131 uint64_t logoutCount = 0;
2134 while(i < ActiveSessions_.size())
2136 if((logoutOtherUserSessions && ActiveSessions_[i].userId_ == uid &&
2137 ActiveSessions_[i].sessionIndex_ != asi) ||
2138 (!logoutOtherUserSessions && ActiveSessions_[i].userId_ == uid &&
2139 ActiveSessions_[i].sessionIndex_ == asi))
2141 __COUT__ <<
"Logging out of active session " << ActiveSessions_[i].userId_
2142 <<
"-" << ActiveSessions_[i].sessionIndex_ << __E__;
2143 ActiveSessions_.erase(ActiveSessions_.begin() + i);
2150 __COUT__ <<
"Found and removed active session count = " << logoutCount << __E__;
2169 std::string& cookieCode,
2170 std::map<std::string /*groupName*/, WebUsers::permissionLevel_t>* userPermissions,
2172 const std::string& ip,
2175 std::string* userWithLock,
2176 uint64_t* userSessionIndex)
2184 __COUT_ERR__ <<
"User IP rejected." << __E__;
2185 cookieCode = REQ_NO_LOGIN_RESPONSE;
2191 uint64_t i, j, userId = NOT_FOUND_IN_DATABASE, userSession = NOT_FOUND_IN_DATABASE;
2193 __COUTTV__(CareAboutCookieCodes_);
2194 __COUTT__ <<
"refresh=" << refresh <<
", doNotGoRemote=" << doNotGoRemote << __E__;
2195 __COUTVS__(2, cookieCode);
2199 __COUTTV__(localEnableRemoteLogin);
2204 if(localEnableRemoteLogin &&
2205 time(0) > remoteLoginVerificationEnabledBlackoutTime_ &&
2206 (userId = checkRemoteLoginVerification(
2207 cookieCode, refresh, doNotGoRemote, ip)) != NOT_FOUND_IN_DATABASE)
2210 __COUTT__ <<
"Remote login session verified." << __E__;
2211 userSession = RemoteSessions_.at(cookieCode).sessionIndex_;
2216 std::string err =
"";
2221 catch(
const std::exception& e)
2226 __COUT_WARN__ <<
"Ignoring exception during remote login verification. " << err
2230 if(!CareAboutCookieCodes_ && localEnableRemoteLogin &&
2231 remoteLoginVerificationEnabledBlackoutTime_ == 0)
2234 localEnableRemoteLogin =
false;
2235 remoteLoginVerificationEnabledBlackoutTime_ = time(0) + 10;
2236 __COUT_INFO__ <<
"Disabled remote login until "
2238 remoteLoginVerificationEnabledBlackoutTime_)
2242 __COUTTV__(localEnableRemoteLogin);
2244 if(localEnableRemoteLogin && userId == NOT_FOUND_IN_DATABASE)
2245 __COUTT__ <<
"Remote login verification failed." << __E__;
2247 if(!CareAboutCookieCodes_ &&
2248 userId == NOT_FOUND_IN_DATABASE)
2252 std::map<std::string , WebUsers::permissionLevel_t>(
2257 *userWithLock = usersUsernameWithLock_;
2258 if(userSessionIndex)
2259 *userSessionIndex = 0;
2261 if(cookieCode.size() != COOKIE_CODE_LENGTH)
2262 cookieCode = genCookieCode();
2264 if(localEnableRemoteLogin)
2266 cookieCode = WebUsers::
2274 if(userId == NOT_FOUND_IN_DATABASE)
2277 if((i = searchActiveSessionDatabaseForCookie(cookieCode)) ==
2278 NOT_FOUND_IN_DATABASE)
2280 __COUT_ERR__ <<
"Cookie code not found" << __E__;
2281 cookieCode = REQ_NO_LOGIN_RESPONSE;
2283 incrementIpBlacklistCount(ip);
2288 ipBlacklistCounts_[ip] = 0;
2291 if(ip !=
"0" && ActiveSessions_[i].ip_ != ip)
2293 __COUTV__(ActiveSessions_[i].ip_);
2295 __COUT_ERR__ <<
"IP does not match active session." << __E__;
2296 cookieCode = REQ_NO_LOGIN_RESPONSE;
2300 userId = ActiveSessions_[i].userId_;
2301 userSession = ActiveSessions_[i].sessionIndex_;
2302 cookieCode = refreshCookieCode(i, refresh);
2303 __COUTT__ <<
"Login session verified." << __E__;
2309 if((j = searchUsersDatabaseForUserId(userId)) == NOT_FOUND_IN_DATABASE)
2311 __COUT_ERR__ <<
"After login verification, User ID not found! Notify admins."
2313 cookieCode = REQ_NO_LOGIN_RESPONSE;
2317 std::map<std::string , WebUsers::permissionLevel_t> tmpPerm =
2320 if(isInactiveForGroup(tmpPerm))
2322 __COUTT__ <<
"Inactive user identified." << __E__;
2323 cookieCode = REQ_NO_PERMISSION_RESPONSE;
2329 *userPermissions = tmpPerm;
2333 *userWithLock = usersUsernameWithLock_;
2334 if(userSessionIndex)
2335 *userSessionIndex = userSession;
2352 if(loggedOutUsernames)
2354 for(i = 0; i < UsersLoggedOutUsernames_.size(); ++i)
2355 loggedOutUsernames->push_back(UsersLoggedOutUsernames_[i]);
2356 UsersLoggedOutUsernames_.clear();
2360 for(i = 0; i < LoginSessions_.size(); ++i)
2361 if(LoginSessions_[i].startTime_ + LOGIN_SESSION_EXPIRATION_TIME <
2363 LoginSessions_[i].loginAttempts_ > LOGIN_SESSION_ATTEMPTS_MAX)
2365 __COUT__ <<
"Found expired login sessions: #" << (i + 1) <<
" of "
2366 << LoginSessions_.size() << __E__;
2370 LoginSessions_.erase(LoginSessions_.begin() + i);
2383 for(i = 0; i < ActiveSessions_.size(); ++i)
2384 if(ActiveSessions_[i].startTime_ + ACTIVE_SESSION_EXPIRATION_TIME <=
2394 __COUT__ <<
"Found expired active sessions: #" << (i + 1) <<
" of "
2395 << ActiveSessions_.size() << __E__;
2396 __COUTTV__(ActiveSessions_[i].cookieCode_);
2398 tmpUid = ActiveSessions_[i].userId_;
2399 ActiveSessions_.erase(ActiveSessions_.begin() + i);
2404 if(loggedOutUsernames)
2405 loggedOutUsernames->push_back(
2406 Users_[searchUsersDatabaseForUserId(tmpUid)].username_);
2408 UsersLoggedOutUsernames_.push_back(
2409 Users_[searchUsersDatabaseForUserId(tmpUid)].username_);
2430 if(CareAboutCookieCodes_ && usersUsernameWithLock_ !=
"" &&
2438 usersUsernameWithLock_ =
"";
2448 std::vector<std::string> toErase;
2449 for(
const auto& remoteSession : RemoteSessions_)
2450 if(remoteSession.second.startTime_ + ACTIVE_SESSION_EXPIRATION_TIME / 4 <=
2453 __COUT__ <<
"Found expired remote active sessions: #" << remoteSession.first
2454 <<
" in " << RemoteSessions_.size() << __E__;
2455 toErase.push_back(remoteSession.first);
2457 for(
const auto& eraseId : toErase)
2458 RemoteSessions_.erase(eraseId);
2469 const std::string& ip)
2475 for(; i < LoginSessions_.size(); ++i)
2476 if(LoginSessions_[i].uuid_ == UUID)
2479 if(i != LoginSessions_.size())
2481 __COUT_ERR__ <<
"UUID: " << UUID <<
" is not unique" << __E__;
2487 LoginSessions_.back().uuid_ = UUID;
2491 std::string sid =
"";
2492 for(i = 0; i < SESSION_ID_LENGTH / 2; ++i)
2494 intToHexStr(rand(), hexStr);
2497 LoginSessions_.back().id_ = sid;
2498 LoginSessions_.back().ip_ = ip;
2499 LoginSessions_.back().startTime_ = time(0);
2500 LoginSessions_.back().loginAttempts_ = 0;
2510 std::string WebUsers::sha512(
const std::string& user,
2511 const std::string& password,
2514 SHA512_CTX sha512_context;
2519 SHA512_Init(&sha512_context);
2521 for(
unsigned int i = 0; i < 8; ++i)
2522 sha512_context.h[i] += rand();
2524 for(
unsigned int i = 0; i <
sizeof(SHA512_CTX); ++i)
2526 intToHexStr((uint8_t)(((uint8_t*)(&sha512_context))[i]), hexStr);
2528 salt.append(hexStr);
2536 for(
unsigned int i = 0; i <
sizeof(SHA512_CTX); ++i)
2537 ((uint8_t*)(&sha512_context))[i] = hexByteStrToInt(&(salt.c_str()[i * 2]));
2540 std::string strToHash = salt + user + password;
2543 unsigned char hash[SHA512_DIGEST_LENGTH];
2545 char retHash[SHA512_DIGEST_LENGTH * 2 + 1];
2549 SHA512_Update(&sha512_context, strToHash.c_str(), strToHash.length());
2551 SHA512_Final(hash, &sha512_context);
2555 for(i = 0; i < SHA512_DIGEST_LENGTH; i++)
2556 sprintf(retHash + (i * 2),
"%02x", hash[i]);
2559 retHash[SHA512_DIGEST_LENGTH * 2] =
'\0';
2570 std::string WebUsers::dejumble(
const std::string& u,
const std::string& s)
2572 if(s.length() != SESSION_ID_LENGTH)
2575 const int ss = s.length() / 2;
2576 int p = hexByteStrToInt(&(s.c_str()[0])) % ss;
2577 int n = hexByteStrToInt(&(s.c_str()[p * 2])) % ss;
2578 int len = (hexByteStrToInt(&(u.c_str()[p * 2])) - p - n + ss * 3) % ss;
2580 std::vector<bool> x(ss);
2581 for(
int i = 0; i < ss; ++i)
2585 int c = hexByteStrToInt(&(u.c_str()[p * 2]));
2587 std::string user =
"";
2589 for(
int l = 0; l < len; ++l)
2591 p = (p + hexByteStrToInt(&(s.c_str()[p * 2]))) % ss;
2595 n = hexByteStrToInt(&(s.c_str()[p * 2]));
2596 user.append(1, (hexByteStrToInt(&(u.c_str()[p * 2])) - c - n + ss * 4) % ss);
2597 c = hexByteStrToInt(&(u.c_str()[p * 2]));
2606 std::map<std::string , WebUsers::permissionLevel_t>
2609 uint64_t userIndex = searchUsersDatabaseForUserId(uid);
2610 if(userIndex < Users_.size())
2611 return Users_[userIndex].permissions_;
2614 std::map<std::string , WebUsers::permissionLevel_t> retErrorMap;
2615 retErrorMap[WebUsers::DEFAULT_USER_GROUP] = WebUsers::PERMISSION_LEVEL_INACTIVE;
2652 WebUsers::permissionLevel_t WebUsers::getPermissionLevelForGroup(
2653 const std::map<std::string /*groupName*/, WebUsers::permissionLevel_t>& permissionMap,
2654 const std::string& groupName)
2656 auto it = permissionMap.find(groupName);
2657 if(it == permissionMap.end())
2659 __COUT__ <<
"Group name '" << groupName
2660 <<
"' not found - assuming inactive user in this group." << __E__;
2661 return WebUsers::PERMISSION_LEVEL_INACTIVE;
2667 bool WebUsers::isInactiveForGroup(
2668 const std::map<std::string /*groupName*/, WebUsers::permissionLevel_t>& permissionMap,
2669 const std::string& groupName)
2671 return getPermissionLevelForGroup(permissionMap, groupName) ==
2672 WebUsers::PERMISSION_LEVEL_INACTIVE;
2676 bool WebUsers::isAdminForGroup(
2677 const std::map<std::string /*groupName*/, WebUsers::permissionLevel_t>& permissionMap,
2678 const std::string& groupName)
2680 return getPermissionLevelForGroup(permissionMap, groupName) ==
2687 std::string WebUsers::getTooltipFilename(
const std::string& username,
2688 const std::string& srcFile,
2689 const std::string& srcFunc,
2690 const std::string& srcId)
2692 std::string filename = (std::string)WEB_LOGIN_DB_PATH + TOOLTIP_DB_PATH +
"/";
2696 mkdir(((std::string)WEB_LOGIN_DB_PATH).c_str(), 0755);
2697 mkdir(((std::string)WEB_LOGIN_DB_PATH + USERS_DB_PATH).c_str(), 0755);
2698 mkdir(filename.c_str(), 0755);
2700 for(
const char& c : username)
2702 (c >=
'a' && c <=
'z') || (c >=
'A' && c <=
'Z') || (c >=
'0' && c <=
'9'))
2707 mkdir(filename.c_str(), 0755);
2709 for(
const char& c : srcFile)
2711 (c >=
'a' && c <=
'z') || (c >=
'A' && c <=
'Z') || (c >=
'0' && c <=
'9'))
2714 for(
const char& c : srcFunc)
2716 (c >=
'a' && c <=
'z') || (c >=
'A' && c <=
'Z') || (c >=
'0' && c <=
'9'))
2719 for(
const char& c : srcId)
2721 (c >=
'a' && c <=
'z') || (c >=
'A' && c <=
'Z') || (c >=
'0' && c <=
'9'))
2728 std::string ots::WebUsers::getUserEmailFromFingerprint(
const std::string& fingerprint)
2730 __COUT__ <<
"Checking if user fingerprint " << fingerprint <<
" is in memory database"
2732 if(certFingerprints_.count(fingerprint))
2734 return certFingerprints_[fingerprint];
2737 __COUT__ <<
"Going to read credential database " << WEB_LOGIN_CERTDATA_PATH << __E__;
2738 std::ifstream f(WEB_LOGIN_CERTDATA_PATH);
2746 if(fp !=
"NOKEY" && fp !=
"")
2748 __COUT__ <<
"Adding user " << email <<
" to list with fingerprint " << fp
2750 certFingerprints_[fp] = email;
2756 remove(WEB_LOGIN_CERTDATA_PATH.c_str());
2759 __COUT__ <<
"Checking again if fingerprint is in memory database" << __E__;
2760 if(certFingerprints_.count(fingerprint))
2762 return certFingerprints_[fingerprint];
2765 __COUT__ <<
"Could not match fingerprint, returning null email" << __E__;
2774 const std::string& srcFile,
2775 const std::string& srcFunc,
2776 const std::string& srcId,
2778 bool temporarySilence)
2780 std::string filename;
2781 bool isForAll = (srcFile ==
"ALL" && srcFunc ==
"ALL" && srcId ==
"ALL");
2785 __COUT__ <<
"Disabling ALL tooltips for user '" << username <<
"' is now set to "
2786 << doNeverShow <<
" (temporarySilence=" << temporarySilence <<
")"
2788 filename = getTooltipFilename(username, SILENCE_ALL_TOOLTIPS_FILENAME,
"",
"");
2792 filename = getTooltipFilename(username, srcFile, srcFunc, srcId);
2793 __COUT__ <<
"Setting tooltip never show for user '" << username <<
"' to "
2794 << doNeverShow <<
" (temporarySilence=" << temporarySilence <<
")"
2799 __COUTTV__(doNeverShow);
2800 __COUTTV__(temporarySilence);
2802 __COUTTV__(srcFunc);
2803 __COUTTV__(srcFile);
2804 __COUTTV__(filename);
2807 FILE* fp = fopen(filename.c_str(),
"w");
2810 if(temporarySilence)
2813 time(0) + 7 * 24 * 60 * 60);
2814 else if(!isForAll && doNeverShow && username == WebUsers::DEFAULT_ADMIN_USERNAME)
2817 fprintf(fp,
"%ld", time(0) + 30 * 24 * 60 * 60);
2819 __COUT__ <<
"User '" << username
2820 <<
"' may be a shared account, so max silence duration for tooltips "
2821 "is 30 days. Silencing now."
2825 fputc(doNeverShow ?
'1' :
'0', fp);
2829 __COUT_ERR__ <<
"Big problem with tooltips! File not accessible: " << filename
2842 const std::string& srcFile,
2843 const std::string& srcFunc,
2844 const std::string& srcId)
2846 if(srcId ==
"ALWAYS")
2849 xmldoc->addTextElementToData(
"ShowTooltip",
"1");
2854 std::string silencefilename =
2855 getTooltipFilename(username, SILENCE_ALL_TOOLTIPS_FILENAME,
"",
"");
2859 __COUTTV__(username);
2861 __COUTTV__(srcFunc);
2862 __COUTTV__(srcFile);
2863 __COUTTV__(silencefilename);
2866 FILE* silencefp = fopen(silencefilename.c_str(),
"r");
2867 if(silencefp != NULL)
2871 fgets(line, 100, silencefp);
2872 sscanf(line,
"%ld", &val);
2876 xmldoc->addTextElementToData(
"ShowTooltip",
"0");
2882 std::string filename = getTooltipFilename(username, srcFile, srcFunc, srcId);
2883 FILE* fp = fopen(filename.c_str(),
"r");
2888 fgets(line, 100, fp);
2889 sscanf(line,
"%ld", &val);
2892 __COUT__ <<
"tooltip value read = " << val <<
" vs time(0)=" << time(0) << __E__;
2896 xmldoc->addTextElementToData(
"ShowTooltip",
2897 val == 1 ?
"0" : (time(0) > val ?
"1" :
"0"));
2901 xmldoc->addTextElementToData(
"ShowTooltip",
"1");
2911 (
"rm -rf " + (std::string)WEB_LOGIN_DB_PATH + TOOLTIP_DB_PATH +
"/" + userNeedle)
2913 __COUT__ <<
"Successfully reset Tooltips for user " << userNeedle << __E__;
2921 std::string silencefilename = getTooltipFilename(
2922 username, SILENCE_ALL_TOOLTIPS_FILENAME,
"",
"");
2924 __COUTV__(silencefilename);
2925 FILE* silencefp = fopen(silencefilename.c_str(),
"w");
2926 if(silencefp != NULL)
2928 fputs(
"1", silencefp);
2956 bool includeAccounts)
2958 std::map<std::string , WebUsers::permissionLevel_t> permissionMap =
2962 if(isInactiveForGroup(permissionMap))
2965 uint64_t userIndex = searchUsersDatabaseForUserId(uid);
2966 __COUT__ <<
"Gettings settings for user: " << Users_[userIndex].username_ << __E__;
2968 std::string fn = (std::string)WEB_LOGIN_DB_PATH +
2969 (std::string)USERS_PREFERENCES_PATH + Users_[userIndex].username_ +
2970 "." + (std::string)USERS_PREFERENCES_FILETYPE;
2974 __COUT__ <<
"Preferences file: " << fn << __E__;
2978 __COUT__ <<
"Preferences are defaults." << __E__;
2980 xmldoc->addTextElementToData(PREF_XML_BGCOLOR_FIELD, PREF_XML_BGCOLOR_DEFAULT);
2981 xmldoc->addTextElementToData(PREF_XML_DBCOLOR_FIELD, PREF_XML_DBCOLOR_DEFAULT);
2982 xmldoc->addTextElementToData(PREF_XML_WINCOLOR_FIELD, PREF_XML_WINCOLOR_DEFAULT);
2983 xmldoc->addTextElementToData(PREF_XML_LAYOUT_FIELD, PREF_XML_LAYOUT_DEFAULT);
2987 __COUT__ <<
"Saved Preferences found." << __E__;
2992 if(includeAccounts && isAdminForGroup(permissionMap))
2994 __COUT__ <<
"Admin on our hands" << __E__;
2996 xmldoc->addTextElementToData(PREF_XML_ACCOUNTS_FIELD,
"");
2998 if(Users_.size() == 0)
3000 __COUT__ <<
"Missing users? Attempting to load database" << __E__;
3005 for(uint64_t i = 0; i < Users_.size(); ++i)
3008 "username", Users_[i].username_, PREF_XML_ACCOUNTS_FIELD);
3010 "display_name", Users_[i].displayName_, PREF_XML_ACCOUNTS_FIELD);
3012 if(Users_[i].email_.size() > i)
3015 "useremail", Users_[i].email_, PREF_XML_ACCOUNTS_FIELD);
3025 PREF_XML_ACCOUNTS_FIELD);
3028 "nac", Users_[i].getNewAccountCode().c_str(), PREF_XML_ACCOUNTS_FIELD);
3033 fn = (std::string)WEB_LOGIN_DB_PATH + (std::string)USERS_PREFERENCES_PATH +
3034 (std::string)SYSTEM_PREFERENCES_PREFIX +
"." +
3035 (std::string)USERS_PREFERENCES_FILETYPE;
3038 __COUT__ <<
"System Preferences are defaults." << __E__;
3040 xmldoc->addTextElementToData(PREF_XML_SYSLAYOUT_FIELD,
3041 PREF_XML_SYSLAYOUT_DEFAULT);
3045 __COUT__ <<
"Saved System Preferences found." << __E__;
3052 xmldoc->addTextElementToData(PREF_XML_PERMISSIONS_FIELD,
3056 xmldoc->addTextElementToData(PREF_XML_USERLOCK_FIELD, usersUsernameWithLock_);
3059 xmldoc->addTextElementToData(PREF_XML_USERNAME_FIELD,
getUsersUsername(uid));
3065 xmldoc->addTextElementToData(
"ots_remote_address",
3066 remoteLoginVerificationIP_ +
":" +
3075 const std::string& preferenceName,
3076 const std::string& preferenceValue)
3078 uint64_t userIndex = searchUsersDatabaseForUserId(uid);
3083 std::string safePreferenceName =
"";
3084 for(
const auto& c : preferenceName)
3085 if((c >=
'a' && c <=
'z') || (c >=
'A' && c <=
'Z') || (c >=
'0' && c <=
'9') ||
3086 (c >=
'-' || c <=
'_'))
3087 safePreferenceName += c;
3089 std::string dir = (std::string)WEB_LOGIN_DB_PATH +
3090 (std::string)USERS_PREFERENCES_PATH +
"generic_" +
3091 safePreferenceName +
"/";
3094 mkdir(dir.c_str(), 0755);
3096 std::string fn = Users_[userIndex].username_ +
"_" + safePreferenceName +
"." +
3097 (std::string)USERS_PREFERENCES_FILETYPE;
3099 __COUT__ <<
"Preferences file: " << (dir + fn) << __E__;
3101 FILE* fp = fopen((dir + fn).c_str(),
"w");
3104 fprintf(fp,
"%s", preferenceValue.c_str());
3108 __COUT_ERR__ <<
"Preferences file could not be opened for writing!" << __E__;
3116 const std::string& preferenceName,
3119 uint64_t userIndex = searchUsersDatabaseForUserId(uid);
3124 std::string safePreferenceName =
"";
3125 for(
const auto& c : preferenceName)
3126 if((c >=
'a' && c <=
'z') || (c >=
'A' && c <=
'Z') || (c >=
'0' && c <=
'9') ||
3127 (c >=
'-' || c <=
'_'))
3128 safePreferenceName += c;
3130 std::string dir = (std::string)WEB_LOGIN_DB_PATH +
3131 (std::string)USERS_PREFERENCES_PATH +
"generic_" +
3132 safePreferenceName +
"/";
3134 std::string fn = Users_[userIndex].username_ +
"_" + safePreferenceName +
"." +
3135 (std::string)USERS_PREFERENCES_FILETYPE;
3137 __COUT__ <<
"Preferences file: " << (dir + fn) << __E__;
3140 FILE* fp = fopen((dir + fn).c_str(),
"r");
3143 fseek(fp, 0, SEEK_END);
3144 const long size = ftell(fp);
3145 char* line =
new char
3149 fread(line, 1, size, fp);
3152 std::string retVal(line, size);
3155 __COUT__ <<
"Read value (sz = " << retVal.size() <<
") " << retVal << __E__;
3157 xmldoc->addTextElementToData(safePreferenceName, retVal);
3161 __COUT__ <<
"Using default value." << __E__;
3165 xmldoc->addTextElementToData(safePreferenceName,
"");
3172 const std::string& bgcolor,
3173 const std::string& dbcolor,
3174 const std::string& wincolor,
3175 const std::string& layout,
3176 const std::string& syslayout,
3177 const std::string& aliaslayout,
3178 const std::string& sysaliaslayout)
3180 std::map<std::string , WebUsers::permissionLevel_t> permissionMap =
3182 if(isInactiveForGroup(permissionMap))
3185 uint64_t userIndex = searchUsersDatabaseForUserId(uid);
3186 __COUT__ <<
"Changing settings for user: " << Users_[userIndex].username_ << __E__;
3188 std::string fn = (std::string)WEB_LOGIN_DB_PATH +
3189 (std::string)USERS_PREFERENCES_PATH + Users_[userIndex].username_ +
3190 "." + (std::string)USERS_PREFERENCES_FILETYPE;
3192 __COUT__ <<
"Preferences file: " << fn << __E__;
3195 prefXml.addTextElementToData(PREF_XML_BGCOLOR_FIELD, bgcolor);
3196 prefXml.addTextElementToData(PREF_XML_DBCOLOR_FIELD, dbcolor);
3197 prefXml.addTextElementToData(PREF_XML_WINCOLOR_FIELD, wincolor);
3198 prefXml.addTextElementToData(PREF_XML_LAYOUT_FIELD, layout);
3199 prefXml.addTextElementToData(PREF_XML_ALIAS_LAYOUT_FIELD, aliaslayout);
3204 if(!isAdminForGroup(permissionMap))
3208 fn = (std::string)WEB_LOGIN_DB_PATH + (std::string)USERS_PREFERENCES_PATH +
3209 (std::string)SYSTEM_PREFERENCES_PREFIX +
"." +
3210 (std::string)USERS_PREFERENCES_FILETYPE;
3213 sysPrefXml.addTextElementToData(PREF_XML_SYSLAYOUT_FIELD, syslayout);
3214 sysPrefXml.addTextElementToData(PREF_XML_SYSALIAS_LAYOUT_FIELD, sysaliaslayout);
3226 std::map<std::string , WebUsers::permissionLevel_t> permissionMap =
3232 __COUTV__(actingUser);
3234 __COUTV__(usersUsernameWithLock_);
3236 __COUTV__(username);
3237 __COUTV__(isUserActive);
3240 (isUserActive || !WebUsers::CareAboutCookieCodes_))
3242 if(!WebUsers::CareAboutCookieCodes_ && !isUserActive &&
3244 DEFAULT_ADMIN_USERNAME)
3247 <<
"User '" << actingUser
3248 <<
"' tried to lock for a user other than admin in wiz mode. Not allowed."
3252 else if(!isAdminForGroup(permissionMap) &&
3253 actingUser != username)
3255 __COUT_ERR__ <<
"A non-admin user '" << actingUser
3256 <<
"' tried to lock for a user other than self. Not allowed."
3260 usersUsernameWithLock_ = username;
3262 else if(!lock && usersUsernameWithLock_ == username)
3263 usersUsernameWithLock_ =
"";
3267 __COUT_ERR__ <<
"User '" << username <<
"' is inactive." << __E__;
3268 __COUT_ERR__ <<
"Failed to lock for user '" << username <<
".'" << __E__;
3272 __COUT_INFO__ <<
"User '" << username <<
"' has locked out the system!" << __E__;
3276 std::string securityFileName = USER_WITH_LOCK_FILE;
3277 FILE* fp = fopen(securityFileName.c_str(),
"w");
3280 __COUT_INFO__ <<
"USER_WITH_LOCK_FILE " << USER_WITH_LOCK_FILE
3281 <<
" not found. Ignoring." << __E__;
3285 fprintf(fp,
"%s", usersUsernameWithLock_.c_str());
3296 const std::string& username,
3297 const std::string& displayname,
3298 const std::string& email,
3299 const std::string& permissions)
3301 std::map<std::string , WebUsers::permissionLevel_t> permissionMap =
3303 if(!isAdminForGroup(permissionMap))
3306 __SS__ <<
"Only admins can modify user settings." << __E__;
3310 uint64_t i = searchUsersDatabaseForUserId(actingUid);
3311 uint64_t modi = searchUsersDatabaseForUsername(username);
3316 __COUT_INFO__ <<
"Admin password reset." << __E__;
3317 Users_[modi].setModifier(Users_[i].username_);
3318 Users_[modi].salt_ =
"";
3319 Users_[modi].loginFailureCount_ = 0;
3320 saveDatabaseToFile(DB_USERS);
3323 __SS__ <<
"Cannot modify first user" << __E__;
3327 if(username.length() < USERNAME_LENGTH)
3329 __SS__ <<
"Invalid Username, must be length " << USERNAME_LENGTH << __E__;
3332 if(displayname.length() < DISPLAY_NAME_LENGTH)
3334 __SS__ <<
"Invalid Display Name; must be length " << DISPLAY_NAME_LENGTH << __E__;
3338 __COUT__ <<
"Input Permissions: " << permissions << __E__;
3339 std::map<std::string , WebUsers::permissionLevel_t> newPermissionsMap;
3343 case MOD_TYPE_UPDATE:
3345 __COUT__ <<
"MOD_TYPE_UPDATE " << username <<
" := " << permissions << __E__;
3347 if(modi == NOT_FOUND_IN_DATABASE)
3349 __SS__ <<
"User not found!? Should not happen." << __E__;
3355 for(uint64_t i = 0; i < Users_.size(); ++i)
3358 else if(Users_[i].displayName_ == displayname)
3360 __SS__ <<
"Display Name '" << displayname
3361 <<
"' already exists! Please choose a unique display name."
3367 Users_[modi].displayName_ = displayname;
3368 Users_[modi].email_ = email;
3372 bool wasInactive = isInactiveForGroup(Users_[modi].permissions_);
3375 if(newPermissionsMap.size() == 0)
3376 Users_[modi].permissions_[WebUsers::DEFAULT_USER_GROUP] =
3377 std::atoi(permissions.c_str());
3378 else if(newPermissionsMap.size() == 1 &&
3379 newPermissionsMap.find(WebUsers::DEFAULT_USER_GROUP) ==
3380 newPermissionsMap.end())
3382 if(newPermissionsMap.begin()->first ==
"")
3383 Users_[modi].permissions_[WebUsers::DEFAULT_USER_GROUP] =
3384 newPermissionsMap.begin()->second;
3387 newPermissionsMap[WebUsers::DEFAULT_USER_GROUP] =
3388 newPermissionsMap.begin()->second;
3389 Users_[modi].permissions_ = newPermissionsMap;
3393 Users_[modi].permissions_ = newPermissionsMap;
3398 !isInactiveForGroup(Users_[modi].permissions_))
3400 __COUT__ <<
"Reactivating " << username << __E__;
3401 Users_[modi].loginFailureCount_ = 0;
3402 Users_[modi].salt_ =
"";
3408 if(i == NOT_FOUND_IN_DATABASE)
3410 __SS__ <<
"Master User not found!? Should not happen." << __E__;
3413 Users_[modi].setModifier(Users_[i].username_);
3419 __COUT__ <<
"MOD_TYPE_ADD " << username <<
" - " << displayname << __E__;
3424 if(i == NOT_FOUND_IN_DATABASE)
3426 __SS__ <<
"Master User not found!? Should not happen." << __E__;
3429 Users_.back().setModifier(Users_[i].username_);
3432 if(permissions.size())
3435 actingUid, MOD_TYPE_UPDATE, username, displayname, email, permissions);
3439 case MOD_TYPE_DELETE:
3440 __COUT__ <<
"MOD_TYPE_DELETE " << username <<
" - " << displayname << __E__;
3441 deleteAccount(username, displayname);
3444 __SS__ <<
"Undefined command - do nothing " << username << __E__;
3448 saveDatabaseToFile(DB_USERS);
3449 loadSecuritySelection();
3456 std::set<unsigned int> activeUserIndices;
3457 for(uint64_t i = 0; i < ActiveSessions_.size(); ++i)
3458 activeUserIndices.emplace(
3459 searchUsersDatabaseForUserId(ActiveSessions_[i].userId_));
3460 return activeUserIndices.size();
3468 std::set<unsigned int> activeUserIndices;
3469 for(uint64_t i = 0; i < ActiveSessions_.size(); ++i)
3470 activeUserIndices.emplace(
3471 searchUsersDatabaseForUserId(ActiveSessions_[i].userId_));
3473 std::string activeUsersString =
"";
3474 bool addComma =
false;
3475 for(
const auto& i : activeUserIndices)
3477 if(i >= Users_.size())
3481 activeUsersString +=
",";
3485 activeUsersString += Users_[i].displayName_;
3487 if(activeUserIndices.size() == 0 &&
3489 WebUsers::SECURITY_TYPE_NONE)
3490 activeUsersString += WebUsers::DEFAULT_ADMIN_DISPLAY_NAME;
3492 __COUTVS__(20, activeUsersString);
3493 return activeUsersString;
3501 uint64_t uid = searchUsersDatabaseForUsername(DEFAULT_ADMIN_USERNAME);
3508 void WebUsers::loadUserWithLock()
3510 char username[300] =
"";
3512 std::string securityFileName = USER_WITH_LOCK_FILE;
3513 FILE* fp = fopen(securityFileName.c_str(),
"r");
3516 __COUT_INFO__ <<
"USER_WITH_LOCK_FILE " << USER_WITH_LOCK_FILE
3517 <<
" not found. Defaulting to admin lock." << __E__;
3520 sprintf(username,
"%s", DEFAULT_ADMIN_USERNAME.c_str());
3524 fgets(username, 300, fp);
3531 __COUT__ <<
"Attempting to load username with lock: " << username << __E__;
3533 if(strlen(username) == 0)
3535 __COUT_INFO__ <<
"Loaded state for user-with-lock is unlocked." << __E__;
3539 uint64_t i = searchUsersDatabaseForUsername(username);
3540 if(i == NOT_FOUND_IN_DATABASE)
3542 __COUT_INFO__ <<
"username " << username <<
" not found in database. Ignoring."
3546 __COUT__ <<
"Setting lock" << __E__;
3554 const std::string& message)
3563 const std::string& subject,
3564 const std::string& message,
3567 std::vector<std::string> targetUsers;
3577 const std::string& subject,
3578 const std::string& message,
3581 systemMessageCleanup();
3583 std::string fullMessage = StringMacros::encodeURIComponent(
3584 (subject ==
"" ?
"" : (subject +
": ")) + message);
3587 std::cout << __COUT_HDR_FL__ <<
"addSystemMessage() fullMessage: " << fullMessage
3591 std::set<std::string> targetEmails;
3593 for(
const auto& targetUser : targetUsers)
3597 if(targetUser ==
"" || (targetUser !=
"*" && targetUser.size() < 3))
3599 __COUT__ <<
"Illegal username '" << targetUser <<
"'" << __E__;
3602 __COUTV__(targetUser);
3606 if(doEmail && targetUser ==
"*")
3609 for(
const auto& user : Users_)
3611 if(user.email_.size() > 5 &&
3612 user.email_.find(
'@') != std::string::npos &&
3613 user.email_.find(
'.') != std::string::npos)
3615 __COUT__ <<
"Adding " << user.displayName_
3616 <<
" email: " << user.email_ << __E__;
3617 targetEmails.emplace(user.email_);
3622 else if(targetUser.find(
':') != std::string::npos)
3625 __COUT__ <<
"Treating as group email target: " << targetUser << __E__;
3627 std::map<std::string, WebUsers::permissionLevel_t> targetGroupMap;
3634 if(targetGroupMap.size() == 1)
3639 for(
const auto& user : Users_)
3641 WebUsers::permissionLevel_t userLevel =
3643 targetGroupMap.begin()->first);
3647 __COUTV__((
int)userLevel);
3648 __COUTV__(targetGroupMap.begin()->first);
3650 if(userLevel != WebUsers::PERMISSION_LEVEL_INACTIVE &&
3651 userLevel >= targetGroupMap.begin()->second &&
3652 user.email_.size() > 5 &&
3653 user.email_.find(
'@') != std::string::npos &&
3654 user.email_.find(
'.') != std::string::npos)
3658 targetEmails.emplace(user.email_);
3659 __COUT__ <<
"Adding " << user.displayName_
3660 <<
" email: " << user.email_ << __E__;
3662 addSystemMessageToMap(user.displayName_, fullMessage);
3667 __COUT__ <<
"target Group Map from '" << targetUser <<
"' is empty."
3675 addSystemMessageToMap(targetUser, fullMessage);
3679 for(
const auto& user : Users_)
3681 if(user.displayName_ == targetUser)
3683 if(user.email_.size() > 5 &&
3684 user.email_.find(
'@') != std::string::npos &&
3685 user.email_.find(
'.') != std::string::npos)
3687 targetEmails.emplace(user.email_);
3688 __COUT__ <<
"Adding " << user.displayName_
3689 <<
" email: " << user.email_ << __E__;
3698 __COUTV__(targetEmails.size());
3700 if(doEmail && targetEmails.size())
3704 std::string toList =
"";
3705 bool addComma =
false;
3706 for(
const auto& email : targetEmails)
3715 std::string filename = (std::string)WEB_LOGIN_DB_PATH +
3716 (std::string)USERS_DB_PATH +
"/.tmp_email.txt";
3717 FILE* fp = fopen(filename.c_str(),
"w");
3720 __SS__ <<
"Could not open email file: " << filename << __E__;
3730 fprintf(fp,
"To: %s\n", toList.c_str());
3731 fprintf(fp,
"Subject: %s\n", subject.c_str());
3732 fprintf(fp,
"Content-Type: text/html\n");
3733 fprintf(fp,
"\n<html><pre>%s</pre></html>", message.c_str());
3739 __COUT_WARN__ <<
"Do email was attempted, but no target users had email "
3740 "addresses specified!"
3749 void WebUsers::addSystemMessageToMap(
const std::string& targetUser,
3750 const std::string& fullMessage)
3753 std::lock_guard<std::mutex> lock(systemMessageLock_);
3755 __COUT__ <<
"Before number of users with system messages: " << systemMessages_.size()
3756 <<
", first user has "
3757 << (systemMessages_.size() ? systemMessages_.begin()->second.size() : 0)
3758 <<
" messages." << __E__;
3760 auto it = systemMessages_.find(targetUser);
3763 if(it != systemMessages_.end() && it->second.size() &&
3764 it->second[it->second.size() - 1].message_ == fullMessage)
3767 if(it == systemMessages_.end())
3769 systemMessages_.emplace(
3770 std::pair<std::string , std::vector<SystemMessage>>(
3771 targetUser, std::vector<SystemMessage>({SystemMessage(fullMessage)})));
3772 __COUTT__ << targetUser <<
" Current System Messages count = " << 1 << __E__;
3777 it->second.push_back(SystemMessage(fullMessage));
3778 __COUTT__ << it->first <<
" Current System Messages count = " << it->second.size()
3782 __COUT__ <<
"After number of users with system messages: " << systemMessages_.size()
3783 <<
", first user has "
3784 << (systemMessages_.size() ? systemMessages_.begin()->second.size() : 0)
3785 <<
" messages." << __E__;
3794 std::lock_guard<std::mutex> lock(systemMessageLock_);
3796 __COUTT__ <<
"GetLast number of users with system messages: "
3797 << systemMessages_.size() <<
", first user has "
3798 << (systemMessages_.size() ? systemMessages_.begin()->second.size() : 0)
3799 <<
" messages." << __E__;
3801 auto it = systemMessages_.find(
"*");
3802 if(it == systemMessages_.end() || it->second.size() == 0)
3803 return std::make_pair(
"", 0);
3805 return std::make_pair(it->second.back().message_, it->second.back().creationTime_);
3814 std::string retStr =
"";
3817 std::lock_guard<std::mutex> lock(systemMessageLock_);
3819 for(
auto& userSysMessages : systemMessages_)
3821 for(
auto& userSysMessage : userSysMessages.second)
3823 if(userSysMessage.deliveredRemote_)
3828 retStr += userSysMessages.first;
3829 retStr +=
"|" + std::to_string(userSysMessage.creationTime_);
3830 retStr +=
"|" + userSysMessage.message_;
3831 userSysMessage.deliveredRemote_ =
true;
3846 __COUTS__(20) <<
"Current System Messages: " << targetUser << __E__;
3847 std::string retStr =
"";
3853 std::lock_guard<std::mutex> lock(systemMessageLock_);
3855 __COUTS__(20) <<
"Number of users with system messages: "
3856 << systemMessages_.size() << __E__;
3859 auto it = systemMessages_.find(
"*");
3860 for(uint64_t i = 0; it != systemMessages_.end() && i < it->second.size(); ++i)
3865 sprintf(tmp,
"%lu", it->second[i].creationTime_);
3866 retStr += std::string(tmp) +
"|" + it->second[i].message_;
3872 __COUTVS__(20, targetUser);
3873 it = systemMessages_.find(targetUser);
3876 for(
auto systemMessagePair : systemMessages_)
3877 __COUTS__(20) << systemMessagePair.first <<
" "
3878 << systemMessagePair.second.size() <<
" "
3879 << (systemMessagePair.second.size()
3880 ? systemMessagePair.second[0].message_
3884 if(it != systemMessages_.end())
3886 __COUTS__(20) <<
"Message count: " << it->second.size() <<
", Last Message: "
3887 << (it->second.size() ? it->second.back().message_ :
"")
3891 for(uint64_t i = 0; it != systemMessages_.end() && i < it->second.size(); ++i)
3896 sprintf(tmp,
"%lu", it->second[i].creationTime_);
3897 retStr += std::string(tmp) +
"|" + it->second[i].message_;
3899 it->second[i].delivered_ =
true;
3904 __COUTS__(20) <<
"retStr: " << retStr << __E__;
3906 systemMessageCleanup();
3914 void WebUsers::systemMessageCleanup()
3917 std::lock_guard<std::mutex> lock(systemMessageLock_);
3919 __COUTT__ <<
"Before cleanup number of users with system messages: "
3920 << systemMessages_.size() <<
", first user has "
3921 << (systemMessages_.size() ? systemMessages_.begin()->second.size() : 0)
3922 <<
" messages." << __E__;
3923 for(
auto& userMessagesPair : systemMessages_)
3925 for(uint64_t i = 0; i < userMessagesPair.second.size(); ++i)
3926 if((userMessagesPair.first !=
"*" &&
3927 userMessagesPair.second[i].delivered_) ||
3931 __COUTT__ << userMessagesPair.first
3932 <<
" at time: " << userMessagesPair.second[i].creationTime_
3933 <<
" system messages: " << userMessagesPair.second.size()
3937 userMessagesPair.second.erase(userMessagesPair.second.begin() + i);
3941 __COUTT__ <<
"User '" << userMessagesPair.first
3942 <<
"' remaining system messages: " << userMessagesPair.second.size()
3945 __COUTT__ <<
"After cleanup number of users with system messages: "
3946 << systemMessages_.size() <<
", first user has "
3947 << (systemMessages_.size() ? systemMessages_.begin()->second.size() : 0)
3948 <<
" messages." << __E__;
3956 void WebUsers::loadSecuritySelection()
3958 std::string securityFileName = SECURITY_FILE_NAME;
3959 FILE* fp = fopen(securityFileName.c_str(),
"r");
3960 char line[100] =
"";
3962 fgets(line, 100, fp);
3966 while(i < strlen(line) && line[i] >=
'A' && line[i] <=
'z')
3970 if(strcmp(line, SECURITY_TYPE_NONE.c_str()) == 0 ||
3971 strcmp(line, SECURITY_TYPE_DIGEST_ACCESS.c_str()) == 0)
3972 securityType_ = line;
3974 securityType_ = SECURITY_TYPE_DEFAULT;
3976 __COUT__ <<
"The current security type is " << securityType_ << __E__;
3981 if(securityType_ == SECURITY_TYPE_NONE)
3982 CareAboutCookieCodes_ =
false;
3984 CareAboutCookieCodes_ =
true;
3986 __COUT__ <<
"CareAboutCookieCodes_: " << CareAboutCookieCodes_ << __E__;
3988 loadIPAddressSecurity();
3994 void WebUsers::loadIPAddressSecurity()
3996 ipAccessAccept_.clear();
3997 ipAccessReject_.clear();
3998 ipAccessBlacklist_.clear();
4000 FILE* fp = fopen((IP_ACCEPT_FILE).c_str(),
"r");
4006 while(fgets(line, 300, fp))
4010 if(len > 2 && line[len - 1] ==
'\n')
4011 line[len - 1] =
'\0';
4012 ipAccessAccept_.emplace(line);
4019 __COUTV__(ipAccessAccept_.size());
4021 fp = fopen((IP_REJECT_FILE).c_str(),
"r");
4024 while(fgets(line, 300, fp))
4028 if(len > 2 && line[len - 1] ==
'\n')
4029 line[len - 1] =
'\0';
4030 ipAccessReject_.emplace(line);
4037 __COUTV__(ipAccessReject_.size());
4039 fp = fopen((IP_BLACKLIST_FILE).c_str(),
"r");
4042 while(fgets(line, 300, fp))
4046 if(len > 2 && line[len - 1] ==
'\n')
4047 line[len - 1] =
'\0';
4048 ipAccessBlacklist_.emplace(line);
4055 __COUTV__(ipAccessBlacklist_.size());
4059 void WebUsers::NACDisplayThread(
const std::string& nac,
const std::string& user)
4070 std::this_thread::sleep_for(std::chrono::seconds(2));
4072 <<
"\n******************************************************************** "
4075 <<
"\n******************************************************************** "
4077 __COUT__ <<
"\n\nNew account code = " << nac <<
" for user: " << user <<
"\n"
4080 <<
"\n******************************************************************** "
4083 <<
"\n******************************************************************** "
4089 void WebUsers::deleteUserData()
4091 __COUT__ <<
"$$$$$$$$$$$$$$ Deleting ALL service user data... $$$$$$$$$$$$" << __E__;
4095 (
"rm -rf " + (std::string)WEB_LOGIN_DB_PATH + HASHES_DB_PATH +
"/*").c_str());
4097 (
"rm -rf " + (std::string)WEB_LOGIN_DB_PATH + USERS_DB_PATH +
"/*").c_str());
4099 (
"rm -rf " + (std::string)WEB_LOGIN_DB_PATH + USERS_LOGIN_HISTORY_PATH +
"/*")
4102 (
"rm -rf " + (std::string)WEB_LOGIN_DB_PATH + USERS_PREFERENCES_PATH +
"/*")
4104 std::system((
"rm -rf " + (std::string)WEB_LOGIN_DB_PATH + TOOLTIP_DB_PATH).c_str());
4106 std::string serviceDataPath = __ENV__(
"SERVICE_DATA_PATH");
4108 std::system((
"rm -rf " + std::string(serviceDataPath) +
"/MacroData/").c_str());
4109 std::system((
"rm -rf " + std::string(serviceDataPath) +
"/MacroHistory/").c_str());
4110 std::system((
"rm -rf " + std::string(serviceDataPath) +
"/MacroExport/").c_str());
4114 (
"rm -rf " + std::string(serviceDataPath) +
"/ConsolePreferences/").c_str());
4117 std::system((
"rm -rf " + std::string(serviceDataPath) +
"/CodeEditorData/").c_str());
4120 std::system((
"rm -rf " + std::string(serviceDataPath) +
"/OtsWizardData/").c_str());
4123 std::system((
"rm -rf " + std::string(serviceDataPath) +
"/ProgressBarData/").c_str());
4126 std::system((
"rm -rf " + std::string(serviceDataPath) +
"/RunNumber/").c_str());
4127 std::system((
"rm -rf " + std::string(serviceDataPath) +
"/RunControlData/").c_str());
4130 std::system((
"rm -rf " + std::string(serviceDataPath) +
"/VisualizerData/").c_str());
4137 std::system((
"rm -rf " + std::string(__ENV__(
"LOGBOOK_DATA_PATH")) +
"/").c_str());
4139 __COUT__ <<
"$$$$$$$$$$$$$$ Successfully deleted ALL service user data $$$$$$$$$$$$"
void copyDataChildren(HttpXmlDocument &document)
void removeDataElement(unsigned int dataChildIndex=0)
default to first child
bool loadXmlDocument(const std::string &filePath)
unsigned int getChildrenCount(xercesc::DOMElement *parent=0)
void addSystemMessage(const std::string &targetUsersCSV, const std::string &message)
const std::string & getSecurity(void)
WebUsers::getSecurity.
std::string getGenericPreference(uint64_t uid, const std::string &preferenceName, HttpXmlDocument *xmldoc=0) const
bool setUserWithLock(uint64_t actingUid, bool lock, const std::string &username)
static bool checkRequestAccess(cgicc::Cgicc &cgi, std::ostringstream *out, HttpXmlDocument *xmldoc, WebUsers::RequestUserInfo &userInfo, bool isWizardMode=false, const std::string &wizardModeSequence="")
static void silenceAllUserTooltips(const std::string &username)
size_t getActiveUserCount(void)
std::map< std::string, WebUsers::permissionLevel_t > getPermissionsForUser(uint64_t uid)
from Gateway, use public version which considers remote users
uint64_t attemptActiveSession(const std::string &uuid, std::string &jumbledUser, const std::string &jumbledPw, std::string &newAccountCode, const std::string &ip)
void setGenericPreference(uint64_t uid, const std::string &preferenceName, const std::string &preferenceValue)
std::string getAllSystemMessages(void)
void cleanupExpiredEntries(std::vector< std::string > *loggedOutUsernames=0)
uint64_t isCookieCodeActiveForLogin(const std::string &uuid, std::string &cookieCode, std::string &username)
std::string createNewLoginSession(const std::string &uuid, const std::string &ip)
std::string getActiveUsersString(void)
void createNewAccount(const std::string &username, const std::string &displayName, const std::string &email)
void modifyAccountSettings(uint64_t actingUid, uint8_t cmd_type, const std::string &username, const std::string &displayname, const std::string &email, const std::string &permissions)
WebUsers::modifyAccountSettings.
int remoteLoginVerificationPort_
Port of remote Gateway to be used for login verification.
bool isUsernameActive(const std::string &username) const
bool isUserIdActive(uint64_t uid) const
void saveActiveSessions(void)
static std::atomic< bool > remoteLoginVerificationEnabled_
true if this supervisor is under control of a remote supervisor
uint64_t getAdminUserID(void)
@ SYS_CLEANUP_WILDCARD_TIME
300 seconds
std::string getUsersUsername(uint64_t uid)
from Gateway, use public version which considers remote users
static void initializeRequestUserInfo(cgicc::Cgicc &cgi, WebUsers::RequestUserInfo &userInfo)
used by gateway and other supervisors to verify requests consistently
bool checkIpAccess(const std::string &ip)
bool xmlRequestOnGateway(cgicc::Cgicc &cgi, std::ostringstream *out, HttpXmlDocument *xmldoc, WebUsers::RequestUserInfo &userInfo)
uint64_t cookieCodeLogout(const std::string &cookieCode, bool logoutOtherUserSessions, uint64_t *uid=0, const std::string &ip="0")
std::string getSystemMessage(const std::string &targetUser)
uint64_t getActiveSessionCountForUser(uint64_t uid)
static void resetAllUserTooltips(const std::string &userNeedle="*")
WebUsers::resetAllUserTooltips.
static void tooltipSetNeverShowForUsername(const std::string &username, HttpXmlDocument *xmldoc, const std::string &srcFile, const std::string &srcFunc, const std::string &srcId, bool doNeverShow, bool temporarySilence)
void cleanupExpiredRemoteEntries(void)
std::string getUsersDisplayName(uint64_t uid)
from Gateway, use public version which considers remote users
void loadActiveSessions(void)
std::pair< std::string, time_t > getLastSystemMessage(void)
uint64_t attemptActiveSessionWithCert(const std::string &uuid, std::string &jumbledEmail, std::string &cookieCode, std::string &username, const std::string &ip)
static const std::string OTS_OWNER
defined by environment variable, e.g. experiment name
static void tooltipCheckForUsername(const std::string &username, HttpXmlDocument *xmldoc, const std::string &srcFile, const std::string &srcFunc, const std::string &srcId)
std::string remoteGatewaySelfName_
IP of remote Gateway to be used for login verification.
bool cookieCodeIsActiveForRequest(std::string &cookieCode, std::map< std::string, WebUsers::permissionLevel_t > *userPermissions=0, uint64_t *uid=0, const std::string &ip="0", bool refresh=true, bool doNotGoRemote=false, std::string *userWithLock=0, uint64_t *userSessionIndex=0)
void changeSettingsForUser(uint64_t uid, const std::string &bgcolor, const std::string &dbcolor, const std::string &wincolor, const std::string &layout, const std::string &syslayout, const std::string &aliaslayout, const std::string &sysaliaslayout)
WebUsers::changeSettingsForUser.
void insertSettingsForUser(uint64_t uid, HttpXmlDocument *xmldoc, bool includeAccounts=false)
@ PERMISSION_LEVEL_ADMIN
max permission level!
xercesc::DOMElement * addTextElementToParent(const std::string &childName, const std::string &childText, xercesc::DOMElement *parent)
void saveXmlDocument(const std::string &filePath)
void INIT_MF(const char *name)
static std::string getTimestampString(const std::string &linuxTimeInSeconds)
static void getVectorFromString(const std::string &inputString, std::vector< std::string > &listToReturn, const std::set< char > &delimiter={',', '|', '&'}, const std::set< char > &whitespace={' ', '\t', '\n', '\r'}, std::vector< char > *listOfDelimiters=0, bool decodeURIComponents=false)
static std::string exec(const char *cmd)
static std::string setToString(const std::set< T > &setToReturn, const std::string &delimeter=", ")
setToString ~
static std::string vectorToString(const std::vector< T > &setToReturn, const std::string &delimeter=", ")
vectorToString ~
static std::string mapToString(const std::map< std::string, T > &mapToReturn, const std::string &primaryDelimeter=", ", const std::string &secondaryDelimeter=": ")
static void getMapFromString(const std::string &inputString, std::map< S, T > &mapToReturn, const std::set< char > &pairPairDelimiter={',', '|', '&'}, const std::set< char > &nameValueDelimiter={'=', ':'}, const std::set< char > &whitespace={' ', '\t', '\n', '\r'})
getMapFromString ~
static bool wildCardMatch(const std::string &needle, const std::string &haystack, unsigned int *priorityIndex=0)
static std::string decodeURIComponent(const std::string &data)
static std::string stackTrace(void)
uint64_t userSessionIndex_
can use session index to track a user's session on multiple devices/browsers
const WebUsers::permissionLevel_t & getGroupPermissionLevel()
bool setGroupPermissionLevels(const std::string &groupPermissionLevelsString)
end setGroupPermissionLevels()