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__ <<
"Login attempt failed. Session uuid '" << uuid
1136 <<
"' is not found or inactive." << __E__;
1137 newAccountCode =
"1";
1139 incrementIpBlacklistCount(ip);
1141 return NOT_FOUND_IN_DATABASE;
1143 ++LoginSessions_[i].loginAttempts_;
1145 std::string user = dejumble(jumbledUser, LoginSessions_[i].id_);
1147 std::string pw = dejumble(jumbledPw, LoginSessions_[i].id_);
1150 if((i = searchUsersDatabaseForUsername(user)) == NOT_FOUND_IN_DATABASE)
1152 __COUT_ERR__ <<
"user: " << user <<
" is not found" << __E__;
1154 incrementIpBlacklistCount(ip);
1156 return NOT_FOUND_IN_DATABASE;
1159 ipBlacklistCounts_[ip] = 0;
1161 Users_[i].lastLoginAttempt_ = time(0);
1163 if(isInactiveForGroup(Users_[i].permissions_))
1165 __COUT_ERR__ <<
"User '" << user
1166 <<
"' account INACTIVE (could be due to failed logins)" << __E__;
1167 return ACCOUNT_INACTIVE;
1170 if(Users_[i].salt_ ==
"")
1172 __COUT__ <<
"First login attempt for user: " << user << __E__;
1174 if(newAccountCode != Users_[i].getNewAccountCode())
1176 __COUT__ <<
"New account code did not match: "
1177 << Users_[i].getNewAccountCode() <<
" != " << newAccountCode
1179 saveDatabaseToFile(DB_USERS);
1180 return NOT_FOUND_IN_DATABASE;
1186 while(!addToHashesDatabase(
1187 sha512(user, pw, Users_[i].salt_)))
1192 Users_[i].salt_ =
"";
1195 __COUT__ <<
"\tHash added: " << Hashes_.back().hash_ << __E__;
1199 std::string salt = Users_[i].salt_;
1201 if(searchHashesDatabaseForHash(sha512(user, pw, salt)) == NOT_FOUND_IN_DATABASE)
1203 __COUT__ <<
"Failed login for " << user <<
" with permissions "
1207 if(++Users_[i].loginFailureCount_ != (
unsigned char)-1)
1208 ++Users_[i].loginFailureCount_;
1210 if(Users_[i].loginFailureCount_ >= USERS_MAX_LOGIN_FAILURES)
1211 Users_[i].permissions_[WebUsers::DEFAULT_USER_GROUP] =
1212 WebUsers::PERMISSION_LEVEL_INACTIVE;
1214 __COUT_INFO__ <<
"User/pw for user '" << user
1215 <<
"' was not correct (Failed Attempt #"
1216 << (int)Users_[i].loginFailureCount_ <<
" of "
1217 << (
int)USERS_MAX_LOGIN_FAILURES <<
" allowed)." << __E__;
1219 __COUTV__(isInactiveForGroup(Users_[i].permissions_));
1220 if(isInactiveForGroup(Users_[i].permissions_))
1221 __COUT_INFO__ <<
"Account '" << user
1222 <<
"' has been marked inactive due to too many failed "
1223 "login attempts (Failed Attempt #"
1224 << (int)Users_[i].loginFailureCount_
1225 <<
")! Note only admins can reactivate accounts." << __E__;
1227 saveDatabaseToFile(DB_USERS);
1228 return NOT_FOUND_IN_DATABASE;
1232 __COUT_INFO__ <<
"Login successful for: " << user << __E__;
1234 Users_[i].loginFailureCount_ = 0;
1237 for(
int h = 0; h < 2; ++h)
1239 std::string fn = (std::string)WEB_LOGIN_DB_PATH +
1240 (std::string)USERS_LOGIN_HISTORY_PATH +
1241 (h ? USERS_GLOBAL_HISTORY_FILE : Users_[i].username_) +
"." +
1242 (std::string)USERS_LOGIN_HISTORY_FILETYPE;
1249 (h ? USERS_GLOBAL_HISTORY_SIZE : USERS_LOGIN_HISTORY_SIZE))
1253 __COUT__ <<
"No previous login history found." << __E__;
1259 "Time=%lu Username=%s Permissions=%s UID=%lu",
1261 Users_[i].username_.c_str(),
1266 "Time=%lu displayName=%s Permissions=%s UID=%lu",
1268 Users_[i].displayName_.c_str(),
1271 histXml.addTextElementToData(PREF_XML_LOGIN_HISTORY_FIELD, entryStr);
1278 saveDatabaseToFile(DB_USERS);
1279 jumbledUser = Users_[i].displayName_;
1280 newAccountCode = createNewActiveSession(Users_[i].userId_,
1283 __COUTTV__(ActiveSessions_.size());
1285 if(ActiveSessions_.size() == 1)
1287 __COUT__ <<
"Attempting to auto-lock for first login user '"
1288 << Users_[i].username_ <<
"'... " << __E__;
1292 return Users_[i].userId_;
1303 std::string& cookieCode,
1305 const std::string& ip)
1309 __COUT_ERR__ <<
"rejected ip: " << ip << __E__;
1310 return NOT_FOUND_IN_DATABASE;
1315 if(!CareAboutCookieCodes_)
1319 cookieCode = genCookieCode();
1325 __COUT__ <<
"Rejecting cert logon with blank fingerprint" << __E__;
1327 incrementIpBlacklistCount(ip);
1329 return NOT_FOUND_IN_DATABASE;
1335 if((i = searchLoginSessionDatabaseForUUID(uuid)) == NOT_FOUND_IN_DATABASE)
1337 __COUT__ <<
"uuid: " << uuid <<
" is not found" << __E__;
1340 incrementIpBlacklistCount(ip);
1342 return NOT_FOUND_IN_DATABASE;
1344 ++LoginSessions_[i].loginAttempts_;
1346 email = getUserEmailFromFingerprint(email);
1347 __COUT__ <<
"DejumbledEmail = " << email << __E__;
1350 __COUT__ <<
"Rejecting logon with unknown fingerprint" << __E__;
1352 incrementIpBlacklistCount(ip);
1354 return NOT_FOUND_IN_DATABASE;
1358 if((i = searchUsersDatabaseForUserEmail(email)) == NOT_FOUND_IN_DATABASE)
1360 __COUT__ <<
"email: " << email <<
" is not found" << __E__;
1362 incrementIpBlacklistCount(ip);
1364 return NOT_FOUND_IN_DATABASE;
1367 ipBlacklistCounts_[ip] = 0;
1371 Users_[i].lastLoginAttempt_ = time(0);
1372 if(isInactiveForGroup(Users_[i].permissions_))
1374 __COUT__ <<
"User '" << user
1375 <<
"' account INACTIVE (could be due to failed logins)." << __E__;
1376 return NOT_FOUND_IN_DATABASE;
1379 if(Users_[i].salt_ ==
"")
1381 return NOT_FOUND_IN_DATABASE;
1384 __COUT__ <<
"Login successful for: " << user << __E__;
1386 Users_[i].loginFailureCount_ = 0;
1389 for(
int h = 0; h < 2; ++h)
1391 std::string fn = (std::string)WEB_LOGIN_DB_PATH +
1392 (std::string)USERS_LOGIN_HISTORY_PATH +
1393 (h ? USERS_GLOBAL_HISTORY_FILE : Users_[i].username_) +
"." +
1394 (std::string)USERS_LOGIN_HISTORY_FILETYPE;
1401 (h ? USERS_GLOBAL_HISTORY_SIZE : USERS_LOGIN_HISTORY_SIZE))
1405 __COUT__ <<
"No previous login history found." << __E__;
1411 "Time=%lu Username=%s Permissions=%s UID=%lu",
1413 Users_[i].username_.c_str(),
1418 "Time=%lu displayName=%s Permissions=%s UID=%lu",
1420 Users_[i].displayName_.c_str(),
1423 histXml.addTextElementToData(PREF_XML_LOGIN_HISTORY_FIELD, entryStr);
1430 saveDatabaseToFile(DB_USERS);
1431 email = Users_[i].displayName_;
1432 cookieCode = createNewActiveSession(Users_[i].userId_,
1434 return Users_[i].userId_;
1440 uint64_t WebUsers::searchActiveSessionDatabaseForCookie(
1441 const std::string& cookieCode)
const
1444 for(; i < ActiveSessions_.size(); ++i)
1445 if(ActiveSessions_[i].cookieCode_ == cookieCode)
1447 return (i == ActiveSessions_.size()) ? NOT_FOUND_IN_DATABASE : i;
1465 uint64_t WebUsers::checkRemoteLoginVerification(std::string& cookieCode,
1468 const std::string& ip)
1470 __COUTVS__(2, cookieCode);
1471 remoteLoginVerificationEnabledBlackoutTime_ = 0;
1472 if(!remoteLoginVerificationSocket_)
1477 <<
"Illegal remote login verification port found in remote destination "
1479 <<
". Please check remote settings." << __E__;
1482 __COUT_INFO__ <<
"Instantiating Remote Gateway login verification socket! "
1483 "Validation requests will go to "
1487 remoteLoginVerificationSocket_ =
1488 std::make_unique<TransceiverSocket>(remoteLoginVerificationIP_);
1489 remoteLoginVerificationSocket_->initialize();
1491 remoteLoginVerificationSocketTarget_ = std::make_unique<Socket>(
1497 auto lockHandling = [
this, refresh](std::string username,
1498 uint64_t verifiedUserId) -> uint64_t {
1499 __COUTT__ <<
"lambda lockHandling()" << __E__;
1500 __COUTTV__(ActiveSessions_.size());
1501 __COUTTV__(RemoteSessions_.size());
1503 if((!CareAboutCookieCodes_)
1505 (usersUsernameWithLock_ == DEFAULT_ADMIN_USERNAME ||
1506 usersUsernameWithLock_ ==
"") &&
1507 usersUsernameWithLock_ != username)
1509 __COUT_INFO__ <<
"Overriding local user-with-lock '" << usersUsernameWithLock_
1510 <<
"' with remote user-with-lock 'Remote:" << username <<
"'"
1512 usersUsernameWithLock_ =
1516 getUserWithLock() +
" has locked REMOTE ots (overriding anonymous " +
1517 DEFAULT_ADMIN_USERNAME +
" user).");
1519 else if((ActiveSessions_.size() == 0 &&
1520 RemoteSessions_.size() == 1)
1521 && refresh && (usersUsernameWithLock_ ==
"") &&
1522 usersUsernameWithLock_ != username)
1524 __COUT_INFO__ <<
"Overriding local user-with-lock '" << usersUsernameWithLock_
1525 <<
"' with remote user-with-lock 'Remote:" << username <<
"'"
1527 usersUsernameWithLock_ =
1531 getUserWithLock() +
" has locked REMOTE ots (which was unlocked).");
1533 return verifiedUserId;
1538 __COUTTV__(cookieCode);
1539 __COUTTV__(RemoteSessions_.size());
1540 auto it = RemoteSessions_.find(cookieCode);
1541 if(it != RemoteSessions_.end())
1543 __COUTT__ <<
"cookieCode still active locally!" << __E__;
1544 __COUTV__(it->second.userId_);
1545 uint64_t j = searchUsersDatabaseForUserId(it->second.userId_);
1546 if(j == NOT_FOUND_IN_DATABASE)
1548 __SS__ <<
"Could not find cache entry for remote user ID '"
1549 << it->second.userId_ <<
"' - notify admins." << __E__;
1552 __COUTV__(Users_[j].username_);
1555 return lockHandling(Users_[j].username_, it->second.userId_);
1560 __COUTTV__(doNotGoRemote);
1562 return NOT_FOUND_IN_DATABASE;
1573 std::string request =
"loginVerify," + cookieCode +
"," + (refresh ?
"1" :
"0") +
1579 std::string requestResponseString = remoteLoginVerificationSocket_->sendAndReceive(
1580 *remoteLoginVerificationSocketTarget_, request, 10 );
1581 __COUTV__(requestResponseString);
1584 std::vector<std::string> rxParams =
1588 if(rxParams.size() != 6)
1590 __COUT__ <<
"Remote login response indicates rejected: " << rxParams.size()
1592 return NOT_FOUND_IN_DATABASE;
1604 __COUTTV__(rxParams[2]);
1605 __COUTTV__(usersUsernameWithLock_);
1608 std::string username = rxParams[3];
1609 __COUTTV__(username);
1610 uint64_t j = searchUsersDatabaseForUsername(username);
1611 if(j == NOT_FOUND_IN_DATABASE)
1613 __COUT_INFO__ <<
"Creating User entry for remote user '" << username
1614 <<
"' in local user list to track user preferences." << __E__;
1618 j = Users_.size() - 1;
1621 Users_[j].lastLoginAttempt_ = time(0);
1622 Users_[j].setModifier(
"REMOTE_GATEWAY");
1627 .permissions_.clear();
1629 Users_[j].permissions_);
1631 __COUTV__(Users_[j].username_);
1632 __COUTV__(Users_[j].userId_);
1636 cookieCode = rxParams[0];
1637 __COUTTV__(cookieCode);
1638 ActiveSession& newRemoteSession =
1639 RemoteSessions_[cookieCode];
1640 newRemoteSession.cookieCode_ = cookieCode;
1641 newRemoteSession.ip_ = ip;
1642 newRemoteSession.userId_ = Users_[j].userId_;
1643 sscanf(rxParams[5].c_str(),
"%lu", &newRemoteSession.sessionIndex_);
1644 newRemoteSession.startTime_ = time(0);
1647 return lockHandling(Users_[j].username_, Users_[j].userId_);
1656 if((u = searchUsersDatabaseForUsername(username)) == NOT_FOUND_IN_DATABASE)
1666 __COUTT__ <<
"isUserIdActive? " << uid << __E__;
1669 for(
const auto& remoteSession : RemoteSessions_)
1670 if(remoteSession.second.userId_ == uid)
1675 for(; i < ActiveSessions_.size(); ++i)
1676 if(ActiveSessions_[i].userId_ == uid)
1684 uint64_t WebUsers::searchUsersDatabaseForUsername(
const std::string& username)
const
1687 for(; i < Users_.size(); ++i)
1688 if(Users_[i].username_ == username)
1690 return (i == Users_.size()) ? NOT_FOUND_IN_DATABASE : i;
1696 uint64_t WebUsers::searchUsersDatabaseForDisplayName(
const std::string& displayName)
const
1699 for(; i < Users_.size(); ++i)
1700 if(Users_[i].displayName_ == displayName)
1702 return (i == Users_.size()) ? NOT_FOUND_IN_DATABASE : i;
1708 uint64_t WebUsers::searchUsersDatabaseForUserEmail(
const std::string& useremail)
const
1711 for(; i < Users_.size(); ++i)
1712 if(Users_[i].email_ == useremail)
1714 return (i == Users_.size()) ? NOT_FOUND_IN_DATABASE : i;
1720 uint64_t WebUsers::searchUsersDatabaseForUserId(uint64_t uid)
const
1723 for(; i < Users_.size(); ++i)
1724 if(Users_[i].userId_ == uid)
1726 return (i == Users_.size()) ? NOT_FOUND_IN_DATABASE : i;
1732 uint64_t WebUsers::searchLoginSessionDatabaseForUUID(
const std::string& uuid)
const
1735 for(; i < LoginSessions_.size(); ++i)
1736 if(LoginSessions_[i].uuid_ == uuid)
1738 return (i == LoginSessions_.size()) ? NOT_FOUND_IN_DATABASE : i;
1744 uint64_t WebUsers::searchHashesDatabaseForHash(
const std::string& hash)
1748 for(; i < Hashes_.size(); ++i)
1749 if(Hashes_[i].hash_ == hash)
1754 if(i < Hashes_.size())
1755 Hashes_[i].accessTime_ =
1756 ((time(0) + (rand() % 2 ? 1 : -1) * (rand() % 30 * 24 * 60 * 60)) &
1757 0x0FFFFFFFFFE000000);
1762 return (i == Hashes_.size()) ? NOT_FOUND_IN_DATABASE : i;
1769 bool WebUsers::addToHashesDatabase(
const std::string& hash)
1771 if(searchHashesDatabaseForHash(hash) != NOT_FOUND_IN_DATABASE)
1773 __COUT__ <<
"Hash collision: " << hash << __E__;
1776 Hashes_.push_back(Hash());
1777 Hashes_.back().hash_ = hash;
1778 Hashes_.back().accessTime_ =
1779 ((time(0) + (rand() % 2 ? 1 : -1) * (rand() % 30 * 24 * 60 * 60)) &
1780 0x0FFFFFFFFFE000000);
1783 return saveDatabaseToFile(DB_HASHES);
1788 std::string WebUsers::genCookieCode()
1791 std::string cc =
"";
1792 for(uint32_t i = 0; i < COOKIE_CODE_LENGTH / 2; ++i)
1794 intToHexStr(rand(), hexStr);
1804 std::string WebUsers::createNewActiveSession(uint64_t uid,
1805 const std::string& ip,
1809 ActiveSessions_.push_back(ActiveSession());
1810 ActiveSessions_.back().cookieCode_ = genCookieCode();
1811 ActiveSessions_.back().ip_ = ip;
1812 ActiveSessions_.back().userId_ = uid;
1813 ActiveSessions_.back().startTime_ = time(0);
1816 ActiveSessions_.back().sessionIndex_ = asIndex;
1821 for(uint64_t j = 0; j < ActiveSessions_.size(); ++j)
1822 if(ActiveSessions_[j].userId_ == uid &&
1823 max < ActiveSessions_[j].sessionIndex_)
1824 max = ActiveSessions_[j].sessionIndex_;
1826 ActiveSessions_.back().sessionIndex_ = (max ? max + 1 : 1);
1829 return ActiveSessions_.back().cookieCode_;
1856 std::string WebUsers::refreshCookieCode(
unsigned int i,
bool enableRefresh)
1859 for(uint64_t j = ActiveSessions_.size() - 1; j != (uint64_t)-1;
1861 if(ActiveSessions_[j].userId_ == ActiveSessions_[i].userId_ &&
1862 ActiveSessions_[j].sessionIndex_ ==
1863 ActiveSessions_[i].sessionIndex_)
1868 if(enableRefresh && (time(0) - ActiveSessions_[j].startTime_ >
1869 ACTIVE_SESSION_EXPIRATION_TIME / 2))
1873 ActiveSessions_[j].startTime_ =
1874 time(0) - ACTIVE_SESSION_EXPIRATION_TIME +
1875 ACTIVE_SESSION_COOKIE_OVERLAP_TIME;
1881 return createNewActiveSession(ActiveSessions_[i].userId_,
1882 ActiveSessions_[i].ip_,
1883 ActiveSessions_[i].sessionIndex_);
1886 return ActiveSessions_[j].cookieCode_;
1898 std::string& cookieCode,
1899 std::string& username)
1901 if(!CareAboutCookieCodes_)
1908 if(!ActiveSessions_.size())
1909 return NOT_FOUND_IN_DATABASE;
1914 if((i = searchLoginSessionDatabaseForUUID(uuid)) == NOT_FOUND_IN_DATABASE)
1916 __COUT__ <<
"uuid not found: " << uuid << __E__;
1917 return NOT_FOUND_IN_DATABASE;
1921 dejumble(username, LoginSessions_[i].id_);
1924 if((i = searchActiveSessionDatabaseForCookie(cookieCode)) == NOT_FOUND_IN_DATABASE)
1926 __COUT__ <<
"Cookie code not found" << __E__;
1927 return NOT_FOUND_IN_DATABASE;
1931 if((j = searchUsersDatabaseForUserId(ActiveSessions_[i].userId_)) ==
1932 NOT_FOUND_IN_DATABASE)
1934 __COUT__ <<
"User ID not found" << __E__;
1935 return NOT_FOUND_IN_DATABASE;
1939 if(Users_[j].username_ != username)
1941 __COUT__ <<
"cookieCode: " << cookieCode <<
" was.." << __E__;
1942 __COUT__ <<
"username: " << username <<
" is not found" << __E__;
1943 return NOT_FOUND_IN_DATABASE;
1946 username = Users_[j].displayName_;
1947 cookieCode = refreshCookieCode(i);
1948 return Users_[j].userId_;
1957 std::vector<uint64_t> uniqueAsi;
1960 for(i = 0; i < ActiveSessions_.size(); ++i)
1961 if(ActiveSessions_[i].userId_ == uid)
1966 for(j = 0; j < uniqueAsi.size(); ++j)
1967 if(uniqueAsi[j] == ActiveSessions_[i].sessionIndex_)
1974 uniqueAsi.push_back(ActiveSessions_[i].sessionIndex_);
1977 __COUT__ <<
"Found " << uniqueAsi.size() <<
" active sessions for uid " << uid
1980 return uniqueAsi.size();
1996 if(time(0) > ipSecurityLastLoadTime_ +
1999 ipSecurityLastLoadTime_ = time(0);
2000 loadIPAddressSecurity();
2003 for(
const auto& acceptIp : ipAccessAccept_)
2006 __COUTV__(acceptIp);
2009 for(
const auto& rejectIp : ipAccessReject_)
2012 __COUTV__(rejectIp);
2015 for(
const auto& blacklistIp : ipAccessBlacklist_)
2018 __COUTV__(blacklistIp);
2028 void WebUsers::incrementIpBlacklistCount(
const std::string& ip)
2030 if(ipAccessBlacklist_.find(ip) != ipAccessBlacklist_.end())
2034 auto it = ipBlacklistCounts_.find(ip);
2035 if(it == ipBlacklistCounts_.end())
2037 __COUT__ <<
"First error for ip '" << ip <<
"'" << __E__;
2038 ipBlacklistCounts_[ip] = 1;
2044 if(it->second >= IP_BLACKLIST_COUNT_THRESHOLD)
2046 __COUT_WARN__ <<
"Adding IP '" << ip <<
"' to blacklist!" << __E__;
2048 ipAccessBlacklist_.emplace(ip);
2049 __COUTV__(ipAccessBlacklist_.size());
2052 FILE* fp = fopen((IP_BLACKLIST_FILE).c_str(),
"a");
2055 __COUT_ERR__ <<
"IP black list file '" << IP_BLACKLIST_FILE
2056 <<
"' could not be opened." << __E__;
2059 fprintf(fp,
"%s\n", ip.c_str());
2070 if((i = searchUsersDatabaseForUserId(uid)) == NOT_FOUND_IN_DATABASE)
2072 return Users_[i].displayName_;
2080 if((i = searchUsersDatabaseForUserId(uid)) == NOT_FOUND_IN_DATABASE)
2082 return Users_[i].username_;
2097 bool logoutOtherUserSessions,
2099 const std::string& ip)
2104 if((i = searchActiveSessionDatabaseForCookie(cookieCode)) == NOT_FOUND_IN_DATABASE)
2106 __COUT__ <<
"Cookie code not found" << __E__;
2108 incrementIpBlacklistCount(ip);
2110 return NOT_FOUND_IN_DATABASE;
2113 ipBlacklistCounts_[ip] = 0;
2116 if(ActiveSessions_[i].ip_ != ip)
2118 __COUT__ <<
"IP does not match active session" << __E__;
2119 return NOT_FOUND_IN_DATABASE;
2128 uint64_t asi = ActiveSessions_[i].sessionIndex_;
2129 uint64_t uid = ActiveSessions_[i].userId_;
2132 uint64_t logoutCount = 0;
2135 while(i < ActiveSessions_.size())
2137 if((logoutOtherUserSessions && ActiveSessions_[i].userId_ == uid &&
2138 ActiveSessions_[i].sessionIndex_ != asi) ||
2139 (!logoutOtherUserSessions && ActiveSessions_[i].userId_ == uid &&
2140 ActiveSessions_[i].sessionIndex_ == asi))
2142 __COUT__ <<
"Logging out of active session " << ActiveSessions_[i].userId_
2143 <<
"-" << ActiveSessions_[i].sessionIndex_ << __E__;
2144 ActiveSessions_.erase(ActiveSessions_.begin() + i);
2151 __COUT__ <<
"Found and removed active session count = " << logoutCount << __E__;
2170 std::string& cookieCode,
2171 std::map<std::string /*groupName*/, WebUsers::permissionLevel_t>* userPermissions,
2173 const std::string& ip,
2176 std::string* userWithLock,
2177 uint64_t* userSessionIndex)
2185 __COUT_ERR__ <<
"User IP rejected." << __E__;
2186 cookieCode = REQ_NO_LOGIN_RESPONSE;
2192 uint64_t i, j, userId = NOT_FOUND_IN_DATABASE, userSession = NOT_FOUND_IN_DATABASE;
2194 __COUTTV__(CareAboutCookieCodes_);
2195 __COUTT__ <<
"refresh=" << refresh <<
", doNotGoRemote=" << doNotGoRemote << __E__;
2196 __COUTVS__(2, cookieCode);
2200 __COUTTV__(localEnableRemoteLogin);
2205 if(localEnableRemoteLogin &&
2206 time(0) > remoteLoginVerificationEnabledBlackoutTime_ &&
2207 (userId = checkRemoteLoginVerification(
2208 cookieCode, refresh, doNotGoRemote, ip)) != NOT_FOUND_IN_DATABASE)
2211 __COUTT__ <<
"Remote login session verified." << __E__;
2212 userSession = RemoteSessions_.at(cookieCode).sessionIndex_;
2217 std::string err =
"";
2222 catch(
const std::exception& e)
2227 __COUT_WARN__ <<
"Ignoring exception during remote login verification. " << err
2231 if(!CareAboutCookieCodes_ && localEnableRemoteLogin &&
2232 remoteLoginVerificationEnabledBlackoutTime_ == 0)
2235 localEnableRemoteLogin =
false;
2236 remoteLoginVerificationEnabledBlackoutTime_ = time(0) + 10;
2237 __COUT_INFO__ <<
"Disabled remote login until "
2239 remoteLoginVerificationEnabledBlackoutTime_)
2243 __COUTTV__(localEnableRemoteLogin);
2245 if(localEnableRemoteLogin && userId == NOT_FOUND_IN_DATABASE)
2246 __COUTT__ <<
"Remote login verification failed." << __E__;
2248 if(!CareAboutCookieCodes_ &&
2249 userId == NOT_FOUND_IN_DATABASE)
2253 std::map<std::string , WebUsers::permissionLevel_t>(
2258 *userWithLock = usersUsernameWithLock_;
2259 if(userSessionIndex)
2260 *userSessionIndex = 0;
2262 if(cookieCode.size() != COOKIE_CODE_LENGTH)
2263 cookieCode = genCookieCode();
2265 if(localEnableRemoteLogin)
2267 cookieCode = WebUsers::
2275 if(userId == NOT_FOUND_IN_DATABASE)
2278 if((i = searchActiveSessionDatabaseForCookie(cookieCode)) ==
2279 NOT_FOUND_IN_DATABASE)
2281 __COUT_ERR__ <<
"Cookie code not found" << __E__;
2282 cookieCode = REQ_NO_LOGIN_RESPONSE;
2284 incrementIpBlacklistCount(ip);
2289 ipBlacklistCounts_[ip] = 0;
2292 if(ip !=
"0" && ActiveSessions_[i].ip_ != ip)
2294 __COUTV__(ActiveSessions_[i].ip_);
2296 __COUT_ERR__ <<
"IP does not match active session." << __E__;
2297 cookieCode = REQ_NO_LOGIN_RESPONSE;
2301 userId = ActiveSessions_[i].userId_;
2302 userSession = ActiveSessions_[i].sessionIndex_;
2303 cookieCode = refreshCookieCode(i, refresh);
2304 __COUTT__ <<
"Login session verified." << __E__;
2310 if((j = searchUsersDatabaseForUserId(userId)) == NOT_FOUND_IN_DATABASE)
2312 __COUT_ERR__ <<
"After login verification, User ID not found! Notify admins."
2314 cookieCode = REQ_NO_LOGIN_RESPONSE;
2318 std::map<std::string , WebUsers::permissionLevel_t> tmpPerm =
2321 if(isInactiveForGroup(tmpPerm))
2323 __COUTT__ <<
"Inactive user identified." << __E__;
2324 cookieCode = REQ_NO_PERMISSION_RESPONSE;
2330 *userPermissions = tmpPerm;
2334 *userWithLock = usersUsernameWithLock_;
2335 if(userSessionIndex)
2336 *userSessionIndex = userSession;
2353 if(loggedOutUsernames)
2355 for(i = 0; i < UsersLoggedOutUsernames_.size(); ++i)
2356 loggedOutUsernames->push_back(UsersLoggedOutUsernames_[i]);
2357 UsersLoggedOutUsernames_.clear();
2361 for(i = 0; i < LoginSessions_.size(); ++i)
2362 if(LoginSessions_[i].startTime_ + LOGIN_SESSION_EXPIRATION_TIME <
2364 LoginSessions_[i].loginAttempts_ > LOGIN_SESSION_ATTEMPTS_MAX)
2366 __COUT__ <<
"Found expired login sessions: #" << (i + 1) <<
" of "
2367 << LoginSessions_.size() << __E__;
2371 LoginSessions_.erase(LoginSessions_.begin() + i);
2384 for(i = 0; i < ActiveSessions_.size(); ++i)
2385 if(ActiveSessions_[i].startTime_ + ACTIVE_SESSION_EXPIRATION_TIME <=
2395 __COUT__ <<
"Found expired active sessions: #" << (i + 1) <<
" of "
2396 << ActiveSessions_.size() << __E__;
2397 __COUTTV__(ActiveSessions_[i].cookieCode_);
2399 tmpUid = ActiveSessions_[i].userId_;
2400 ActiveSessions_.erase(ActiveSessions_.begin() + i);
2405 if(loggedOutUsernames)
2406 loggedOutUsernames->push_back(
2407 Users_[searchUsersDatabaseForUserId(tmpUid)].username_);
2409 UsersLoggedOutUsernames_.push_back(
2410 Users_[searchUsersDatabaseForUserId(tmpUid)].username_);
2431 if(CareAboutCookieCodes_ && usersUsernameWithLock_ !=
"" &&
2439 usersUsernameWithLock_ =
"";
2449 std::vector<std::string> toErase;
2450 for(
const auto& remoteSession : RemoteSessions_)
2451 if(remoteSession.second.startTime_ + ACTIVE_SESSION_EXPIRATION_TIME / 4 <=
2454 __COUT__ <<
"Found expired remote active sessions: #" << remoteSession.first
2455 <<
" in " << RemoteSessions_.size() << __E__;
2456 toErase.push_back(remoteSession.first);
2458 for(
const auto& eraseId : toErase)
2459 RemoteSessions_.erase(eraseId);
2470 const std::string& ip)
2476 for(; i < LoginSessions_.size(); ++i)
2477 if(LoginSessions_[i].uuid_ == UUID)
2480 if(i != LoginSessions_.size())
2482 __COUT_ERR__ <<
"UUID: " << UUID <<
" is not unique" << __E__;
2488 LoginSessions_.back().uuid_ = UUID;
2492 std::string sid =
"";
2493 for(i = 0; i < SESSION_ID_LENGTH / 2; ++i)
2495 intToHexStr(rand(), hexStr);
2498 LoginSessions_.back().id_ = sid;
2499 LoginSessions_.back().ip_ = ip;
2500 LoginSessions_.back().startTime_ = time(0);
2501 LoginSessions_.back().loginAttempts_ = 0;
2511 std::string WebUsers::sha512(
const std::string& user,
2512 const std::string& password,
2515 SHA512_CTX sha512_context;
2520 SHA512_Init(&sha512_context);
2522 for(
unsigned int i = 0; i < 8; ++i)
2523 sha512_context.h[i] += rand();
2525 for(
unsigned int i = 0; i <
sizeof(SHA512_CTX); ++i)
2527 intToHexStr((uint8_t)(((uint8_t*)(&sha512_context))[i]), hexStr);
2529 salt.append(hexStr);
2537 for(
unsigned int i = 0; i <
sizeof(SHA512_CTX); ++i)
2538 ((uint8_t*)(&sha512_context))[i] = hexByteStrToInt(&(salt.c_str()[i * 2]));
2541 std::string strToHash = salt + user + password;
2544 unsigned char hash[SHA512_DIGEST_LENGTH];
2546 char retHash[SHA512_DIGEST_LENGTH * 2 + 1];
2550 SHA512_Update(&sha512_context, strToHash.c_str(), strToHash.length());
2552 SHA512_Final(hash, &sha512_context);
2556 for(i = 0; i < SHA512_DIGEST_LENGTH; i++)
2557 sprintf(retHash + (i * 2),
"%02x", hash[i]);
2560 retHash[SHA512_DIGEST_LENGTH * 2] =
'\0';
2571 std::string WebUsers::dejumble(
const std::string& u,
const std::string& s)
2573 if(s.length() != SESSION_ID_LENGTH)
2576 const int ss = s.length() / 2;
2577 int p = hexByteStrToInt(&(s.c_str()[0])) % ss;
2578 int n = hexByteStrToInt(&(s.c_str()[p * 2])) % ss;
2579 int len = (hexByteStrToInt(&(u.c_str()[p * 2])) - p - n + ss * 3) % ss;
2581 std::vector<bool> x(ss);
2582 for(
int i = 0; i < ss; ++i)
2586 int c = hexByteStrToInt(&(u.c_str()[p * 2]));
2588 std::string user =
"";
2590 for(
int l = 0; l < len; ++l)
2592 p = (p + hexByteStrToInt(&(s.c_str()[p * 2]))) % ss;
2596 n = hexByteStrToInt(&(s.c_str()[p * 2]));
2597 user.append(1, (hexByteStrToInt(&(u.c_str()[p * 2])) - c - n + ss * 4) % ss);
2598 c = hexByteStrToInt(&(u.c_str()[p * 2]));
2607 std::map<std::string , WebUsers::permissionLevel_t>
2610 uint64_t userIndex = searchUsersDatabaseForUserId(uid);
2611 if(userIndex < Users_.size())
2612 return Users_[userIndex].permissions_;
2615 std::map<std::string , WebUsers::permissionLevel_t> retErrorMap;
2616 retErrorMap[WebUsers::DEFAULT_USER_GROUP] = WebUsers::PERMISSION_LEVEL_INACTIVE;
2653 WebUsers::permissionLevel_t WebUsers::getPermissionLevelForGroup(
2654 const std::map<std::string /*groupName*/, WebUsers::permissionLevel_t>& permissionMap,
2655 const std::string& groupName)
2657 auto it = permissionMap.find(groupName);
2658 if(it == permissionMap.end())
2660 __COUT__ <<
"Group name '" << groupName
2661 <<
"' not found - assuming inactive user in this group." << __E__;
2662 return WebUsers::PERMISSION_LEVEL_INACTIVE;
2668 bool WebUsers::isInactiveForGroup(
2669 const std::map<std::string /*groupName*/, WebUsers::permissionLevel_t>& permissionMap,
2670 const std::string& groupName)
2672 return getPermissionLevelForGroup(permissionMap, groupName) ==
2673 WebUsers::PERMISSION_LEVEL_INACTIVE;
2677 bool WebUsers::isAdminForGroup(
2678 const std::map<std::string /*groupName*/, WebUsers::permissionLevel_t>& permissionMap,
2679 const std::string& groupName)
2681 return getPermissionLevelForGroup(permissionMap, groupName) ==
2688 std::string WebUsers::getTooltipFilename(
const std::string& username,
2689 const std::string& srcFile,
2690 const std::string& srcFunc,
2691 const std::string& srcId)
2693 std::string filename = (std::string)WEB_LOGIN_DB_PATH + TOOLTIP_DB_PATH +
"/";
2697 mkdir(((std::string)WEB_LOGIN_DB_PATH).c_str(), 0755);
2698 mkdir(((std::string)WEB_LOGIN_DB_PATH + USERS_DB_PATH).c_str(), 0755);
2699 mkdir(filename.c_str(), 0755);
2701 for(
const char& c : username)
2703 (c >=
'a' && c <=
'z') || (c >=
'A' && c <=
'Z') || (c >=
'0' && c <=
'9'))
2708 mkdir(filename.c_str(), 0755);
2710 for(
const char& c : srcFile)
2712 (c >=
'a' && c <=
'z') || (c >=
'A' && c <=
'Z') || (c >=
'0' && c <=
'9'))
2715 for(
const char& c : srcFunc)
2717 (c >=
'a' && c <=
'z') || (c >=
'A' && c <=
'Z') || (c >=
'0' && c <=
'9'))
2720 for(
const char& c : srcId)
2722 (c >=
'a' && c <=
'z') || (c >=
'A' && c <=
'Z') || (c >=
'0' && c <=
'9'))
2729 std::string ots::WebUsers::getUserEmailFromFingerprint(
const std::string& fingerprint)
2731 __COUT__ <<
"Checking if user fingerprint " << fingerprint <<
" is in memory database"
2733 if(certFingerprints_.count(fingerprint))
2735 return certFingerprints_[fingerprint];
2738 __COUT__ <<
"Going to read credential database " << WEB_LOGIN_CERTDATA_PATH << __E__;
2739 std::ifstream f(WEB_LOGIN_CERTDATA_PATH);
2747 if(fp !=
"NOKEY" && fp !=
"")
2749 __COUT__ <<
"Adding user " << email <<
" to list with fingerprint " << fp
2751 certFingerprints_[fp] = email;
2757 remove(WEB_LOGIN_CERTDATA_PATH.c_str());
2760 __COUT__ <<
"Checking again if fingerprint is in memory database" << __E__;
2761 if(certFingerprints_.count(fingerprint))
2763 return certFingerprints_[fingerprint];
2766 __COUT__ <<
"Could not match fingerprint, returning null email" << __E__;
2775 const std::string& srcFile,
2776 const std::string& srcFunc,
2777 const std::string& srcId,
2779 bool temporarySilence)
2781 std::string filename;
2782 bool isForAll = (srcFile ==
"ALL" && srcFunc ==
"ALL" && srcId ==
"ALL");
2786 __COUT__ <<
"Disabling ALL tooltips for user '" << username <<
"' is now set to "
2787 << doNeverShow <<
" (temporarySilence=" << temporarySilence <<
")"
2789 filename = getTooltipFilename(username, SILENCE_ALL_TOOLTIPS_FILENAME,
"",
"");
2793 filename = getTooltipFilename(username, srcFile, srcFunc, srcId);
2794 __COUT__ <<
"Setting tooltip never show for user '" << username <<
"' to "
2795 << doNeverShow <<
" (temporarySilence=" << temporarySilence <<
")"
2800 __COUTTV__(doNeverShow);
2801 __COUTTV__(temporarySilence);
2803 __COUTTV__(srcFunc);
2804 __COUTTV__(srcFile);
2805 __COUTTV__(filename);
2808 FILE* fp = fopen(filename.c_str(),
"w");
2811 if(temporarySilence)
2814 time(0) + 7 * 24 * 60 * 60);
2815 else if(!isForAll && doNeverShow && username == WebUsers::DEFAULT_ADMIN_USERNAME)
2818 fprintf(fp,
"%ld", time(0) + 30 * 24 * 60 * 60);
2820 __COUT__ <<
"User '" << username
2821 <<
"' may be a shared account, so max silence duration for tooltips "
2822 "is 30 days. Silencing now."
2826 fputc(doNeverShow ?
'1' :
'0', fp);
2830 __COUT_ERR__ <<
"Big problem with tooltips! File not accessible: " << filename
2843 const std::string& srcFile,
2844 const std::string& srcFunc,
2845 const std::string& srcId)
2847 if(srcId ==
"ALWAYS")
2850 xmldoc->addTextElementToData(
"ShowTooltip",
"1");
2855 std::string silencefilename =
2856 getTooltipFilename(username, SILENCE_ALL_TOOLTIPS_FILENAME,
"",
"");
2860 __COUTTV__(username);
2862 __COUTTV__(srcFunc);
2863 __COUTTV__(srcFile);
2864 __COUTTV__(silencefilename);
2867 FILE* silencefp = fopen(silencefilename.c_str(),
"r");
2868 if(silencefp != NULL)
2872 fgets(line, 100, silencefp);
2873 sscanf(line,
"%ld", &val);
2877 xmldoc->addTextElementToData(
"ShowTooltip",
"0");
2883 std::string filename = getTooltipFilename(username, srcFile, srcFunc, srcId);
2884 FILE* fp = fopen(filename.c_str(),
"r");
2889 fgets(line, 100, fp);
2890 sscanf(line,
"%ld", &val);
2893 __COUT__ <<
"tooltip value read = " << val <<
" vs time(0)=" << time(0) << __E__;
2897 xmldoc->addTextElementToData(
"ShowTooltip",
2898 val == 1 ?
"0" : (time(0) > val ?
"1" :
"0"));
2902 xmldoc->addTextElementToData(
"ShowTooltip",
"1");
2912 (
"rm -rf " + (std::string)WEB_LOGIN_DB_PATH + TOOLTIP_DB_PATH +
"/" + userNeedle)
2914 __COUT__ <<
"Successfully reset Tooltips for user " << userNeedle << __E__;
2922 std::string silencefilename = getTooltipFilename(
2923 username, SILENCE_ALL_TOOLTIPS_FILENAME,
"",
"");
2925 __COUTV__(silencefilename);
2926 FILE* silencefp = fopen(silencefilename.c_str(),
"w");
2927 if(silencefp != NULL)
2929 fputs(
"1", silencefp);
2960 bool includeAccounts,
2961 std::map<std::string /*groupName*/, WebUsers::permissionLevel_t>
2964 if(permissionMap.size() == 0)
2966 __COUTT__ <<
"Getting local permissions for user " << uid << __E__;
2971 if(isInactiveForGroup(permissionMap))
2974 uint64_t userIndex = searchUsersDatabaseForUserId(uid);
2975 __COUT__ <<
"Gettings settings for user: " << Users_[userIndex].username_ << __E__;
2977 std::string fn = (std::string)WEB_LOGIN_DB_PATH +
2978 (std::string)USERS_PREFERENCES_PATH + Users_[userIndex].username_ +
2979 "." + (std::string)USERS_PREFERENCES_FILETYPE;
2983 __COUT__ <<
"Preferences file: " << fn << __E__;
2987 __COUT__ <<
"Preferences are defaults." << __E__;
2989 xmldoc->addTextElementToData(PREF_XML_BGCOLOR_FIELD, PREF_XML_BGCOLOR_DEFAULT);
2990 xmldoc->addTextElementToData(PREF_XML_DBCOLOR_FIELD, PREF_XML_DBCOLOR_DEFAULT);
2991 xmldoc->addTextElementToData(PREF_XML_WINCOLOR_FIELD, PREF_XML_WINCOLOR_DEFAULT);
2992 xmldoc->addTextElementToData(PREF_XML_LAYOUT_FIELD, PREF_XML_LAYOUT_DEFAULT);
2996 __COUT__ <<
"Saved Preferences found." << __E__;
3001 if(includeAccounts && isAdminForGroup(permissionMap))
3003 __COUT__ <<
"Admin on our hands" << __E__;
3005 xmldoc->addTextElementToData(PREF_XML_ACCOUNTS_FIELD,
"");
3007 if(Users_.size() == 0)
3009 __COUT__ <<
"Missing users? Attempting to load database" << __E__;
3014 for(uint64_t i = 0; i < Users_.size(); ++i)
3017 "username", Users_[i].username_, PREF_XML_ACCOUNTS_FIELD);
3019 "display_name", Users_[i].displayName_, PREF_XML_ACCOUNTS_FIELD);
3021 if(Users_[i].email_.size() > i)
3024 "useremail", Users_[i].email_, PREF_XML_ACCOUNTS_FIELD);
3034 PREF_XML_ACCOUNTS_FIELD);
3037 "nac", Users_[i].getNewAccountCode().c_str(), PREF_XML_ACCOUNTS_FIELD);
3042 fn = (std::string)WEB_LOGIN_DB_PATH + (std::string)USERS_PREFERENCES_PATH +
3043 (std::string)SYSTEM_PREFERENCES_PREFIX +
"." +
3044 (std::string)USERS_PREFERENCES_FILETYPE;
3047 __COUT__ <<
"System Preferences are defaults." << __E__;
3049 xmldoc->addTextElementToData(PREF_XML_SYSLAYOUT_FIELD,
3050 PREF_XML_SYSLAYOUT_DEFAULT);
3054 __COUT__ <<
"Saved System Preferences found." << __E__;
3061 xmldoc->addTextElementToData(PREF_XML_PERMISSIONS_FIELD,
3065 xmldoc->addTextElementToData(PREF_XML_USERLOCK_FIELD, usersUsernameWithLock_);
3068 xmldoc->addTextElementToData(PREF_XML_USERNAME_FIELD,
getUsersUsername(uid));
3074 xmldoc->addTextElementToData(
"ots_remote_address",
3075 remoteLoginVerificationIP_ +
":" +
3084 const std::string& preferenceName,
3085 const std::string& preferenceValue)
3087 uint64_t userIndex = searchUsersDatabaseForUserId(uid);
3092 std::string safePreferenceName =
"";
3093 for(
const auto& c : preferenceName)
3094 if((c >=
'a' && c <=
'z') || (c >=
'A' && c <=
'Z') || (c >=
'0' && c <=
'9') ||
3095 (c >=
'-' || c <=
'_'))
3096 safePreferenceName += c;
3098 std::string dir = (std::string)WEB_LOGIN_DB_PATH +
3099 (std::string)USERS_PREFERENCES_PATH +
"generic_" +
3100 safePreferenceName +
"/";
3103 mkdir(dir.c_str(), 0755);
3105 std::string fn = Users_[userIndex].username_ +
"_" + safePreferenceName +
"." +
3106 (std::string)USERS_PREFERENCES_FILETYPE;
3108 __COUT__ <<
"Preferences file: " << (dir + fn) << __E__;
3110 FILE* fp = fopen((dir + fn).c_str(),
"w");
3113 fprintf(fp,
"%s", preferenceValue.c_str());
3117 __COUT_ERR__ <<
"Preferences file could not be opened for writing!" << __E__;
3125 const std::string& preferenceName,
3128 uint64_t userIndex = searchUsersDatabaseForUserId(uid);
3133 std::string safePreferenceName =
"";
3134 for(
const auto& c : preferenceName)
3135 if((c >=
'a' && c <=
'z') || (c >=
'A' && c <=
'Z') || (c >=
'0' && c <=
'9') ||
3136 (c >=
'-' || c <=
'_'))
3137 safePreferenceName += c;
3139 std::string dir = (std::string)WEB_LOGIN_DB_PATH +
3140 (std::string)USERS_PREFERENCES_PATH +
"generic_" +
3141 safePreferenceName +
"/";
3143 std::string fn = Users_[userIndex].username_ +
"_" + safePreferenceName +
"." +
3144 (std::string)USERS_PREFERENCES_FILETYPE;
3146 __COUT__ <<
"Preferences file: " << (dir + fn) << __E__;
3149 FILE* fp = fopen((dir + fn).c_str(),
"r");
3152 fseek(fp, 0, SEEK_END);
3153 const long size = ftell(fp);
3154 char* line =
new char
3158 fread(line, 1, size, fp);
3161 std::string retVal(line, size);
3164 __COUT__ <<
"Read value (sz = " << retVal.size() <<
") " << retVal << __E__;
3166 xmldoc->addTextElementToData(safePreferenceName, retVal);
3170 __COUT__ <<
"Using default value." << __E__;
3174 xmldoc->addTextElementToData(safePreferenceName,
"");
3181 const std::string& bgcolor,
3182 const std::string& dbcolor,
3183 const std::string& wincolor,
3184 const std::string& layout,
3185 const std::string& syslayout,
3186 const std::string& aliaslayout,
3187 const std::string& sysaliaslayout)
3189 std::map<std::string , WebUsers::permissionLevel_t> permissionMap =
3191 if(isInactiveForGroup(permissionMap))
3194 uint64_t userIndex = searchUsersDatabaseForUserId(uid);
3195 __COUT__ <<
"Changing settings for user: " << Users_[userIndex].username_ << __E__;
3197 std::string fn = (std::string)WEB_LOGIN_DB_PATH +
3198 (std::string)USERS_PREFERENCES_PATH + Users_[userIndex].username_ +
3199 "." + (std::string)USERS_PREFERENCES_FILETYPE;
3201 __COUT__ <<
"Preferences file: " << fn << __E__;
3204 prefXml.addTextElementToData(PREF_XML_BGCOLOR_FIELD, bgcolor);
3205 prefXml.addTextElementToData(PREF_XML_DBCOLOR_FIELD, dbcolor);
3206 prefXml.addTextElementToData(PREF_XML_WINCOLOR_FIELD, wincolor);
3207 prefXml.addTextElementToData(PREF_XML_LAYOUT_FIELD, layout);
3208 prefXml.addTextElementToData(PREF_XML_ALIAS_LAYOUT_FIELD, aliaslayout);
3213 if(!isAdminForGroup(permissionMap))
3217 fn = (std::string)WEB_LOGIN_DB_PATH + (std::string)USERS_PREFERENCES_PATH +
3218 (std::string)SYSTEM_PREFERENCES_PREFIX +
"." +
3219 (std::string)USERS_PREFERENCES_FILETYPE;
3222 sysPrefXml.addTextElementToData(PREF_XML_SYSLAYOUT_FIELD, syslayout);
3223 sysPrefXml.addTextElementToData(PREF_XML_SYSALIAS_LAYOUT_FIELD, sysaliaslayout);
3235 std::map<std::string , WebUsers::permissionLevel_t> permissionMap =
3241 __COUTV__(actingUser);
3243 __COUTV__(usersUsernameWithLock_);
3245 __COUTV__(username);
3246 __COUTV__(isUserActive);
3249 (isUserActive || !WebUsers::CareAboutCookieCodes_))
3251 if(!WebUsers::CareAboutCookieCodes_ && !isUserActive &&
3253 DEFAULT_ADMIN_USERNAME)
3256 <<
"User '" << actingUser
3257 <<
"' tried to lock for a user other than admin in wiz mode. Not allowed."
3261 else if(!isAdminForGroup(permissionMap) &&
3262 actingUser != username)
3264 __COUT_ERR__ <<
"A non-admin user '" << actingUser
3265 <<
"' tried to lock for a user other than self. Not allowed."
3269 usersUsernameWithLock_ = username;
3271 else if(!lock && usersUsernameWithLock_ == username)
3272 usersUsernameWithLock_ =
"";
3276 __COUT_ERR__ <<
"User '" << username <<
"' is inactive." << __E__;
3277 __COUT_ERR__ <<
"Failed to lock for user '" << username <<
".'" << __E__;
3281 __COUT_INFO__ <<
"User '" << username <<
"' has locked out the system!" << __E__;
3285 std::string securityFileName = USER_WITH_LOCK_FILE;
3286 FILE* fp = fopen(securityFileName.c_str(),
"w");
3289 __COUT_INFO__ <<
"USER_WITH_LOCK_FILE " << USER_WITH_LOCK_FILE
3290 <<
" not found. Ignoring." << __E__;
3294 fprintf(fp,
"%s", usersUsernameWithLock_.c_str());
3305 const std::string& username,
3306 const std::string& displayname,
3307 const std::string& email,
3308 const std::string& permissions)
3310 std::map<std::string , WebUsers::permissionLevel_t> permissionMap =
3312 if(!isAdminForGroup(permissionMap))
3315 __SS__ <<
"Only admins can modify user settings." << __E__;
3319 uint64_t i = searchUsersDatabaseForUserId(actingUid);
3320 uint64_t modi = searchUsersDatabaseForUsername(username);
3325 __COUT_INFO__ <<
"Admin password reset." << __E__;
3326 Users_[modi].setModifier(Users_[i].username_);
3327 Users_[modi].salt_ =
"";
3328 Users_[modi].loginFailureCount_ = 0;
3329 saveDatabaseToFile(DB_USERS);
3332 __SS__ <<
"Cannot modify first user" << __E__;
3336 if(username.length() < USERNAME_LENGTH)
3338 __SS__ <<
"Invalid Username, must be length " << USERNAME_LENGTH << __E__;
3341 if(displayname.length() < DISPLAY_NAME_LENGTH)
3343 __SS__ <<
"Invalid Display Name; must be length " << DISPLAY_NAME_LENGTH << __E__;
3347 __COUT__ <<
"Input Permissions: " << permissions << __E__;
3348 std::map<std::string , WebUsers::permissionLevel_t> newPermissionsMap;
3352 case MOD_TYPE_UPDATE:
3354 __COUT__ <<
"MOD_TYPE_UPDATE " << username <<
" := " << permissions << __E__;
3356 if(modi == NOT_FOUND_IN_DATABASE)
3358 __SS__ <<
"User not found!? Should not happen." << __E__;
3364 for(uint64_t i = 0; i < Users_.size(); ++i)
3367 else if(Users_[i].displayName_ == displayname)
3369 __SS__ <<
"Display Name '" << displayname
3370 <<
"' already exists! Please choose a unique display name."
3376 Users_[modi].displayName_ = displayname;
3377 Users_[modi].email_ = email;
3381 bool wasInactive = isInactiveForGroup(Users_[modi].permissions_);
3384 if(newPermissionsMap.size() == 0)
3385 Users_[modi].permissions_[WebUsers::DEFAULT_USER_GROUP] =
3386 std::atoi(permissions.c_str());
3387 else if(newPermissionsMap.size() == 1 &&
3388 newPermissionsMap.find(WebUsers::DEFAULT_USER_GROUP) ==
3389 newPermissionsMap.end())
3391 if(newPermissionsMap.begin()->first ==
"")
3392 Users_[modi].permissions_[WebUsers::DEFAULT_USER_GROUP] =
3393 newPermissionsMap.begin()->second;
3396 newPermissionsMap[WebUsers::DEFAULT_USER_GROUP] =
3397 newPermissionsMap.begin()->second;
3398 Users_[modi].permissions_ = newPermissionsMap;
3402 Users_[modi].permissions_ = newPermissionsMap;
3407 !isInactiveForGroup(Users_[modi].permissions_))
3409 __COUT__ <<
"Reactivating " << username << __E__;
3410 Users_[modi].loginFailureCount_ = 0;
3411 Users_[modi].salt_ =
"";
3417 if(i == NOT_FOUND_IN_DATABASE)
3419 __SS__ <<
"Master User not found!? Should not happen." << __E__;
3422 Users_[modi].setModifier(Users_[i].username_);
3428 __COUT__ <<
"MOD_TYPE_ADD " << username <<
" - " << displayname << __E__;
3433 if(i == NOT_FOUND_IN_DATABASE)
3435 __SS__ <<
"Master User not found!? Should not happen." << __E__;
3438 Users_.back().setModifier(Users_[i].username_);
3441 if(permissions.size())
3444 actingUid, MOD_TYPE_UPDATE, username, displayname, email, permissions);
3448 case MOD_TYPE_DELETE:
3449 __COUT__ <<
"MOD_TYPE_DELETE " << username <<
" - " << displayname << __E__;
3450 deleteAccount(username, displayname);
3453 __SS__ <<
"Undefined command - do nothing " << username << __E__;
3457 saveDatabaseToFile(DB_USERS);
3458 loadSecuritySelection();
3465 std::set<unsigned int> activeUserIndices;
3466 for(uint64_t i = 0; i < ActiveSessions_.size(); ++i)
3467 activeUserIndices.emplace(
3468 searchUsersDatabaseForUserId(ActiveSessions_[i].userId_));
3470 for(
const auto& sessionPair : RemoteSessions_)
3471 activeUserIndices.emplace(
3472 searchUsersDatabaseForUserId(sessionPair.second.userId_));
3473 return activeUserIndices.size();
3481 std::set<unsigned int> activeUserIndices;
3482 for(uint64_t i = 0; i < ActiveSessions_.size(); ++i)
3483 activeUserIndices.emplace(
3484 searchUsersDatabaseForUserId(ActiveSessions_[i].userId_));
3486 for(
const auto& sessionPair : RemoteSessions_)
3487 activeUserIndices.emplace(
3488 searchUsersDatabaseForUserId(sessionPair.second.userId_));
3490 std::string activeUsersString =
"";
3491 bool addComma =
false;
3492 for(
const auto& i : activeUserIndices)
3494 if(i >= Users_.size())
3498 activeUsersString +=
",";
3502 activeUsersString += Users_[i].displayName_;
3504 if(activeUserIndices.size() == 0 &&
3506 WebUsers::SECURITY_TYPE_NONE)
3507 activeUsersString += WebUsers::DEFAULT_ADMIN_DISPLAY_NAME;
3509 __COUTVS__(20, activeUsersString);
3510 return activeUsersString;
3518 uint64_t uid = searchUsersDatabaseForUsername(DEFAULT_ADMIN_USERNAME);
3525 void WebUsers::loadUserWithLock()
3527 char username[300] =
"";
3529 std::string securityFileName = USER_WITH_LOCK_FILE;
3530 FILE* fp = fopen(securityFileName.c_str(),
"r");
3533 __COUT_INFO__ <<
"USER_WITH_LOCK_FILE " << USER_WITH_LOCK_FILE
3534 <<
" not found. Defaulting to admin lock." << __E__;
3537 sprintf(username,
"%s", DEFAULT_ADMIN_USERNAME.c_str());
3541 fgets(username, 300, fp);
3548 __COUT__ <<
"Attempting to load username with lock: " << username << __E__;
3550 if(strlen(username) == 0)
3552 __COUT_INFO__ <<
"Loaded state for user-with-lock is unlocked." << __E__;
3556 uint64_t i = searchUsersDatabaseForUsername(username);
3557 if(i == NOT_FOUND_IN_DATABASE)
3559 __COUT_INFO__ <<
"username " << username <<
" not found in database. Ignoring."
3563 __COUT__ <<
"Setting lock" << __E__;
3571 const std::string& message)
3580 const std::string& subject,
3581 const std::string& message,
3584 std::vector<std::string> targetUsers;
3594 const std::string& subject,
3595 const std::string& message,
3598 systemMessageCleanup();
3600 std::string fullMessage = StringMacros::encodeURIComponent(
3601 (subject ==
"" ?
"" : (subject +
": ")) + message);
3604 std::cout << __COUT_HDR_FL__ <<
"addSystemMessage() fullMessage: " << fullMessage
3608 std::set<std::string> targetEmails;
3610 for(
const auto& targetUser : targetUsers)
3614 if(targetUser ==
"" || (targetUser !=
"*" && targetUser.size() < 3))
3616 __COUT__ <<
"Illegal username '" << targetUser <<
"'" << __E__;
3619 __COUTV__(targetUser);
3623 if(doEmail && targetUser ==
"*")
3626 for(
const auto& user : Users_)
3628 if(user.email_.size() > 5 &&
3629 user.email_.find(
'@') != std::string::npos &&
3630 user.email_.find(
'.') != std::string::npos)
3632 __COUT__ <<
"Adding " << user.displayName_
3633 <<
" email: " << user.email_ << __E__;
3634 targetEmails.emplace(user.email_);
3639 else if(targetUser.find(
':') != std::string::npos)
3642 __COUT__ <<
"Treating as group email target: " << targetUser << __E__;
3644 std::map<std::string, WebUsers::permissionLevel_t> targetGroupMap;
3651 if(targetGroupMap.size() == 1)
3656 for(
const auto& user : Users_)
3658 WebUsers::permissionLevel_t userLevel =
3660 targetGroupMap.begin()->first);
3664 __COUTV__((
int)userLevel);
3665 __COUTV__(targetGroupMap.begin()->first);
3667 if(userLevel != WebUsers::PERMISSION_LEVEL_INACTIVE &&
3668 userLevel >= targetGroupMap.begin()->second &&
3669 user.email_.size() > 5 &&
3670 user.email_.find(
'@') != std::string::npos &&
3671 user.email_.find(
'.') != std::string::npos)
3675 targetEmails.emplace(user.email_);
3676 __COUT__ <<
"Adding " << user.displayName_
3677 <<
" email: " << user.email_ << __E__;
3679 addSystemMessageToMap(user.displayName_, fullMessage);
3684 __COUT__ <<
"target Group Map from '" << targetUser <<
"' is empty."
3692 addSystemMessageToMap(targetUser, fullMessage);
3696 for(
const auto& user : Users_)
3698 if(user.displayName_ == targetUser)
3700 if(user.email_.size() > 5 &&
3701 user.email_.find(
'@') != std::string::npos &&
3702 user.email_.find(
'.') != std::string::npos)
3704 targetEmails.emplace(user.email_);
3705 __COUT__ <<
"Adding " << user.displayName_
3706 <<
" email: " << user.email_ << __E__;
3715 __COUTV__(targetEmails.size());
3717 if(doEmail && targetEmails.size())
3721 std::string toList =
"";
3722 bool addComma =
false;
3723 for(
const auto& email : targetEmails)
3732 std::string filename = (std::string)WEB_LOGIN_DB_PATH +
3733 (std::string)USERS_DB_PATH +
"/.tmp_email.txt";
3734 FILE* fp = fopen(filename.c_str(),
"w");
3737 __SS__ <<
"Could not open email file: " << filename << __E__;
3747 fprintf(fp,
"To: %s\n", toList.c_str());
3748 fprintf(fp,
"Subject: %s\n", subject.c_str());
3749 fprintf(fp,
"Content-Type: text/html\n");
3750 fprintf(fp,
"\n<html><pre>%s</pre></html>", message.c_str());
3756 __COUT_WARN__ <<
"Do email was attempted, but no target users had email "
3757 "addresses specified!"
3766 void WebUsers::addSystemMessageToMap(
const std::string& targetUser,
3767 const std::string& fullMessage)
3770 std::lock_guard<std::mutex> lock(systemMessageLock_);
3772 __COUT__ <<
"Before number of users with system messages: " << systemMessages_.size()
3773 <<
", first user has "
3774 << (systemMessages_.size() ? systemMessages_.begin()->second.size() : 0)
3775 <<
" messages." << __E__;
3777 auto it = systemMessages_.find(targetUser);
3780 if(it != systemMessages_.end() && it->second.size() &&
3781 it->second[it->second.size() - 1].message_ == fullMessage)
3784 if(it == systemMessages_.end())
3786 systemMessages_.emplace(
3787 std::pair<std::string , std::vector<SystemMessage>>(
3788 targetUser, std::vector<SystemMessage>({SystemMessage(fullMessage)})));
3789 __COUTT__ << targetUser <<
" Current System Messages count = " << 1 << __E__;
3794 it->second.push_back(SystemMessage(fullMessage));
3795 __COUTT__ << it->first <<
" Current System Messages count = " << it->second.size()
3799 __COUT__ <<
"After number of users with system messages: " << systemMessages_.size()
3800 <<
", first user has "
3801 << (systemMessages_.size() ? systemMessages_.begin()->second.size() : 0)
3802 <<
" messages." << __E__;
3811 std::lock_guard<std::mutex> lock(systemMessageLock_);
3813 __COUTT__ <<
"GetLast number of users with system messages: "
3814 << systemMessages_.size() <<
", first user has "
3815 << (systemMessages_.size() ? systemMessages_.begin()->second.size() : 0)
3816 <<
" messages." << __E__;
3818 auto it = systemMessages_.find(
"*");
3819 if(it == systemMessages_.end() || it->second.size() == 0)
3820 return std::make_pair(
"", 0);
3822 return std::make_pair(it->second.back().message_, it->second.back().creationTime_);
3831 std::string retStr =
"";
3834 std::lock_guard<std::mutex> lock(systemMessageLock_);
3836 for(
auto& userSysMessages : systemMessages_)
3838 for(
auto& userSysMessage : userSysMessages.second)
3840 if(userSysMessage.deliveredRemote_)
3845 retStr += userSysMessages.first;
3846 retStr +=
"|" + std::to_string(userSysMessage.creationTime_);
3847 retStr +=
"|" + userSysMessage.message_;
3848 userSysMessage.deliveredRemote_ =
true;
3863 __COUTS__(20) <<
"Current System Messages: " << targetUser << __E__;
3864 std::string retStr =
"";
3870 std::lock_guard<std::mutex> lock(systemMessageLock_);
3872 __COUTS__(20) <<
"Number of users with system messages: "
3873 << systemMessages_.size() << __E__;
3876 auto it = systemMessages_.find(
"*");
3877 for(uint64_t i = 0; it != systemMessages_.end() && i < it->second.size(); ++i)
3882 sprintf(tmp,
"%lu", it->second[i].creationTime_);
3883 retStr += std::string(tmp) +
"|" + it->second[i].message_;
3889 __COUTVS__(20, targetUser);
3890 it = systemMessages_.find(targetUser);
3893 for(
auto systemMessagePair : systemMessages_)
3894 __COUTS__(20) << systemMessagePair.first <<
" "
3895 << systemMessagePair.second.size() <<
" "
3896 << (systemMessagePair.second.size()
3897 ? systemMessagePair.second[0].message_
3901 if(it != systemMessages_.end())
3903 __COUTS__(20) <<
"Message count: " << it->second.size() <<
", Last Message: "
3904 << (it->second.size() ? it->second.back().message_ :
"")
3908 for(uint64_t i = 0; it != systemMessages_.end() && i < it->second.size(); ++i)
3913 sprintf(tmp,
"%lu", it->second[i].creationTime_);
3914 retStr += std::string(tmp) +
"|" + it->second[i].message_;
3916 it->second[i].delivered_ =
true;
3921 __COUTS__(20) <<
"retStr: " << retStr << __E__;
3923 systemMessageCleanup();
3931 void WebUsers::systemMessageCleanup()
3934 std::lock_guard<std::mutex> lock(systemMessageLock_);
3936 __COUTT__ <<
"Before cleanup number of users with system messages: "
3937 << systemMessages_.size() <<
", first user has "
3938 << (systemMessages_.size() ? systemMessages_.begin()->second.size() : 0)
3939 <<
" messages." << __E__;
3940 for(
auto& userMessagesPair : systemMessages_)
3942 for(uint64_t i = 0; i < userMessagesPair.second.size(); ++i)
3943 if((userMessagesPair.first !=
"*" &&
3944 userMessagesPair.second[i].delivered_) ||
3948 __COUTT__ << userMessagesPair.first
3949 <<
" at time: " << userMessagesPair.second[i].creationTime_
3950 <<
" system messages: " << userMessagesPair.second.size()
3954 userMessagesPair.second.erase(userMessagesPair.second.begin() + i);
3958 __COUTT__ <<
"User '" << userMessagesPair.first
3959 <<
"' remaining system messages: " << userMessagesPair.second.size()
3962 __COUTT__ <<
"After cleanup number of users with system messages: "
3963 << systemMessages_.size() <<
", first user has "
3964 << (systemMessages_.size() ? systemMessages_.begin()->second.size() : 0)
3965 <<
" messages." << __E__;
3973 void WebUsers::loadSecuritySelection()
3975 std::string securityFileName = SECURITY_FILE_NAME;
3976 FILE* fp = fopen(securityFileName.c_str(),
"r");
3977 char line[100] =
"";
3979 fgets(line, 100, fp);
3983 while(i < strlen(line) && line[i] >=
'A' && line[i] <=
'z')
3987 if(strcmp(line, SECURITY_TYPE_NONE.c_str()) == 0 ||
3988 strcmp(line, SECURITY_TYPE_DIGEST_ACCESS.c_str()) == 0)
3989 securityType_ = line;
3991 securityType_ = SECURITY_TYPE_DEFAULT;
3993 __COUT__ <<
"The current security type is " << securityType_ << __E__;
3998 if(securityType_ == SECURITY_TYPE_NONE)
3999 CareAboutCookieCodes_ =
false;
4001 CareAboutCookieCodes_ =
true;
4003 __COUT__ <<
"CareAboutCookieCodes_: " << CareAboutCookieCodes_ << __E__;
4005 loadIPAddressSecurity();
4011 void WebUsers::loadIPAddressSecurity()
4013 ipAccessAccept_.clear();
4014 ipAccessReject_.clear();
4015 ipAccessBlacklist_.clear();
4017 FILE* fp = fopen((IP_ACCEPT_FILE).c_str(),
"r");
4023 while(fgets(line, 300, fp))
4027 if(len > 2 && line[len - 1] ==
'\n')
4028 line[len - 1] =
'\0';
4029 ipAccessAccept_.emplace(line);
4036 __COUTV__(ipAccessAccept_.size());
4038 fp = fopen((IP_REJECT_FILE).c_str(),
"r");
4041 while(fgets(line, 300, fp))
4045 if(len > 2 && line[len - 1] ==
'\n')
4046 line[len - 1] =
'\0';
4047 ipAccessReject_.emplace(line);
4054 __COUTV__(ipAccessReject_.size());
4056 fp = fopen((IP_BLACKLIST_FILE).c_str(),
"r");
4059 while(fgets(line, 300, fp))
4063 if(len > 2 && line[len - 1] ==
'\n')
4064 line[len - 1] =
'\0';
4065 ipAccessBlacklist_.emplace(line);
4072 __COUTV__(ipAccessBlacklist_.size());
4076 void WebUsers::NACDisplayThread(
const std::string& nac,
const std::string& user)
4087 std::this_thread::sleep_for(std::chrono::seconds(2));
4089 <<
"\n******************************************************************** "
4092 <<
"\n******************************************************************** "
4094 __COUT__ <<
"\n\nNew account code = " << nac <<
" for user: " << user <<
"\n"
4097 <<
"\n******************************************************************** "
4100 <<
"\n******************************************************************** "
4106 void WebUsers::deleteUserData()
4108 __COUT__ <<
"$$$$$$$$$$$$$$ Deleting ALL service user data... $$$$$$$$$$$$" << __E__;
4112 (
"rm -rf " + (std::string)WEB_LOGIN_DB_PATH + HASHES_DB_PATH +
"/*").c_str());
4114 (
"rm -rf " + (std::string)WEB_LOGIN_DB_PATH + USERS_DB_PATH +
"/*").c_str());
4116 (
"rm -rf " + (std::string)WEB_LOGIN_DB_PATH + USERS_LOGIN_HISTORY_PATH +
"/*")
4119 (
"rm -rf " + (std::string)WEB_LOGIN_DB_PATH + USERS_PREFERENCES_PATH +
"/*")
4121 std::system((
"rm -rf " + (std::string)WEB_LOGIN_DB_PATH + TOOLTIP_DB_PATH).c_str());
4123 std::string serviceDataPath = __ENV__(
"SERVICE_DATA_PATH");
4125 std::system((
"rm -rf " + std::string(serviceDataPath) +
"/MacroData/").c_str());
4126 std::system((
"rm -rf " + std::string(serviceDataPath) +
"/MacroHistory/").c_str());
4127 std::system((
"rm -rf " + std::string(serviceDataPath) +
"/MacroExport/").c_str());
4131 (
"rm -rf " + std::string(serviceDataPath) +
"/ConsolePreferences/").c_str());
4134 std::system((
"rm -rf " + std::string(serviceDataPath) +
"/CodeEditorData/").c_str());
4137 std::system((
"rm -rf " + std::string(serviceDataPath) +
"/OtsWizardData/").c_str());
4140 std::system((
"rm -rf " + std::string(serviceDataPath) +
"/ProgressBarData/").c_str());
4143 std::system((
"rm -rf " + std::string(serviceDataPath) +
"/RunNumber/").c_str());
4144 std::system((
"rm -rf " + std::string(serviceDataPath) +
"/RunControlData/").c_str());
4147 std::system((
"rm -rf " + std::string(serviceDataPath) +
"/VisualizerData/").c_str());
4154 std::system((
"rm -rf " + std::string(__ENV__(
"LOGBOOK_DATA_PATH")) +
"/").c_str());
4156 __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)
void insertSettingsForUser(uint64_t uid, HttpXmlDocument *xmldoc, bool includeAccounts=false, std::map< std::string, WebUsers::permissionLevel_t > permissionMap={})
if empty, fetches local permissions; if provided, overrides with given permissions (e....
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.
@ 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)
defines used also by OtsConfigurationWizardSupervisor
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()