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"
34 #define USERS_LOGIN_FAILURE_FILE USERS_DB_PATH + "/loginFailureCounts.dat"
36 #define SILENCE_ALL_TOOLTIPS_FILENAME "silenceTooltips"
38 #define HASHES_DB_GLOBAL_STRING "hashData"
39 #define HASHES_DB_ENTRY_STRING "hashEntry"
40 #define USERS_DB_GLOBAL_STRING "userData"
41 #define USERS_DB_ENTRY_STRING "userEntry"
42 #define USERS_DB_NEXT_UID_STRING "nextUserId"
45 #define PREF_XML_BGCOLOR_FIELD "pref_bgcolor"
46 #define PREF_XML_DBCOLOR_FIELD "pref_dbcolor"
47 #define PREF_XML_WINCOLOR_FIELD "pref_wincolor"
48 #define PREF_XML_LAYOUT_FIELD "pref_layout"
49 #define PREF_XML_SYSLAYOUT_FIELD "pref_syslayout"
50 #define PREF_XML_ALIAS_LAYOUT_FIELD "pref_aliaslayout"
51 #define PREF_XML_SYSALIAS_LAYOUT_FIELD "pref_sysalias_layout"
52 #define PREF_XML_PERMISSIONS_FIELD "desktop_user_permissions"
53 #define PREF_XML_USERLOCK_FIELD "username_with_lock"
54 #define PREF_XML_USERNAME_FIELD "pref_username"
55 #define PREF_XML_OTS_OWNER_FIELD "ots_owner"
57 #define PREF_XML_BGCOLOR_DEFAULT "rgb(0,76,151)"
58 #define PREF_XML_DBCOLOR_DEFAULT "rgb(0,40,85)"
59 #define PREF_XML_WINCOLOR_DEFAULT "rgba(196,229,255,0.9)"
60 #define PREF_XML_LAYOUT_DEFAULT "0;0;0;0"
61 #define PREF_XML_SYSLAYOUT_DEFAULT "0;0"
63 #define PREF_XML_ACCOUNTS_FIELD "users_accounts"
64 #define PREF_XML_LOGIN_HISTORY_FIELD "login_entry"
67 const std::string WebUsers::DEFAULT_ADMIN_USERNAME =
"admin";
68 const std::string WebUsers::DEFAULT_ADMIN_DISPLAY_NAME =
"Administrator";
69 const std::string WebUsers::DEFAULT_ADMIN_EMAIL =
"root@otsdaq.fnal.gov";
70 const std::string WebUsers::DEFAULT_ITERATOR_USERNAME =
"iterator";
71 const std::string WebUsers::DEFAULT_STATECHANGER_USERNAME =
"statechanger";
72 const std::string WebUsers::DEFAULT_USER_GROUP =
"allUsers";
74 const std::string WebUsers::REQ_NO_LOGIN_RESPONSE =
"NoLogin";
75 const std::string WebUsers::REQ_NO_PERMISSION_RESPONSE =
"NoPermission";
76 const std::string WebUsers::REQ_USER_LOCKOUT_RESPONSE =
"UserLockout";
77 const std::string WebUsers::REQ_LOCK_REQUIRED_RESPONSE =
"LockRequired";
78 const std::string WebUsers::REQ_ALLOW_NO_USER =
"AllowNoUser";
80 const std::string WebUsers::SECURITY_TYPE_NONE =
"NoSecurity";
81 const std::string WebUsers::SECURITY_TYPE_DIGEST_ACCESS =
"DigestAccessAuthentication";
82 const std::string WebUsers::SECURITY_TYPE_DEFAULT = WebUsers::SECURITY_TYPE_NONE;
84 const std::vector<std::string> WebUsers::HashesDatabaseEntryFields_ = {
"hash",
"lastAccessTime"};
85 const std::vector<std::string> WebUsers::UsersDatabaseEntryFields_ = {
"username",
"displayName",
"salt",
86 "uid",
"permissions",
"lastLoginAttemptTime",
"accountCreatedTime",
87 "loginFailureCount",
"lastModifiedTime",
"lastModifierUsername",
"useremail"};
90 #define __MF_SUBJECT__ "WebUsers"
93 volatile bool WebUsers::CareAboutCookieCodes_ =
true;
103 usersNextUserId_ = 0;
104 usersUsernameWithLock_ =
"";
123 mkdir(((std::string)WEB_LOGIN_DB_PATH).c_str(), 0755);
124 mkdir(((std::string)WEB_LOGIN_DB_PATH +
"bkup/" + USERS_DB_PATH).c_str(), 0755);
125 mkdir(((std::string)WEB_LOGIN_DB_PATH + HASHES_DB_PATH).c_str(), 0755);
126 mkdir(((std::string)WEB_LOGIN_DB_PATH + USERS_DB_PATH).c_str(), 0755);
127 mkdir(((std::string)WEB_LOGIN_DB_PATH + USERS_LOGIN_HISTORY_PATH).c_str(), 0755);
128 mkdir(((std::string)WEB_LOGIN_DB_PATH + USERS_PREFERENCES_PATH).c_str(), 0755);
131 __COUT__ <<
"FATAL USER DATABASE ERROR - failed to load!!!" << __E__;
133 loadSecuritySelection();
137 std::string user = DEFAULT_ADMIN_USERNAME;
138 if((i = searchUsersDatabaseForUsername(user)) == NOT_FOUND_IN_DATABASE)
140 __SS__ <<
"user: " << user <<
" is not found. This should be impossible!"
142 __COUT_ERR__ << ss.str();
145 else if(Users_[i].salt_ ==
147 securityType_ == SECURITY_TYPE_DIGEST_ACCESS)
153 [](
const std::string& nac,
const std::string& user) {
154 WebUsers::NACDisplayThread(nac, user);
156 Users_[i].getNewAccountCode(),
165 loadLoginFailureCounts();
173 __COUT__ <<
"Done with Web Users initialization!" << __E__;
182 std::ostringstream* out,
186 std::lock_guard<std::mutex> lock(webUserMutex_);
194 userInfo.cookieCode_,
195 &userInfo.groupPermissionLevelMap_,
198 !userInfo.automatedCommand_ ,
202 &userInfo.usernameWithLock_,
205 *out << userInfo.cookieCode_;
206 goto HANDLE_ACCESS_FAILURE;
212 i = searchUsersDatabaseForUserId(userInfo.uid_);
213 if(i >= Users_.size())
215 __SS__ <<
"Illegal uid encountered in cookie codes!? " << i << __E__;
216 ss <<
"User size = " << Users_.size() << __E__;
220 userInfo.username_ = Users_[i].username_;
221 userInfo.displayName_ = Users_[i].displayName_;
224 goto HANDLE_ACCESS_FAILURE;
228 HANDLE_ACCESS_FAILURE:
230 if(!userInfo.automatedCommand_)
231 __COUT_ERR__ <<
"Failed request (requestType = " << userInfo.requestType_
232 <<
"): " << out->str() << __E__;
243 userInfo.ip_ = cgi.getEnvironment().getRemoteAddr();
246 userInfo.username_ =
"";
247 userInfo.displayName_ =
"";
248 userInfo.usernameWithLock_ =
"";
262 std::ostringstream* out,
266 const std::string& wizardModeSequence )
272 if(userInfo.requireSecurity_ && userInfo.permissionsThreshold_ > 1)
278 if(isWizardMode && wizardModeSequence.size() < 8)
281 *out << WebUsers::REQ_NO_PERMISSION_RESPONSE;
282 __COUT__ <<
"User (@" << userInfo.ip_ <<
") has attempted requestType '"
283 << userInfo.requestType_
284 <<
"' which requires sufficient security enabled. Please enable the "
286 " sequence of at least 8 characters."
291 else if(!isWizardMode &&
292 (userInfo.username_ == WebUsers::DEFAULT_ADMIN_USERNAME ||
293 userInfo.username_ == WebUsers::DEFAULT_ITERATOR_USERNAME ||
294 userInfo.username_ == WebUsers::DEFAULT_STATECHANGER_USERNAME))
297 *out << WebUsers::REQ_NO_PERMISSION_RESPONSE;
298 __COUT__ <<
"User (@" << userInfo.ip_ <<
") has attempted requestType '"
299 << userInfo.requestType_
300 <<
"' which requires sufficient security enabled. Please enable "
302 " logins (Note: the user admin is disallowed in an attempt to "
303 "force personal accountability for edits)."
311 if(!userInfo.automatedCommand_)
313 __COUTT__ <<
"requestType ==========>>> " << userInfo.requestType_ << __E__;
314 __COUTTV__((
unsigned int)userInfo.permissionLevel_);
315 __COUTTV__((
unsigned int)userInfo.permissionsThreshold_);
319 if(!isWizardMode && !userInfo.allowNoUser_ &&
320 userInfo.cookieCode_.length() != WebUsers::COOKIE_CODE_LENGTH &&
322 userInfo.cookieCode_ ==
326 __COUT__ <<
"User (@" << userInfo.ip_
327 <<
") has invalid cookie code: " << userInfo.cookieCode_ << std::endl;
328 *out << WebUsers::REQ_NO_LOGIN_RESPONSE;
332 if(!userInfo.allowNoUser_ &&
333 (userInfo.permissionLevel_ == 0 ||
334 userInfo.permissionsThreshold_ == 0 ||
335 userInfo.permissionLevel_ < userInfo.permissionsThreshold_))
338 *out << WebUsers::REQ_NO_PERMISSION_RESPONSE;
339 __COUT_INFO__ <<
"User (@" << userInfo.ip_
340 <<
") has insufficient permissions for requestType '"
341 << userInfo.requestType_ <<
"' : user level is "
342 << (
unsigned int)userInfo.permissionLevel_ <<
", "
343 << (
unsigned int)userInfo.permissionsThreshold_ <<
" required."
351 userInfo.username_ = WebUsers::DEFAULT_ADMIN_USERNAME;
352 userInfo.displayName_ =
"Admin";
353 userInfo.usernameWithLock_ = userInfo.username_;
361 if(userInfo.allowNoUser_)
362 xmldoc->setHeader(WebUsers::REQ_ALLOW_NO_USER);
364 xmldoc->setHeader(userInfo.cookieCode_);
367 if(userInfo.allowNoUser_)
369 if(userInfo.automatedCommand_)
370 __COUTT__ <<
"Allowing anonymous access." << __E__;
381 if((userInfo.checkLock_ || userInfo.requireLock_) &&
382 userInfo.usernameWithLock_ !=
"" &&
383 userInfo.usernameWithLock_ != userInfo.username_)
385 *out << WebUsers::REQ_USER_LOCKOUT_RESPONSE;
386 __COUT_INFO__ <<
"User '" << userInfo.username_ <<
"' is locked out. '"
387 << userInfo.usernameWithLock_ <<
"' has lock." << std::endl;
391 if(userInfo.requireLock_ && userInfo.usernameWithLock_ != userInfo.username_)
393 *out << WebUsers::REQ_LOCK_REQUIRED_RESPONSE;
394 __COUT_INFO__ <<
"User '" << userInfo.username_
395 <<
"' must have lock to proceed. ('" << userInfo.usernameWithLock_
396 <<
"' has lock.)" << std::endl;
411 fn = (std::string)WEB_LOGIN_DB_PATH + (std::string)USERS_ACTIVE_SESSIONS_FILE;
412 __COUT__ << fn << __E__;
414 FILE* fp = fopen(fn.c_str(),
"w");
417 __COUT_ERR__ <<
"Error! Persistent active sessions could not be saved to file: "
423 fprintf(fp,
"%d\n", version);
424 for(
unsigned int i = 0; i < ActiveSessions_.size(); ++i)
432 fprintf(fp,
"%s\n", ActiveSessions_[i].cookieCode_.c_str());
433 fprintf(fp,
"%s\n", ActiveSessions_[i].ip_.c_str());
434 fprintf(fp,
"%lu\n", ActiveSessions_[i].userId_);
435 fprintf(fp,
"%lu\n", ActiveSessions_[i].sessionIndex_);
436 fprintf(fp,
"%ld\n", ActiveSessions_[i].startTime_);
439 __COUT__ <<
"Active Sessions saved with size " << ActiveSessions_.size() << __E__;
451 fn = (std::string)WEB_LOGIN_DB_PATH + (std::string)USERS_ACTIVE_SESSIONS_FILE;
452 __COUT__ << fn << __E__;
453 FILE* fp = fopen(fn.c_str(),
"r");
457 <<
"Persistent active sessions were not found to be loaded at file: " << fn
464 const int LINELEN = 1000;
466 fgets(line, LINELEN, fp);
467 sscanf(line,
"%d", &version);
470 __COUT__ <<
"Extracting active sessions..." << __E__;
472 while(fgets(line, LINELEN, fp))
475 line[strlen(line) - 1] =
'\0';
476 if(strlen(line) != COOKIE_CODE_LENGTH)
478 __COUT__ <<
"Illegal cookie code found: " << line << __E__;
484 ActiveSessions_.back().cookieCode_ = line;
486 fgets(line, LINELEN, fp);
488 line[strlen(line) - 1] =
'\0';
489 ActiveSessions_.back().ip_ = line;
491 fgets(line, LINELEN, fp);
492 sscanf(line,
"%lu", &(ActiveSessions_.back().userId_));
494 fgets(line, LINELEN, fp);
495 sscanf(line,
"%lu", &(ActiveSessions_.back().sessionIndex_));
497 fgets(line, LINELEN, fp);
498 sscanf(line,
"%ld", &(ActiveSessions_.back().startTime_));
501 __COUT__ <<
"Active Sessions loaded with size " << ActiveSessions_.size() << __E__;
505 fp = fopen(fn.c_str(),
"w");
514 bool WebUsers::loadDatabases()
519 const unsigned int LINE_LEN = 1000;
521 unsigned int i, si, c, len, f;
532 fn = (std::string)WEB_LOGIN_DB_PATH + (std::string)HASHES_DB_FILE;
533 __COUT__ << fn << __E__;
534 fp = fopen(fn.c_str(),
"r");
537 mkdir(((std::string)WEB_LOGIN_DB_PATH + (std::string)HASHES_DB_PATH).c_str(),
539 __COUT__ << ((std::string)WEB_LOGIN_DB_PATH + (std::string)HASHES_DB_PATH).c_str()
541 fp = fopen(fn.c_str(),
"w");
544 __COUT__ <<
"Hashes database created: " << fn << __E__;
546 saveToDatabase(fp, HASHES_DB_GLOBAL_STRING,
"", DB_SAVE_OPEN);
547 saveToDatabase(fp, HASHES_DB_GLOBAL_STRING,
"", DB_SAVE_CLOSE);
554 while(fgets(line, LINE_LEN, fp))
556 if(strlen(line) < SHA512_DIGEST_LENGTH)
562 for(i = 0; i < len; ++i)
570 while(i < len && line[i] !=
'<')
582 Hashes_.push_back(Hash());
583 Hashes_.back().hash_ = &line[si];
586 sscanf(&line[si],
"%ld", &Hashes_.back().accessTime_);
589 __COUT__ << Hashes_.size() <<
" Hashes found." << __E__;
603 fn = (std::string)WEB_LOGIN_DB_PATH + (std::string)USERS_DB_FILE;
604 fp = fopen(fn.c_str(),
"r");
607 mkdir(((std::string)WEB_LOGIN_DB_PATH + (std::string)USERS_DB_PATH).c_str(),
609 __COUT__ << ((std::string)WEB_LOGIN_DB_PATH + (std::string)USERS_DB_PATH).c_str()
611 fp = fopen(fn.c_str(),
"w");
614 __COUT__ <<
"Users database created: " << fn << __E__;
616 saveToDatabase(fp, USERS_DB_GLOBAL_STRING,
"", DB_SAVE_OPEN);
618 sprintf(nidStr,
"%lu", usersNextUserId_);
619 saveToDatabase(fp, USERS_DB_NEXT_UID_STRING, nidStr, DB_SAVE_OPEN_AND_CLOSE);
620 saveToDatabase(fp, USERS_DB_GLOBAL_STRING,
"", DB_SAVE_CLOSE);
624 DEFAULT_ADMIN_DISPLAY_NAME,
625 DEFAULT_ADMIN_EMAIL);
629 __COUT__ <<
"Users database: " << fn << __E__;
633 char salt[] =
"nextUserId";
634 while(fgets(line, LINE_LEN, fp))
636 if(strlen(line) < strlen(salt) * 2)
639 for(i = 0; i < strlen(salt); ++i)
640 if(line[i + 1] != salt[i])
643 if(i == strlen(salt))
648 while(i < LINE_LEN && line[i] !=
'\0' && line[i] !=
'<')
651 sscanf(&line[si],
"%lu", &usersNextUserId_);
656 __COUT__ <<
"Found Users database next user Id: " << usersNextUserId_ << __E__;
660 while(fgets(line, LINE_LEN, fp))
662 if(strlen(line) < 30)
670 __COUT__ <<
"Line buffer too small: " << len << __E__;
676 for(i = 0; i < len; ++i)
680 if(c == 0 || c % 2 == 1)
684 while(i < len && line[i] !=
'<')
696 Users_.push_back(User());
697 Users_.back().username_ = &line[si];
700 Users_.back().displayName_ = &line[si];
702 Users_.back().salt_ = &line[si];
704 sscanf(&line[si],
"%lu", &Users_.back().userId_);
707 std::map<std::string, permissionLevel_t>& lastPermissionsMap =
708 Users_.back().permissions_;
709 StringMacros::getMapFromString<permissionLevel_t>(
710 &line[si], lastPermissionsMap);
718 if(lastPermissionsMap.find(WebUsers::DEFAULT_USER_GROUP) ==
719 lastPermissionsMap.end())
722 <<
"User '" << Users_.back().username_
723 <<
"' is not a member of the default user group '"
724 << WebUsers::DEFAULT_USER_GROUP
725 <<
".' Assuming user account is inactive (permission "
727 << WebUsers::PERMISSION_LEVEL_INACTIVE <<
")." << __E__;
728 lastPermissionsMap[WebUsers::DEFAULT_USER_GROUP] =
729 WebUsers::PERMISSION_LEVEL_INACTIVE;
732 if(Users_.back().username_ == DEFAULT_ADMIN_USERNAME)
736 std::map<std::string ,
737 WebUsers::permissionLevel_t>
738 initPermissions = {{WebUsers::DEFAULT_USER_GROUP,
741 Users_.back().permissions_ = initPermissions;
745 sscanf(&line[si],
"%ld", &Users_.back().lastLoginAttempt_);
747 sscanf(&line[si],
"%ld", &Users_.back().accountCreationTime_);
749 sscanf(&line[si],
"%hhu", &Users_.back().loginFailureCount_);
751 sscanf(&line[si],
"%ld", &Users_.back().accessModifierTime());
753 Users_.back().loadModifierUsername(&line[si]);
755 Users_.back().email_ = &line[si];
762 __COUT__ << Users_.size() <<
" Users found." << __E__;
763 for(
size_t ii = 0; ii < Users_.size(); ++ii)
766 "User [" << Users_[ii].userId_ <<
"] \tName: " << std::left
767 << std::setfill(
' ') << std::setw(20) << Users_[ii].username_
768 <<
"\tDisplay Name: " << std::left << std::setfill(
' ') << std::setw(30)
769 << Users_[ii].displayName_ <<
"\tEmail: " << std::left
770 << std::setfill(
' ') << std::setw(30) << Users_[ii].email_
771 <<
"\tNAC: " << std::left << std::setfill(
' ') << std::setw(5)
772 << Users_[ii].getNewAccountCode()
773 <<
"\tFailedCount: " << (int)Users_[ii].loginFailureCount_
794 void WebUsers::saveLoginFailureCounts()
797 (std::string)WEB_LOGIN_DB_PATH + (std::string)USERS_LOGIN_FAILURE_FILE;
799 FILE* fp = fopen(fn.c_str(),
"w");
802 __COUT_ERR__ <<
"Failed to open login failure counts file for writing: " << fn
806 for(uint64_t i = 0; i < Users_.size(); ++i)
808 if(Users_[i].loginFailureCount_ > 0)
809 fprintf(fp,
"%lu %hhu\n", Users_[i].userId_, Users_[i].loginFailureCount_);
818 void WebUsers::loadLoginFailureCounts()
821 (std::string)WEB_LOGIN_DB_PATH + (std::string)USERS_LOGIN_FAILURE_FILE;
823 FILE* fp = fopen(fn.c_str(),
"r");
826 __COUT__ <<
"No login failure counts file found (this is normal on first run): "
832 for(
auto& user : Users_)
833 user.loginFailureCount_ = 0;
837 while(fscanf(fp,
"%lu %u", &uid, &count) == 2)
839 for(
auto& user : Users_)
841 if(user.userId_ == uid)
843 user.loginFailureCount_ = (
unsigned char)count;
849 __COUT__ <<
"Loaded login failure counts from " << fn << __E__;
854 void WebUsers::saveToDatabase(FILE* fp,
855 const std::string& field,
856 const std::string& value,
863 std::string newLine = addNewLine ?
"\n" :
"";
865 if(type == DB_SAVE_OPEN_AND_CLOSE)
872 else if(type == DB_SAVE_OPEN)
873 fprintf(fp,
"<%s>%s%s", field.c_str(), value.c_str(), newLine.c_str());
874 else if(type == DB_SAVE_CLOSE)
875 fprintf(fp,
"</%s>%s", field.c_str(), newLine.c_str());
884 bool WebUsers::saveDatabaseToFile(uint8_t db)
889 (std::string)WEB_LOGIN_DB_PATH +
890 ((db == DB_USERS) ? (std::string)USERS_DB_FILE : (std::string)HASHES_DB_FILE);
892 __COUT__ <<
"Save Database Filename: " << fn << __E__;
898 sprintf(dayAppend,
".%lu.bkup", time(0) / (3600 * 24));
899 std::string bkup_fn = (std::string)WEB_LOGIN_DB_PATH +
900 (std::string)WEB_LOGIN_BKUP_DB_PATH +
901 ((db == DB_USERS) ? (std::string)USERS_DB_FILE
902 : (std::string)HASHES_DB_FILE) +
903 (std::string)dayAppend;
905 __COUT__ <<
"Backup file: " << bkup_fn << __E__;
907 std::string shell_command =
"mv " + fn +
" " + bkup_fn;
908 system(shell_command.c_str());
911 FILE* fp = fopen(fn.c_str(),
"wb");
919 saveToDatabase(fp, USERS_DB_GLOBAL_STRING,
"", DB_SAVE_OPEN);
921 sprintf(fldStr,
"%lu", usersNextUserId_);
922 saveToDatabase(fp, USERS_DB_NEXT_UID_STRING, fldStr, DB_SAVE_OPEN_AND_CLOSE);
924 __COUT__ <<
"Saving " << Users_.size() <<
" Users." << __E__;
926 for(uint64_t i = 0; i < Users_.size(); ++i)
930 saveToDatabase(fp, USERS_DB_ENTRY_STRING,
"", DB_SAVE_OPEN,
false);
932 for(
unsigned int f = 0; f < WebUsers::UsersDatabaseEntryFields_.size(); ++f)
937 WebUsers::UsersDatabaseEntryFields_[f],
939 DB_SAVE_OPEN_AND_CLOSE,
943 WebUsers::UsersDatabaseEntryFields_[f],
944 Users_[i].displayName_,
945 DB_SAVE_OPEN_AND_CLOSE,
949 WebUsers::UsersDatabaseEntryFields_[f],
951 DB_SAVE_OPEN_AND_CLOSE,
955 sprintf(fldStr,
"%lu", Users_[i].userId_);
957 WebUsers::UsersDatabaseEntryFields_[f],
959 DB_SAVE_OPEN_AND_CLOSE,
964 WebUsers::UsersDatabaseEntryFields_[f],
968 DB_SAVE_OPEN_AND_CLOSE,
972 sprintf(fldStr,
"%lu", Users_[i].lastLoginAttempt_);
974 WebUsers::UsersDatabaseEntryFields_[f],
976 DB_SAVE_OPEN_AND_CLOSE,
981 sprintf(fldStr,
"%lu", Users_[i].accountCreationTime_);
983 WebUsers::UsersDatabaseEntryFields_[f],
985 DB_SAVE_OPEN_AND_CLOSE,
990 sprintf(fldStr,
"%hhu", Users_[i].loginFailureCount_);
992 WebUsers::UsersDatabaseEntryFields_[f],
994 DB_SAVE_OPEN_AND_CLOSE,
999 sprintf(fldStr,
"%lu", Users_[i].getModifierTime());
1001 WebUsers::UsersDatabaseEntryFields_[f],
1003 DB_SAVE_OPEN_AND_CLOSE,
1008 WebUsers::UsersDatabaseEntryFields_[f],
1009 Users_[i].getModifierUsername(),
1010 DB_SAVE_OPEN_AND_CLOSE,
1014 WebUsers::UsersDatabaseEntryFields_[f],
1016 DB_SAVE_OPEN_AND_CLOSE,
1020 saveToDatabase(fp, USERS_DB_ENTRY_STRING,
"", DB_SAVE_CLOSE);
1023 saveToDatabase(fp, USERS_DB_GLOBAL_STRING,
"", DB_SAVE_CLOSE);
1027 saveToDatabase(fp, HASHES_DB_GLOBAL_STRING,
"", DB_SAVE_OPEN);
1029 __COUT__ <<
"Saving " << Hashes_.size() <<
" Hashes." << __E__;
1030 for(uint64_t i = 0; i < Hashes_.size(); ++i)
1032 __COUT__ <<
"Saving " << Hashes_[i].hash_ <<
" Hash." << __E__;
1033 saveToDatabase(fp, HASHES_DB_ENTRY_STRING,
"", DB_SAVE_OPEN,
false);
1034 for(
unsigned int f = 0; f < WebUsers::HashesDatabaseEntryFields_.size(); ++f)
1038 WebUsers::HashesDatabaseEntryFields_[f],
1040 DB_SAVE_OPEN_AND_CLOSE,
1044 sprintf(fldStr,
"%lu", Hashes_[i].accessTime_);
1046 WebUsers::HashesDatabaseEntryFields_[f],
1048 DB_SAVE_OPEN_AND_CLOSE,
1052 saveToDatabase(fp, HASHES_DB_ENTRY_STRING,
"", DB_SAVE_CLOSE);
1055 saveToDatabase(fp, HASHES_DB_GLOBAL_STRING,
"", DB_SAVE_CLOSE);
1071 const std::string& displayName,
1072 const std::string& email)
1074 __COUT__ <<
"Creating account: " << username << __E__;
1077 if((i = searchUsersDatabaseForUsername(username)) != NOT_FOUND_IN_DATABASE ||
1078 username == WebUsers::DEFAULT_ITERATOR_USERNAME ||
1079 username == WebUsers::DEFAULT_STATECHANGER_USERNAME)
1082 __SS__ <<
"Username '" << username
1083 <<
"' already exists! Please choose a unique username." << __E__;
1088 if((i = searchUsersDatabaseForDisplayName(displayName)) != NOT_FOUND_IN_DATABASE)
1091 __SS__ <<
"Display Name '" << displayName
1092 <<
"' already exists! Please choose a unique display name." << __E__;
1097 Users_.push_back(
User());
1099 Users_.back().username_ = username;
1100 Users_.back().displayName_ = displayName;
1101 Users_.back().email_ = email;
1104 std::map<std::string , WebUsers::permissionLevel_t> initPermissions = {
1105 {WebUsers::DEFAULT_USER_GROUP,
1106 (Users_.size() ? WebUsers::PERMISSION_LEVEL_NOVICE
1109 Users_.back().permissions_ = initPermissions;
1110 Users_.back().userId_ = usersNextUserId_++;
1111 if(usersNextUserId_ >= ACCOUNT_ERROR_THRESHOLD)
1113 __SS__ <<
"usersNextUserId_ wrap around!! Too many users??? Notify Admins."
1116 usersNextUserId_ = 1;
1120 Users_.back().accountCreationTime_ = time(0);
1122 if(!saveDatabaseToFile(DB_USERS))
1124 __SS__ <<
"Failed to save User DB!" << __E__;
1135 bool WebUsers::deleteAccount(
const std::string& username,
const std::string& displayName)
1137 uint64_t i = searchUsersDatabaseForUsername(username);
1138 if(i == NOT_FOUND_IN_DATABASE)
1140 if(Users_[i].displayName_ != displayName)
1145 Users_.erase(Users_.begin() + i);
1148 return saveDatabaseToFile(DB_USERS);
1152 unsigned int WebUsers::hexByteStrToInt(
const char* h)
1155 char hs[3] = {h[0], h[1],
'\0'};
1156 sscanf(hs,
"%X", &rv);
1161 void WebUsers::intToHexStr(
unsigned char i,
char* h) { sprintf(h,
"%2.2X", i); }
1174 std::string& jumbledUser,
1175 const std::string& jumbledPw,
1176 std::string& newAccountCode,
1177 const std::string& ip)
1182 __COUT_ERR__ <<
"rejected ip: " << ip << __E__;
1183 return ACCOUNT_BLACKLISTED;
1188 if(!CareAboutCookieCodes_)
1192 newAccountCode = genCookieCode();
1199 if((i = searchLoginSessionDatabaseForUUID(uuid)) == NOT_FOUND_IN_DATABASE)
1201 __COUT_ERR__ <<
"Login attempt failed. Session uuid '" << uuid
1202 <<
"' is not found or inactive." << __E__;
1203 newAccountCode =
"1";
1205 incrementIpBlacklistCount(ip);
1207 return NOT_FOUND_IN_DATABASE;
1209 ++LoginSessions_[i].loginAttempts_;
1211 std::string user = dejumble(jumbledUser, LoginSessions_[i].id_);
1213 std::string pw = dejumble(jumbledPw, LoginSessions_[i].id_);
1216 if((i = searchUsersDatabaseForUsername(user)) == NOT_FOUND_IN_DATABASE)
1218 __COUT_ERR__ <<
"user: " << user <<
" is not found" << __E__;
1220 incrementIpBlacklistCount(ip);
1222 return NOT_FOUND_IN_DATABASE;
1225 ipBlacklistCounts_[ip] = 0;
1227 Users_[i].lastLoginAttempt_ = time(0);
1229 if(isInactiveForGroup(Users_[i].permissions_))
1231 __COUT_ERR__ <<
"User '" << user
1232 <<
"' account INACTIVE (could be due to failed logins)" << __E__;
1233 return ACCOUNT_INACTIVE;
1236 if(Users_[i].salt_ ==
"")
1238 __COUT__ <<
"First login attempt for user: " << user << __E__;
1240 if(newAccountCode != Users_[i].getNewAccountCode())
1242 __COUT__ <<
"New account code did not match: "
1243 << Users_[i].getNewAccountCode() <<
" != " << newAccountCode
1248 return NOT_FOUND_IN_DATABASE;
1254 while(!addToHashesDatabase(
1255 sha512(user, pw, Users_[i].salt_)))
1260 Users_[i].salt_ =
"";
1263 __COUT__ <<
"\tHash added: " << Hashes_.back().hash_ << __E__;
1267 std::string salt = Users_[i].salt_;
1269 if(searchHashesDatabaseForHash(sha512(user, pw, salt)) == NOT_FOUND_IN_DATABASE)
1271 __COUT__ <<
"Failed login for " << user <<
" with permissions "
1275 if(++Users_[i].loginFailureCount_ != (
unsigned char)-1)
1276 ++Users_[i].loginFailureCount_;
1278 if(Users_[i].loginFailureCount_ >= USERS_MAX_LOGIN_FAILURES)
1279 Users_[i].permissions_[WebUsers::DEFAULT_USER_GROUP] =
1280 WebUsers::PERMISSION_LEVEL_INACTIVE;
1282 __COUT_INFO__ <<
"User/pw for user '" << user
1283 <<
"' was not correct (Failed Attempt #"
1284 << (int)Users_[i].loginFailureCount_ <<
" of "
1285 << (
int)USERS_MAX_LOGIN_FAILURES <<
" allowed)." << __E__;
1287 __COUTV__(isInactiveForGroup(Users_[i].permissions_));
1288 if(isInactiveForGroup(Users_[i].permissions_))
1290 __COUT_INFO__ <<
"Account '" << user
1291 <<
"' has been marked inactive due to too many failed "
1292 "login attempts (Failed Attempt #"
1293 << (int)Users_[i].loginFailureCount_
1294 <<
")! Note only admins can reactivate accounts." << __E__;
1297 saveDatabaseToFile(DB_USERS);
1301 return NOT_FOUND_IN_DATABASE;
1305 __COUT_INFO__ <<
"Login successful for: " << user << __E__;
1308 if(Users_[i].loginFailureCount_ != 0)
1310 Users_[i].loginFailureCount_ = 0;
1311 saveLoginFailureCounts();
1315 for(
int h = 0; h < 2; ++h)
1317 std::string fn = (std::string)WEB_LOGIN_DB_PATH +
1318 (std::string)USERS_LOGIN_HISTORY_PATH +
1319 (h ? USERS_GLOBAL_HISTORY_FILE : Users_[i].username_) +
"." +
1320 (std::string)USERS_LOGIN_HISTORY_FILETYPE;
1327 (h ? USERS_GLOBAL_HISTORY_SIZE : USERS_LOGIN_HISTORY_SIZE))
1331 __COUT__ <<
"No previous login history found." << __E__;
1337 "Time=%lu Username=%s Permissions=%s UID=%lu",
1339 Users_[i].username_.c_str(),
1344 "Time=%lu displayName=%s Permissions=%s UID=%lu",
1346 Users_[i].displayName_.c_str(),
1349 histXml.addTextElementToData(PREF_XML_LOGIN_HISTORY_FIELD, entryStr);
1361 jumbledUser = Users_[i].displayName_;
1362 newAccountCode = createNewActiveSession(Users_[i].userId_,
1365 __COUTTV__(ActiveSessions_.size());
1367 if(ActiveSessions_.size() == 1)
1369 __COUT__ <<
"Attempting to auto-lock for first login user '"
1370 << Users_[i].username_ <<
"'... " << __E__;
1374 return Users_[i].userId_;
1385 std::string& cookieCode,
1387 const std::string& ip)
1391 __COUT_ERR__ <<
"rejected ip: " << ip << __E__;
1392 return NOT_FOUND_IN_DATABASE;
1397 if(!CareAboutCookieCodes_)
1401 cookieCode = genCookieCode();
1407 __COUT__ <<
"Rejecting cert logon with blank fingerprint" << __E__;
1409 incrementIpBlacklistCount(ip);
1411 return NOT_FOUND_IN_DATABASE;
1417 if((i = searchLoginSessionDatabaseForUUID(uuid)) == NOT_FOUND_IN_DATABASE)
1419 __COUT__ <<
"uuid: " << uuid <<
" is not found" << __E__;
1422 incrementIpBlacklistCount(ip);
1424 return NOT_FOUND_IN_DATABASE;
1426 ++LoginSessions_[i].loginAttempts_;
1428 email = getUserEmailFromFingerprint(email);
1429 __COUT__ <<
"DejumbledEmail = " << email << __E__;
1432 __COUT__ <<
"Rejecting logon with unknown fingerprint" << __E__;
1434 incrementIpBlacklistCount(ip);
1436 return NOT_FOUND_IN_DATABASE;
1440 if((i = searchUsersDatabaseForUserEmail(email)) == NOT_FOUND_IN_DATABASE)
1442 __COUT__ <<
"email: " << email <<
" is not found" << __E__;
1444 incrementIpBlacklistCount(ip);
1446 return NOT_FOUND_IN_DATABASE;
1449 ipBlacklistCounts_[ip] = 0;
1453 Users_[i].lastLoginAttempt_ = time(0);
1454 if(isInactiveForGroup(Users_[i].permissions_))
1456 __COUT__ <<
"User '" << user
1457 <<
"' account INACTIVE (could be due to failed logins)." << __E__;
1458 return NOT_FOUND_IN_DATABASE;
1461 if(Users_[i].salt_ ==
"")
1463 return NOT_FOUND_IN_DATABASE;
1466 __COUT__ <<
"Login successful for: " << user << __E__;
1469 if(Users_[i].loginFailureCount_ != 0)
1471 Users_[i].loginFailureCount_ = 0;
1472 saveLoginFailureCounts();
1476 for(
int h = 0; h < 2; ++h)
1478 std::string fn = (std::string)WEB_LOGIN_DB_PATH +
1479 (std::string)USERS_LOGIN_HISTORY_PATH +
1480 (h ? USERS_GLOBAL_HISTORY_FILE : Users_[i].username_) +
"." +
1481 (std::string)USERS_LOGIN_HISTORY_FILETYPE;
1488 (h ? USERS_GLOBAL_HISTORY_SIZE : USERS_LOGIN_HISTORY_SIZE))
1492 __COUT__ <<
"No previous login history found." << __E__;
1498 "Time=%lu Username=%s Permissions=%s UID=%lu",
1500 Users_[i].username_.c_str(),
1505 "Time=%lu displayName=%s Permissions=%s UID=%lu",
1507 Users_[i].displayName_.c_str(),
1510 histXml.addTextElementToData(PREF_XML_LOGIN_HISTORY_FIELD, entryStr);
1522 email = Users_[i].displayName_;
1523 cookieCode = createNewActiveSession(Users_[i].userId_,
1525 return Users_[i].userId_;
1531 uint64_t WebUsers::searchActiveSessionDatabaseForCookie(
1532 const std::string& cookieCode)
const
1535 for(; i < ActiveSessions_.size(); ++i)
1536 if(ActiveSessions_[i].cookieCode_ == cookieCode)
1538 return (i == ActiveSessions_.size()) ? NOT_FOUND_IN_DATABASE : i;
1556 uint64_t WebUsers::checkRemoteLoginVerification(std::string& cookieCode,
1559 const std::string& ip)
1561 __COUTVS__(2, cookieCode);
1562 remoteLoginVerificationEnabledBlackoutTime_ = 0;
1563 if(!remoteLoginVerificationSocket_)
1568 <<
"Illegal remote login verification port found in remote destination "
1570 <<
". Please check remote settings." << __E__;
1573 __COUT_INFO__ <<
"Instantiating Remote Gateway login verification socket! "
1574 "Validation requests will go to "
1578 remoteLoginVerificationSocket_ =
1579 std::make_unique<TransceiverSocket>(remoteLoginVerificationIP_);
1580 remoteLoginVerificationSocket_->initialize();
1582 remoteLoginVerificationSocketTarget_ = std::make_unique<Socket>(
1588 auto lockHandling = [
this, refresh](std::string username,
1589 uint64_t verifiedUserId) -> uint64_t {
1590 __COUTT__ <<
"lambda lockHandling()" << __E__;
1591 __COUTTV__(ActiveSessions_.size());
1592 __COUTTV__(RemoteSessions_.size());
1594 if((!CareAboutCookieCodes_)
1596 (usersUsernameWithLock_ == DEFAULT_ADMIN_USERNAME ||
1597 usersUsernameWithLock_ ==
"") &&
1598 usersUsernameWithLock_ != username)
1600 __COUT_INFO__ <<
"Overriding local user-with-lock '" << usersUsernameWithLock_
1601 <<
"' with remote user-with-lock 'Remote:" << username <<
"'"
1603 usersUsernameWithLock_ =
1607 getUserWithLock() +
" has locked REMOTE ots (overriding anonymous " +
1608 DEFAULT_ADMIN_USERNAME +
" user).");
1610 else if((ActiveSessions_.size() == 0 &&
1611 RemoteSessions_.size() == 1)
1612 && refresh && (usersUsernameWithLock_ ==
"") &&
1613 usersUsernameWithLock_ != username)
1615 __COUT_INFO__ <<
"Overriding local user-with-lock '" << usersUsernameWithLock_
1616 <<
"' with remote user-with-lock 'Remote:" << username <<
"'"
1618 usersUsernameWithLock_ =
1622 getUserWithLock() +
" has locked REMOTE ots (which was unlocked).");
1624 return verifiedUserId;
1629 __COUTTV__(cookieCode);
1630 __COUTTV__(RemoteSessions_.size());
1631 auto it = RemoteSessions_.find(cookieCode);
1632 if(it != RemoteSessions_.end())
1634 __COUTT__ <<
"cookieCode still active locally!" << __E__;
1635 __COUTTV__(it->second.userId_);
1636 uint64_t j = searchUsersDatabaseForUserId(it->second.userId_);
1637 if(j == NOT_FOUND_IN_DATABASE)
1639 __SS__ <<
"Could not find cache entry for remote user ID '"
1640 << it->second.userId_ <<
"' - notify admins." << __E__;
1643 __COUTTV__(Users_[j].username_);
1646 return lockHandling(Users_[j].username_, it->second.userId_);
1651 __COUTTV__(doNotGoRemote);
1653 return NOT_FOUND_IN_DATABASE;
1664 std::string request =
"loginVerify," + cookieCode +
"," + (refresh ?
"1" :
"0") +
1670 std::string requestResponseString = remoteLoginVerificationSocket_->sendAndReceive(
1671 *remoteLoginVerificationSocketTarget_, request, 10 );
1672 __COUTV__(requestResponseString);
1675 std::vector<std::string> rxParams =
1679 if(rxParams.size() != 6)
1681 __COUT__ <<
"Remote login response indicates rejected: " << rxParams.size()
1683 return NOT_FOUND_IN_DATABASE;
1695 __COUTTV__(rxParams[2]);
1696 __COUTTV__(usersUsernameWithLock_);
1699 std::string username = rxParams[3];
1700 __COUTTV__(username);
1701 uint64_t j = searchUsersDatabaseForUsername(username);
1702 if(j == NOT_FOUND_IN_DATABASE)
1704 __COUT_INFO__ <<
"Creating User entry for remote user '" << username
1705 <<
"' in local user list to track user preferences." << __E__;
1709 j = Users_.size() - 1;
1712 Users_[j].lastLoginAttempt_ = time(0);
1713 Users_[j].setModifier(
"REMOTE_GATEWAY");
1718 .permissions_.clear();
1720 Users_[j].permissions_);
1722 __COUTV__(Users_[j].username_);
1723 __COUTV__(Users_[j].userId_);
1727 cookieCode = rxParams[0];
1728 __COUTTV__(cookieCode);
1729 ActiveSession& newRemoteSession =
1730 RemoteSessions_[cookieCode];
1731 newRemoteSession.cookieCode_ = cookieCode;
1732 newRemoteSession.ip_ = ip;
1733 newRemoteSession.userId_ = Users_[j].userId_;
1734 sscanf(rxParams[5].c_str(),
"%lu", &newRemoteSession.sessionIndex_);
1735 newRemoteSession.startTime_ = time(0);
1738 return lockHandling(Users_[j].username_, Users_[j].userId_);
1747 if((u = searchUsersDatabaseForUsername(username)) == NOT_FOUND_IN_DATABASE)
1757 __COUTT__ <<
"isUserIdActive? " << uid << __E__;
1760 for(
const auto& remoteSession : RemoteSessions_)
1761 if(remoteSession.second.userId_ == uid)
1766 for(; i < ActiveSessions_.size(); ++i)
1767 if(ActiveSessions_[i].userId_ == uid)
1775 uint64_t WebUsers::searchUsersDatabaseForUsername(
const std::string& username)
const
1778 for(; i < Users_.size(); ++i)
1779 if(Users_[i].username_ == username)
1781 return (i == Users_.size()) ? NOT_FOUND_IN_DATABASE : i;
1787 uint64_t WebUsers::searchUsersDatabaseForDisplayName(
const std::string& displayName)
const
1790 for(; i < Users_.size(); ++i)
1791 if(Users_[i].displayName_ == displayName)
1793 return (i == Users_.size()) ? NOT_FOUND_IN_DATABASE : i;
1799 uint64_t WebUsers::searchUsersDatabaseForUserEmail(
const std::string& useremail)
const
1802 for(; i < Users_.size(); ++i)
1803 if(Users_[i].email_ == useremail)
1805 return (i == Users_.size()) ? NOT_FOUND_IN_DATABASE : i;
1811 uint64_t WebUsers::searchUsersDatabaseForUserId(uint64_t uid)
const
1814 for(; i < Users_.size(); ++i)
1815 if(Users_[i].userId_ == uid)
1817 return (i == Users_.size()) ? NOT_FOUND_IN_DATABASE : i;
1823 uint64_t WebUsers::searchLoginSessionDatabaseForUUID(
const std::string& uuid)
const
1826 for(; i < LoginSessions_.size(); ++i)
1827 if(LoginSessions_[i].uuid_ == uuid)
1829 return (i == LoginSessions_.size()) ? NOT_FOUND_IN_DATABASE : i;
1835 uint64_t WebUsers::searchHashesDatabaseForHash(
const std::string& hash)
1839 for(; i < Hashes_.size(); ++i)
1840 if(Hashes_[i].hash_ == hash)
1845 if(i < Hashes_.size())
1846 Hashes_[i].accessTime_ =
1847 ((time(0) + (rand() % 2 ? 1 : -1) * (rand() % 30 * 24 * 60 * 60)) &
1848 0x0FFFFFFFFFE000000);
1853 return (i == Hashes_.size()) ? NOT_FOUND_IN_DATABASE : i;
1860 bool WebUsers::addToHashesDatabase(
const std::string& hash)
1862 if(searchHashesDatabaseForHash(hash) != NOT_FOUND_IN_DATABASE)
1864 __COUT__ <<
"Hash collision: " << hash << __E__;
1867 Hashes_.push_back(Hash());
1868 Hashes_.back().hash_ = hash;
1869 Hashes_.back().accessTime_ =
1870 ((time(0) + (rand() % 2 ? 1 : -1) * (rand() % 30 * 24 * 60 * 60)) &
1871 0x0FFFFFFFFFE000000);
1874 return saveDatabaseToFile(DB_HASHES);
1879 std::string WebUsers::genCookieCode()
1882 std::string cc =
"";
1883 for(uint32_t i = 0; i < COOKIE_CODE_LENGTH / 2; ++i)
1885 intToHexStr(rand(), hexStr);
1895 std::string WebUsers::createNewActiveSession(uint64_t uid,
1896 const std::string& ip,
1900 ActiveSessions_.push_back(ActiveSession());
1901 ActiveSessions_.back().cookieCode_ = genCookieCode();
1902 ActiveSessions_.back().ip_ = ip;
1903 ActiveSessions_.back().userId_ = uid;
1904 ActiveSessions_.back().startTime_ = time(0);
1907 ActiveSessions_.back().sessionIndex_ = asIndex;
1912 for(uint64_t j = 0; j < ActiveSessions_.size(); ++j)
1913 if(ActiveSessions_[j].userId_ == uid &&
1914 max < ActiveSessions_[j].sessionIndex_)
1915 max = ActiveSessions_[j].sessionIndex_;
1917 ActiveSessions_.back().sessionIndex_ = (max ? max + 1 : 1);
1920 return ActiveSessions_.back().cookieCode_;
1947 std::string WebUsers::refreshCookieCode(
unsigned int i,
bool enableRefresh)
1950 for(uint64_t j = ActiveSessions_.size() - 1; j != (uint64_t)-1;
1952 if(ActiveSessions_[j].userId_ == ActiveSessions_[i].userId_ &&
1953 ActiveSessions_[j].sessionIndex_ ==
1954 ActiveSessions_[i].sessionIndex_)
1959 if(enableRefresh && (time(0) - ActiveSessions_[j].startTime_ >
1960 ACTIVE_SESSION_EXPIRATION_TIME / 2))
1964 ActiveSessions_[j].startTime_ =
1965 time(0) - ACTIVE_SESSION_EXPIRATION_TIME +
1966 ACTIVE_SESSION_COOKIE_OVERLAP_TIME;
1972 return createNewActiveSession(ActiveSessions_[i].userId_,
1973 ActiveSessions_[i].ip_,
1974 ActiveSessions_[i].sessionIndex_);
1977 return ActiveSessions_[j].cookieCode_;
1989 std::string& cookieCode,
1990 std::string& username)
1992 if(!CareAboutCookieCodes_)
1999 if(!ActiveSessions_.size())
2000 return NOT_FOUND_IN_DATABASE;
2005 if((i = searchLoginSessionDatabaseForUUID(uuid)) == NOT_FOUND_IN_DATABASE)
2007 __COUT__ <<
"uuid not found: " << uuid << __E__;
2008 return NOT_FOUND_IN_DATABASE;
2012 dejumble(username, LoginSessions_[i].id_);
2015 if((i = searchActiveSessionDatabaseForCookie(cookieCode)) == NOT_FOUND_IN_DATABASE)
2017 __COUT__ <<
"Cookie code not found" << __E__;
2018 return NOT_FOUND_IN_DATABASE;
2022 if((j = searchUsersDatabaseForUserId(ActiveSessions_[i].userId_)) ==
2023 NOT_FOUND_IN_DATABASE)
2025 __COUT__ <<
"User ID not found" << __E__;
2026 return NOT_FOUND_IN_DATABASE;
2030 if(Users_[j].username_ != username)
2032 __COUT__ <<
"cookieCode: " << cookieCode <<
" was.." << __E__;
2033 __COUT__ <<
"username: " << username <<
" is not found" << __E__;
2034 return NOT_FOUND_IN_DATABASE;
2037 username = Users_[j].displayName_;
2038 cookieCode = refreshCookieCode(i);
2039 return Users_[j].userId_;
2048 std::vector<uint64_t> uniqueAsi;
2051 for(i = 0; i < ActiveSessions_.size(); ++i)
2052 if(ActiveSessions_[i].userId_ == uid)
2057 for(j = 0; j < uniqueAsi.size(); ++j)
2058 if(uniqueAsi[j] == ActiveSessions_[i].sessionIndex_)
2065 uniqueAsi.push_back(ActiveSessions_[i].sessionIndex_);
2068 __COUT__ <<
"Found " << uniqueAsi.size() <<
" active sessions for uid " << uid
2071 return uniqueAsi.size();
2087 if(time(0) > ipSecurityLastLoadTime_ +
2090 ipSecurityLastLoadTime_ = time(0);
2091 loadIPAddressSecurity();
2094 for(
const auto& acceptIp : ipAccessAccept_)
2097 __COUTV__(acceptIp);
2100 for(
const auto& rejectIp : ipAccessReject_)
2103 __COUTV__(rejectIp);
2106 for(
const auto& blacklistIp : ipAccessBlacklist_)
2109 __COUTV__(blacklistIp);
2119 void WebUsers::incrementIpBlacklistCount(
const std::string& ip)
2121 if(ipAccessBlacklist_.find(ip) != ipAccessBlacklist_.end())
2125 auto it = ipBlacklistCounts_.find(ip);
2126 if(it == ipBlacklistCounts_.end())
2128 __COUT__ <<
"First error for ip '" << ip <<
"'" << __E__;
2129 ipBlacklistCounts_[ip] = 1;
2135 if(it->second >= IP_BLACKLIST_COUNT_THRESHOLD)
2137 __COUT_WARN__ <<
"Adding IP '" << ip <<
"' to blacklist!" << __E__;
2139 ipAccessBlacklist_.emplace(ip);
2140 __COUTV__(ipAccessBlacklist_.size());
2143 FILE* fp = fopen((IP_BLACKLIST_FILE).c_str(),
"a");
2146 __COUT_ERR__ <<
"IP black list file '" << IP_BLACKLIST_FILE
2147 <<
"' could not be opened." << __E__;
2150 fprintf(fp,
"%s\n", ip.c_str());
2161 if((i = searchUsersDatabaseForUserId(uid)) == NOT_FOUND_IN_DATABASE)
2163 return Users_[i].displayName_;
2171 if((i = searchUsersDatabaseForUserId(uid)) == NOT_FOUND_IN_DATABASE)
2173 return Users_[i].username_;
2188 bool logoutOtherUserSessions,
2190 const std::string& ip)
2195 if((i = searchActiveSessionDatabaseForCookie(cookieCode)) == NOT_FOUND_IN_DATABASE)
2197 __COUT__ <<
"Cookie code not found" << __E__;
2199 incrementIpBlacklistCount(ip);
2201 return NOT_FOUND_IN_DATABASE;
2204 ipBlacklistCounts_[ip] = 0;
2207 if(ActiveSessions_[i].ip_ != ip)
2209 __COUT__ <<
"IP does not match active session" << __E__;
2210 return NOT_FOUND_IN_DATABASE;
2219 uint64_t asi = ActiveSessions_[i].sessionIndex_;
2220 uint64_t uid = ActiveSessions_[i].userId_;
2223 uint64_t logoutCount = 0;
2226 while(i < ActiveSessions_.size())
2228 if((logoutOtherUserSessions && ActiveSessions_[i].userId_ == uid &&
2229 ActiveSessions_[i].sessionIndex_ != asi) ||
2230 (!logoutOtherUserSessions && ActiveSessions_[i].userId_ == uid &&
2231 ActiveSessions_[i].sessionIndex_ == asi))
2233 __COUT__ <<
"Logging out of active session " << ActiveSessions_[i].userId_
2234 <<
"-" << ActiveSessions_[i].sessionIndex_ << __E__;
2235 ActiveSessions_.erase(ActiveSessions_.begin() + i);
2242 __COUT__ <<
"Found and removed active session count = " << logoutCount << __E__;
2261 std::string& cookieCode,
2262 std::map<std::string /*groupName*/, WebUsers::permissionLevel_t>* userPermissions,
2264 const std::string& ip,
2267 std::string* userWithLock,
2268 uint64_t* userSessionIndex)
2276 __COUT_ERR__ <<
"User IP rejected." << __E__;
2277 cookieCode = REQ_NO_LOGIN_RESPONSE;
2283 uint64_t i, j, userId = NOT_FOUND_IN_DATABASE, userSession = NOT_FOUND_IN_DATABASE;
2285 __COUTTV__(CareAboutCookieCodes_);
2286 __COUTT__ <<
"refresh=" << refresh <<
", doNotGoRemote=" << doNotGoRemote << __E__;
2287 __COUTVS__(2, cookieCode);
2291 __COUTTV__(localEnableRemoteLogin);
2296 if(localEnableRemoteLogin &&
2297 time(0) > remoteLoginVerificationEnabledBlackoutTime_ &&
2298 (userId = checkRemoteLoginVerification(
2299 cookieCode, refresh, doNotGoRemote, ip)) != NOT_FOUND_IN_DATABASE)
2302 __COUTT__ <<
"Remote login session verified." << __E__;
2303 userSession = RemoteSessions_.at(cookieCode).sessionIndex_;
2308 std::string err =
"";
2313 catch(
const std::exception& e)
2318 __COUT_WARN__ <<
"Ignoring exception during remote login verification. " << err
2322 if(!CareAboutCookieCodes_ && localEnableRemoteLogin &&
2323 remoteLoginVerificationEnabledBlackoutTime_ == 0)
2326 localEnableRemoteLogin =
false;
2327 remoteLoginVerificationEnabledBlackoutTime_ = time(0) + 10;
2328 __COUT_INFO__ <<
"Disabled remote login until "
2330 remoteLoginVerificationEnabledBlackoutTime_)
2334 __COUTTV__(localEnableRemoteLogin);
2336 if(localEnableRemoteLogin && userId == NOT_FOUND_IN_DATABASE)
2337 __COUTT__ <<
"Remote login verification failed." << __E__;
2339 if(!CareAboutCookieCodes_ &&
2340 userId == NOT_FOUND_IN_DATABASE)
2344 std::map<std::string , WebUsers::permissionLevel_t>(
2349 *userWithLock = usersUsernameWithLock_;
2350 if(userSessionIndex)
2351 *userSessionIndex = 0;
2353 if(cookieCode.size() != COOKIE_CODE_LENGTH)
2354 cookieCode = genCookieCode();
2356 if(localEnableRemoteLogin)
2358 cookieCode = WebUsers::
2366 if(userId == NOT_FOUND_IN_DATABASE)
2369 if((i = searchActiveSessionDatabaseForCookie(cookieCode)) ==
2370 NOT_FOUND_IN_DATABASE)
2372 __COUT_ERR__ <<
"Cookie code not found" << __E__;
2373 cookieCode = REQ_NO_LOGIN_RESPONSE;
2375 incrementIpBlacklistCount(ip);
2380 ipBlacklistCounts_[ip] = 0;
2383 if(ip !=
"0" && ActiveSessions_[i].ip_ != ip)
2385 __COUTV__(ActiveSessions_[i].ip_);
2387 __COUT_ERR__ <<
"IP does not match active session." << __E__;
2388 cookieCode = REQ_NO_LOGIN_RESPONSE;
2392 userId = ActiveSessions_[i].userId_;
2393 userSession = ActiveSessions_[i].sessionIndex_;
2394 cookieCode = refreshCookieCode(i, refresh);
2395 __COUTT__ <<
"Login session verified." << __E__;
2401 if((j = searchUsersDatabaseForUserId(userId)) == NOT_FOUND_IN_DATABASE)
2403 __COUT_ERR__ <<
"After login verification, User ID not found! Notify admins."
2405 cookieCode = REQ_NO_LOGIN_RESPONSE;
2409 std::map<std::string , WebUsers::permissionLevel_t> tmpPerm =
2412 if(isInactiveForGroup(tmpPerm))
2414 __COUTT__ <<
"Inactive user identified." << __E__;
2415 cookieCode = REQ_NO_PERMISSION_RESPONSE;
2421 *userPermissions = tmpPerm;
2425 *userWithLock = usersUsernameWithLock_;
2426 if(userSessionIndex)
2427 *userSessionIndex = userSession;
2444 if(loggedOutUsernames)
2446 for(i = 0; i < UsersLoggedOutUsernames_.size(); ++i)
2447 loggedOutUsernames->push_back(UsersLoggedOutUsernames_[i]);
2448 UsersLoggedOutUsernames_.clear();
2452 for(i = 0; i < LoginSessions_.size(); ++i)
2453 if(LoginSessions_[i].startTime_ + LOGIN_SESSION_EXPIRATION_TIME <
2455 LoginSessions_[i].loginAttempts_ > LOGIN_SESSION_ATTEMPTS_MAX)
2457 __COUT__ <<
"Found expired login sessions: #" << (i + 1) <<
" of "
2458 << LoginSessions_.size() << __E__;
2462 LoginSessions_.erase(LoginSessions_.begin() + i);
2475 for(i = 0; i < ActiveSessions_.size(); ++i)
2476 if(ActiveSessions_[i].startTime_ + ACTIVE_SESSION_EXPIRATION_TIME <=
2486 __COUT__ <<
"Found expired active sessions: #" << (i + 1) <<
" of "
2487 << ActiveSessions_.size() << __E__;
2488 __COUTTV__(ActiveSessions_[i].cookieCode_);
2490 tmpUid = ActiveSessions_[i].userId_;
2491 ActiveSessions_.erase(ActiveSessions_.begin() + i);
2496 if(loggedOutUsernames)
2497 loggedOutUsernames->push_back(
2498 Users_[searchUsersDatabaseForUserId(tmpUid)].username_);
2500 UsersLoggedOutUsernames_.push_back(
2501 Users_[searchUsersDatabaseForUserId(tmpUid)].username_);
2522 if(CareAboutCookieCodes_ && usersUsernameWithLock_ !=
"" &&
2530 usersUsernameWithLock_ =
"";
2540 std::vector<std::string> toErase;
2541 for(
const auto& remoteSession : RemoteSessions_)
2542 if(remoteSession.second.startTime_ + ACTIVE_SESSION_EXPIRATION_TIME / 4 <=
2545 __COUT__ <<
"Found expired remote active sessions: #" << remoteSession.first
2546 <<
" in " << RemoteSessions_.size() << __E__;
2547 toErase.push_back(remoteSession.first);
2549 for(
const auto& eraseId : toErase)
2550 RemoteSessions_.erase(eraseId);
2561 const std::string& ip)
2567 for(; i < LoginSessions_.size(); ++i)
2568 if(LoginSessions_[i].uuid_ == UUID)
2571 if(i != LoginSessions_.size())
2573 __COUT_ERR__ <<
"UUID: " << UUID <<
" is not unique" << __E__;
2579 LoginSessions_.back().uuid_ = UUID;
2583 std::string sid =
"";
2584 for(i = 0; i < SESSION_ID_LENGTH / 2; ++i)
2586 intToHexStr(rand(), hexStr);
2589 LoginSessions_.back().id_ = sid;
2590 LoginSessions_.back().ip_ = ip;
2591 LoginSessions_.back().startTime_ = time(0);
2592 LoginSessions_.back().loginAttempts_ = 0;
2602 std::string WebUsers::sha512(
const std::string& user,
2603 const std::string& password,
2606 SHA512_CTX sha512_context;
2611 SHA512_Init(&sha512_context);
2613 for(
unsigned int i = 0; i < 8; ++i)
2614 sha512_context.h[i] += rand();
2616 for(
unsigned int i = 0; i <
sizeof(SHA512_CTX); ++i)
2618 intToHexStr((uint8_t)(((uint8_t*)(&sha512_context))[i]), hexStr);
2620 salt.append(hexStr);
2628 for(
unsigned int i = 0; i <
sizeof(SHA512_CTX); ++i)
2629 ((uint8_t*)(&sha512_context))[i] = hexByteStrToInt(&(salt.c_str()[i * 2]));
2632 std::string strToHash = salt + user + password;
2635 unsigned char hash[SHA512_DIGEST_LENGTH];
2637 char retHash[SHA512_DIGEST_LENGTH * 2 + 1];
2641 SHA512_Update(&sha512_context, strToHash.c_str(), strToHash.length());
2643 SHA512_Final(hash, &sha512_context);
2647 for(i = 0; i < SHA512_DIGEST_LENGTH; i++)
2648 sprintf(retHash + (i * 2),
"%02x", hash[i]);
2651 retHash[SHA512_DIGEST_LENGTH * 2] =
'\0';
2662 std::string WebUsers::dejumble(
const std::string& u,
const std::string& s)
2664 if(s.length() != SESSION_ID_LENGTH)
2667 const int ss = s.length() / 2;
2668 int p = hexByteStrToInt(&(s.c_str()[0])) % ss;
2669 int n = hexByteStrToInt(&(s.c_str()[p * 2])) % ss;
2670 int len = (hexByteStrToInt(&(u.c_str()[p * 2])) - p - n + ss * 3) % ss;
2672 std::vector<bool> x(ss);
2673 for(
int i = 0; i < ss; ++i)
2677 int c = hexByteStrToInt(&(u.c_str()[p * 2]));
2679 std::string user =
"";
2681 for(
int l = 0; l < len; ++l)
2683 p = (p + hexByteStrToInt(&(s.c_str()[p * 2]))) % ss;
2687 n = hexByteStrToInt(&(s.c_str()[p * 2]));
2688 user.append(1, (hexByteStrToInt(&(u.c_str()[p * 2])) - c - n + ss * 4) % ss);
2689 c = hexByteStrToInt(&(u.c_str()[p * 2]));
2698 std::map<std::string , WebUsers::permissionLevel_t>
2701 uint64_t userIndex = searchUsersDatabaseForUserId(uid);
2702 if(userIndex < Users_.size())
2703 return Users_[userIndex].permissions_;
2706 std::map<std::string , WebUsers::permissionLevel_t> retErrorMap;
2707 retErrorMap[WebUsers::DEFAULT_USER_GROUP] = WebUsers::PERMISSION_LEVEL_INACTIVE;
2744 WebUsers::permissionLevel_t WebUsers::getPermissionLevelForGroup(
2745 const std::map<std::string /*groupName*/, WebUsers::permissionLevel_t>& permissionMap,
2746 const std::string& groupName)
2748 auto it = permissionMap.find(groupName);
2749 if(it == permissionMap.end())
2751 __COUT__ <<
"Group name '" << groupName
2752 <<
"' not found - assuming inactive user in this group." << __E__;
2753 return WebUsers::PERMISSION_LEVEL_INACTIVE;
2759 bool WebUsers::isInactiveForGroup(
2760 const std::map<std::string /*groupName*/, WebUsers::permissionLevel_t>& permissionMap,
2761 const std::string& groupName)
2763 return getPermissionLevelForGroup(permissionMap, groupName) ==
2764 WebUsers::PERMISSION_LEVEL_INACTIVE;
2768 bool WebUsers::isAdminForGroup(
2769 const std::map<std::string /*groupName*/, WebUsers::permissionLevel_t>& permissionMap,
2770 const std::string& groupName)
2772 return getPermissionLevelForGroup(permissionMap, groupName) ==
2779 std::string WebUsers::getTooltipFilename(
const std::string& username,
2780 const std::string& srcFile,
2781 const std::string& srcFunc,
2782 const std::string& srcId)
2784 std::string filename = (std::string)WEB_LOGIN_DB_PATH + TOOLTIP_DB_PATH +
"/";
2788 mkdir(((std::string)WEB_LOGIN_DB_PATH).c_str(), 0755);
2789 mkdir(((std::string)WEB_LOGIN_DB_PATH + USERS_DB_PATH).c_str(), 0755);
2790 mkdir(filename.c_str(), 0755);
2792 for(
const char& c : username)
2794 (c >=
'a' && c <=
'z') || (c >=
'A' && c <=
'Z') || (c >=
'0' && c <=
'9'))
2799 mkdir(filename.c_str(), 0755);
2801 for(
const char& c : srcFile)
2803 (c >=
'a' && c <=
'z') || (c >=
'A' && c <=
'Z') || (c >=
'0' && c <=
'9'))
2806 for(
const char& c : srcFunc)
2808 (c >=
'a' && c <=
'z') || (c >=
'A' && c <=
'Z') || (c >=
'0' && c <=
'9'))
2811 for(
const char& c : srcId)
2813 (c >=
'a' && c <=
'z') || (c >=
'A' && c <=
'Z') || (c >=
'0' && c <=
'9'))
2820 std::string ots::WebUsers::getUserEmailFromFingerprint(
const std::string& fingerprint)
2822 __COUT__ <<
"Checking if user fingerprint " << fingerprint <<
" is in memory database"
2824 if(certFingerprints_.count(fingerprint))
2826 return certFingerprints_[fingerprint];
2829 __COUT__ <<
"Going to read credential database " << WEB_LOGIN_CERTDATA_PATH << __E__;
2830 std::ifstream f(WEB_LOGIN_CERTDATA_PATH);
2838 if(fp !=
"NOKEY" && fp !=
"")
2840 __COUT__ <<
"Adding user " << email <<
" to list with fingerprint " << fp
2842 certFingerprints_[fp] = email;
2848 remove(WEB_LOGIN_CERTDATA_PATH.c_str());
2851 __COUT__ <<
"Checking again if fingerprint is in memory database" << __E__;
2852 if(certFingerprints_.count(fingerprint))
2854 return certFingerprints_[fingerprint];
2857 __COUT__ <<
"Could not match fingerprint, returning null email" << __E__;
2866 const std::string& srcFile,
2867 const std::string& srcFunc,
2868 const std::string& srcId,
2870 bool temporarySilence)
2872 std::string filename;
2873 bool isForAll = (srcFile ==
"ALL" && srcFunc ==
"ALL" && srcId ==
"ALL");
2877 __COUT__ <<
"Disabling ALL tooltips for user '" << username <<
"' is now set to "
2878 << doNeverShow <<
" (temporarySilence=" << temporarySilence <<
")"
2880 filename = getTooltipFilename(username, SILENCE_ALL_TOOLTIPS_FILENAME,
"",
"");
2884 filename = getTooltipFilename(username, srcFile, srcFunc, srcId);
2885 __COUT__ <<
"Setting tooltip never show for user '" << username <<
"' to "
2886 << doNeverShow <<
" (temporarySilence=" << temporarySilence <<
")"
2891 __COUTTV__(doNeverShow);
2892 __COUTTV__(temporarySilence);
2894 __COUTTV__(srcFunc);
2895 __COUTTV__(srcFile);
2896 __COUTTV__(filename);
2899 FILE* fp = fopen(filename.c_str(),
"w");
2902 if(temporarySilence)
2905 time(0) + 7 * 24 * 60 * 60);
2906 else if(!isForAll && doNeverShow && username == WebUsers::DEFAULT_ADMIN_USERNAME)
2909 fprintf(fp,
"%ld", time(0) + 30 * 24 * 60 * 60);
2911 __COUT__ <<
"User '" << username
2912 <<
"' may be a shared account, so max silence duration for tooltips "
2913 "is 30 days. Silencing now."
2917 fputc(doNeverShow ?
'1' :
'0', fp);
2921 __COUT_ERR__ <<
"Big problem with tooltips! File not accessible: " << filename
2934 const std::string& srcFile,
2935 const std::string& srcFunc,
2936 const std::string& srcId)
2938 if(srcId ==
"ALWAYS")
2941 xmldoc->addTextElementToData(
"ShowTooltip",
"1");
2946 std::string silencefilename =
2947 getTooltipFilename(username, SILENCE_ALL_TOOLTIPS_FILENAME,
"",
"");
2951 __COUTTV__(username);
2953 __COUTTV__(srcFunc);
2954 __COUTTV__(srcFile);
2955 __COUTTV__(silencefilename);
2958 FILE* silencefp = fopen(silencefilename.c_str(),
"r");
2959 if(silencefp != NULL)
2963 fgets(line, 100, silencefp);
2964 sscanf(line,
"%ld", &val);
2968 xmldoc->addTextElementToData(
"ShowTooltip",
"0");
2974 std::string filename = getTooltipFilename(username, srcFile, srcFunc, srcId);
2975 FILE* fp = fopen(filename.c_str(),
"r");
2980 fgets(line, 100, fp);
2981 sscanf(line,
"%ld", &val);
2984 __COUT__ <<
"tooltip value read = " << val <<
" vs time(0)=" << time(0) << __E__;
2988 xmldoc->addTextElementToData(
"ShowTooltip",
2989 val == 1 ?
"0" : (time(0) > val ?
"1" :
"0"));
2993 xmldoc->addTextElementToData(
"ShowTooltip",
"1");
3003 (
"rm -rf " + (std::string)WEB_LOGIN_DB_PATH + TOOLTIP_DB_PATH +
"/" + userNeedle)
3005 __COUT__ <<
"Successfully reset Tooltips for user " << userNeedle << __E__;
3013 std::string silencefilename = getTooltipFilename(
3014 username, SILENCE_ALL_TOOLTIPS_FILENAME,
"",
"");
3016 __COUTV__(silencefilename);
3017 FILE* silencefp = fopen(silencefilename.c_str(),
"w");
3018 if(silencefp != NULL)
3020 fputs(
"1", silencefp);
3051 bool includeAccounts,
3052 std::map<std::string /*groupName*/, WebUsers::permissionLevel_t>
3055 if(permissionMap.size() == 0)
3057 __COUTT__ <<
"Getting local permissions for user " << uid << __E__;
3062 if(isInactiveForGroup(permissionMap))
3065 uint64_t userIndex = searchUsersDatabaseForUserId(uid);
3066 __COUT__ <<
"Gettings settings for user: " << Users_[userIndex].username_ << __E__;
3068 std::string fn = (std::string)WEB_LOGIN_DB_PATH +
3069 (std::string)USERS_PREFERENCES_PATH + Users_[userIndex].username_ +
3070 "." + (std::string)USERS_PREFERENCES_FILETYPE;
3074 __COUT__ <<
"Preferences file: " << fn << __E__;
3078 __COUT__ <<
"Preferences are defaults." << __E__;
3080 xmldoc->addTextElementToData(PREF_XML_BGCOLOR_FIELD, PREF_XML_BGCOLOR_DEFAULT);
3081 xmldoc->addTextElementToData(PREF_XML_DBCOLOR_FIELD, PREF_XML_DBCOLOR_DEFAULT);
3082 xmldoc->addTextElementToData(PREF_XML_WINCOLOR_FIELD, PREF_XML_WINCOLOR_DEFAULT);
3083 xmldoc->addTextElementToData(PREF_XML_LAYOUT_FIELD, PREF_XML_LAYOUT_DEFAULT);
3087 __COUT__ <<
"Saved Preferences found." << __E__;
3092 if(includeAccounts && isAdminForGroup(permissionMap))
3094 __COUT__ <<
"Admin on our hands" << __E__;
3096 xmldoc->addTextElementToData(PREF_XML_ACCOUNTS_FIELD,
"");
3098 if(Users_.size() == 0)
3100 __COUT__ <<
"Missing users? Attempting to load database" << __E__;
3105 for(uint64_t i = 0; i < Users_.size(); ++i)
3108 "username", Users_[i].username_, PREF_XML_ACCOUNTS_FIELD);
3110 "display_name", Users_[i].displayName_, PREF_XML_ACCOUNTS_FIELD);
3112 if(Users_[i].email_.size() > i)
3115 "useremail", Users_[i].email_, PREF_XML_ACCOUNTS_FIELD);
3125 PREF_XML_ACCOUNTS_FIELD);
3128 "nac", Users_[i].getNewAccountCode().c_str(), PREF_XML_ACCOUNTS_FIELD);
3133 fn = (std::string)WEB_LOGIN_DB_PATH + (std::string)USERS_PREFERENCES_PATH +
3134 (std::string)SYSTEM_PREFERENCES_PREFIX +
"." +
3135 (std::string)USERS_PREFERENCES_FILETYPE;
3138 __COUT__ <<
"System Preferences are defaults." << __E__;
3140 xmldoc->addTextElementToData(PREF_XML_SYSLAYOUT_FIELD,
3141 PREF_XML_SYSLAYOUT_DEFAULT);
3145 __COUT__ <<
"Saved System Preferences found." << __E__;
3152 xmldoc->addTextElementToData(PREF_XML_PERMISSIONS_FIELD,
3156 xmldoc->addTextElementToData(PREF_XML_USERLOCK_FIELD, usersUsernameWithLock_);
3159 xmldoc->addTextElementToData(PREF_XML_USERNAME_FIELD,
getUsersUsername(uid));
3165 xmldoc->addTextElementToData(
"ots_remote_address",
3166 remoteLoginVerificationIP_ +
":" +
3175 const std::string& preferenceName,
3176 const std::string& preferenceValue)
3178 uint64_t userIndex = searchUsersDatabaseForUserId(uid);
3183 std::string safePreferenceName =
"";
3184 for(
const auto& c : preferenceName)
3185 if((c >=
'a' && c <=
'z') || (c >=
'A' && c <=
'Z') || (c >=
'0' && c <=
'9') ||
3186 (c >=
'-' || c <=
'_'))
3187 safePreferenceName += c;
3189 std::string dir = (std::string)WEB_LOGIN_DB_PATH +
3190 (std::string)USERS_PREFERENCES_PATH +
"generic_" +
3191 safePreferenceName +
"/";
3194 mkdir(dir.c_str(), 0755);
3196 std::string fn = Users_[userIndex].username_ +
"_" + safePreferenceName +
"." +
3197 (std::string)USERS_PREFERENCES_FILETYPE;
3199 __COUT__ <<
"Preferences file: " << (dir + fn) << __E__;
3201 FILE* fp = fopen((dir + fn).c_str(),
"w");
3204 fprintf(fp,
"%s", preferenceValue.c_str());
3208 __COUT_ERR__ <<
"Preferences file could not be opened for writing!" << __E__;
3216 const std::string& preferenceName,
3219 uint64_t userIndex = searchUsersDatabaseForUserId(uid);
3224 std::string safePreferenceName =
"";
3225 for(
const auto& c : preferenceName)
3226 if((c >=
'a' && c <=
'z') || (c >=
'A' && c <=
'Z') || (c >=
'0' && c <=
'9') ||
3227 (c >=
'-' || c <=
'_'))
3228 safePreferenceName += c;
3230 std::string dir = (std::string)WEB_LOGIN_DB_PATH +
3231 (std::string)USERS_PREFERENCES_PATH +
"generic_" +
3232 safePreferenceName +
"/";
3234 std::string fn = Users_[userIndex].username_ +
"_" + safePreferenceName +
"." +
3235 (std::string)USERS_PREFERENCES_FILETYPE;
3237 __COUT__ <<
"Preferences file: " << (dir + fn) << __E__;
3240 FILE* fp = fopen((dir + fn).c_str(),
"r");
3243 fseek(fp, 0, SEEK_END);
3244 const long size = ftell(fp);
3245 char* line =
new char
3249 fread(line, 1, size, fp);
3252 std::string retVal(line, size);
3255 __COUT__ <<
"Read value (sz = " << retVal.size() <<
") " << retVal << __E__;
3257 xmldoc->addTextElementToData(safePreferenceName, retVal);
3261 __COUT__ <<
"Using default value." << __E__;
3265 xmldoc->addTextElementToData(safePreferenceName,
"");
3272 const std::string& bgcolor,
3273 const std::string& dbcolor,
3274 const std::string& wincolor,
3275 const std::string& layout,
3276 const std::string& syslayout,
3277 const std::string& aliaslayout,
3278 const std::string& sysaliaslayout)
3280 std::map<std::string , WebUsers::permissionLevel_t> permissionMap =
3282 if(isInactiveForGroup(permissionMap))
3285 uint64_t userIndex = searchUsersDatabaseForUserId(uid);
3286 __COUT__ <<
"Changing settings for user: " << Users_[userIndex].username_ << __E__;
3288 std::string fn = (std::string)WEB_LOGIN_DB_PATH +
3289 (std::string)USERS_PREFERENCES_PATH + Users_[userIndex].username_ +
3290 "." + (std::string)USERS_PREFERENCES_FILETYPE;
3292 __COUT__ <<
"Preferences file: " << fn << __E__;
3295 prefXml.addTextElementToData(PREF_XML_BGCOLOR_FIELD, bgcolor);
3296 prefXml.addTextElementToData(PREF_XML_DBCOLOR_FIELD, dbcolor);
3297 prefXml.addTextElementToData(PREF_XML_WINCOLOR_FIELD, wincolor);
3298 prefXml.addTextElementToData(PREF_XML_LAYOUT_FIELD, layout);
3299 prefXml.addTextElementToData(PREF_XML_ALIAS_LAYOUT_FIELD, aliaslayout);
3304 if(!isAdminForGroup(permissionMap))
3308 fn = (std::string)WEB_LOGIN_DB_PATH + (std::string)USERS_PREFERENCES_PATH +
3309 (std::string)SYSTEM_PREFERENCES_PREFIX +
"." +
3310 (std::string)USERS_PREFERENCES_FILETYPE;
3313 sysPrefXml.addTextElementToData(PREF_XML_SYSLAYOUT_FIELD, syslayout);
3314 sysPrefXml.addTextElementToData(PREF_XML_SYSALIAS_LAYOUT_FIELD, sysaliaslayout);
3326 std::map<std::string , WebUsers::permissionLevel_t> permissionMap =
3332 __COUTV__(actingUser);
3334 __COUTV__(usersUsernameWithLock_);
3336 __COUTV__(username);
3337 __COUTV__(isUserActive);
3340 (isUserActive || !WebUsers::CareAboutCookieCodes_))
3342 if(!WebUsers::CareAboutCookieCodes_ && !isUserActive &&
3344 DEFAULT_ADMIN_USERNAME)
3347 <<
"User '" << actingUser
3348 <<
"' tried to lock for a user other than admin in wiz mode. Not allowed."
3352 else if(!isAdminForGroup(permissionMap) &&
3353 actingUser != username)
3355 __COUT_ERR__ <<
"A non-admin user '" << actingUser
3356 <<
"' tried to lock for a user other than self. Not allowed."
3360 usersUsernameWithLock_ = username;
3362 else if(!lock && usersUsernameWithLock_ == username)
3363 usersUsernameWithLock_ =
"";
3367 __COUT_INFO__ <<
"User '" << username <<
"' is inactive so not giving lock."
3370 __COUT_ERR__ <<
"Failed to lock for user '" << username <<
".'" << __E__;
3374 __COUT_INFO__ <<
"User '" << username <<
"' has locked out the system!" << __E__;
3378 std::string securityFileName = USER_WITH_LOCK_FILE;
3379 FILE* fp = fopen(securityFileName.c_str(),
"w");
3382 __COUT_INFO__ <<
"USER_WITH_LOCK_FILE " << USER_WITH_LOCK_FILE
3383 <<
" not found. Ignoring." << __E__;
3387 fprintf(fp,
"%s", usersUsernameWithLock_.c_str());
3398 const std::string& username,
3399 const std::string& displayname,
3400 const std::string& email,
3401 const std::string& permissions)
3403 std::map<std::string , WebUsers::permissionLevel_t> permissionMap =
3405 if(!isAdminForGroup(permissionMap))
3408 __SS__ <<
"Only admins can modify user settings." << __E__;
3412 uint64_t i = searchUsersDatabaseForUserId(actingUid);
3413 uint64_t modi = searchUsersDatabaseForUsername(username);
3418 __COUT_INFO__ <<
"Admin password reset." << __E__;
3419 Users_[modi].setModifier(Users_[i].username_);
3420 Users_[modi].salt_ =
"";
3421 Users_[modi].loginFailureCount_ = 0;
3422 saveDatabaseToFile(DB_USERS);
3425 __SS__ <<
"Cannot modify first user" << __E__;
3429 if(username.length() < USERNAME_LENGTH)
3431 __SS__ <<
"Invalid Username, must be length " << USERNAME_LENGTH << __E__;
3434 if(displayname.length() < DISPLAY_NAME_LENGTH)
3436 __SS__ <<
"Invalid Display Name; must be length " << DISPLAY_NAME_LENGTH << __E__;
3440 __COUT__ <<
"Input Permissions: " << permissions << __E__;
3441 std::map<std::string , WebUsers::permissionLevel_t> newPermissionsMap;
3445 case MOD_TYPE_UPDATE:
3447 __COUT__ <<
"MOD_TYPE_UPDATE " << username <<
" := " << permissions << __E__;
3449 if(modi == NOT_FOUND_IN_DATABASE)
3451 __SS__ <<
"User not found!? Should not happen." << __E__;
3457 for(uint64_t i = 0; i < Users_.size(); ++i)
3460 else if(Users_[i].displayName_ == displayname)
3462 __SS__ <<
"Display Name '" << displayname
3463 <<
"' already exists! Please choose a unique display name."
3469 Users_[modi].displayName_ = displayname;
3470 Users_[modi].email_ = email;
3474 bool wasInactive = isInactiveForGroup(Users_[modi].permissions_);
3477 if(newPermissionsMap.size() == 0)
3478 Users_[modi].permissions_[WebUsers::DEFAULT_USER_GROUP] =
3479 std::atoi(permissions.c_str());
3480 else if(newPermissionsMap.size() == 1 &&
3481 newPermissionsMap.find(WebUsers::DEFAULT_USER_GROUP) ==
3482 newPermissionsMap.end())
3484 if(newPermissionsMap.begin()->first ==
"")
3485 Users_[modi].permissions_[WebUsers::DEFAULT_USER_GROUP] =
3486 newPermissionsMap.begin()->second;
3489 newPermissionsMap[WebUsers::DEFAULT_USER_GROUP] =
3490 newPermissionsMap.begin()->second;
3491 Users_[modi].permissions_ = newPermissionsMap;
3495 Users_[modi].permissions_ = newPermissionsMap;
3500 !isInactiveForGroup(Users_[modi].permissions_))
3502 __COUT__ <<
"Reactivating " << username << __E__;
3503 Users_[modi].loginFailureCount_ = 0;
3504 Users_[modi].salt_ =
"";
3510 if(i == NOT_FOUND_IN_DATABASE)
3512 __SS__ <<
"Master User not found!? Should not happen." << __E__;
3515 Users_[modi].setModifier(Users_[i].username_);
3521 __COUT__ <<
"MOD_TYPE_ADD " << username <<
" - " << displayname << __E__;
3526 if(i == NOT_FOUND_IN_DATABASE)
3528 __SS__ <<
"Master User not found!? Should not happen." << __E__;
3531 Users_.back().setModifier(Users_[i].username_);
3534 if(permissions.size())
3537 actingUid, MOD_TYPE_UPDATE, username, displayname, email, permissions);
3541 case MOD_TYPE_DELETE:
3542 __COUT__ <<
"MOD_TYPE_DELETE " << username <<
" - " << displayname << __E__;
3543 deleteAccount(username, displayname);
3546 __SS__ <<
"Undefined command - do nothing " << username << __E__;
3550 saveDatabaseToFile(DB_USERS);
3551 loadSecuritySelection();
3559 std::set<unsigned int> activeUserIndices;
3560 for(uint64_t i = 0; i < ActiveSessions_.size(); ++i)
3561 activeUserIndices.emplace(
3562 searchUsersDatabaseForUserId(ActiveSessions_[i].userId_));
3564 for(
const auto& sessionPair : RemoteSessions_)
3565 activeUserIndices.emplace(
3566 searchUsersDatabaseForUserId(sessionPair.second.userId_));
3567 return activeUserIndices.size();
3575 std::set<unsigned int> activeUserIndices;
3576 for(uint64_t i = 0; i < ActiveSessions_.size(); ++i)
3577 activeUserIndices.emplace(
3578 searchUsersDatabaseForUserId(ActiveSessions_[i].userId_));
3580 for(
const auto& sessionPair : RemoteSessions_)
3581 activeUserIndices.emplace(
3582 searchUsersDatabaseForUserId(sessionPair.second.userId_));
3584 std::string activeUsersString =
"";
3585 bool addComma =
false;
3586 for(
const auto& i : activeUserIndices)
3588 if(i >= Users_.size())
3592 activeUsersString +=
",";
3596 activeUsersString += Users_[i].displayName_;
3598 if(activeUserIndices.size() == 0 &&
3600 WebUsers::SECURITY_TYPE_NONE)
3601 activeUsersString += WebUsers::DEFAULT_ADMIN_DISPLAY_NAME;
3603 __COUTVS__(20, activeUsersString);
3604 return activeUsersString;
3612 std::set<unsigned int> activeUserIndices;
3613 for(uint64_t i = 0; i < ActiveSessions_.size(); ++i)
3614 activeUserIndices.emplace(
3615 searchUsersDatabaseForUserId(ActiveSessions_[i].userId_));
3617 for(
const auto& sessionPair : RemoteSessions_)
3618 activeUserIndices.emplace(
3619 searchUsersDatabaseForUserId(sessionPair.second.userId_));
3621 std::string activeUsersString =
"";
3622 bool addComma =
false;
3623 for(
const auto& i : activeUserIndices)
3625 if(i >= Users_.size())
3629 activeUsersString +=
",";
3633 activeUsersString += Users_[i].username_;
3635 if(activeUserIndices.size() == 0 &&
3637 WebUsers::SECURITY_TYPE_NONE)
3638 activeUsersString += WebUsers::DEFAULT_ADMIN_USERNAME;
3640 __COUTVS__(20, activeUsersString);
3641 return activeUsersString;
3649 uint64_t uid = searchUsersDatabaseForUsername(DEFAULT_ADMIN_USERNAME);
3656 void WebUsers::loadUserWithLock()
3658 char username[300] =
"";
3660 std::string securityFileName = USER_WITH_LOCK_FILE;
3661 FILE* fp = fopen(securityFileName.c_str(),
"r");
3664 __COUT_INFO__ <<
"USER_WITH_LOCK_FILE " << USER_WITH_LOCK_FILE
3665 <<
" not found. Defaulting to admin lock." << __E__;
3668 sprintf(username,
"%s", DEFAULT_ADMIN_USERNAME.c_str());
3672 fgets(username, 300, fp);
3679 __COUT__ <<
"Attempting to load username with lock: " << username << __E__;
3681 if(strlen(username) == 0)
3683 __COUT_INFO__ <<
"Loaded state for user-with-lock is unlocked." << __E__;
3687 uint64_t i = searchUsersDatabaseForUsername(username);
3688 if(i == NOT_FOUND_IN_DATABASE)
3690 __COUT_INFO__ <<
"username " << username <<
" not found in database. Ignoring."
3694 __COUT__ <<
"Setting lock" << __E__;
3702 const std::string& message)
3711 const std::string& subject,
3712 const std::string& message,
3715 std::vector<std::string> targetUsers;
3725 const std::string& subject,
3726 const std::string& message,
3729 systemMessageCleanup();
3731 std::string fullMessage = StringMacros::encodeURIComponent(
3732 (subject ==
"" ?
"" : (subject +
": ")) + message);
3735 std::cout << __COUT_HDR_FL__ <<
"addSystemMessage() fullMessage: " << fullMessage
3739 std::set<std::string> targetEmails;
3741 for(
const auto& targetUser : targetUsers)
3745 if(targetUser ==
"" || (targetUser !=
"*" && targetUser.size() < 3))
3747 __COUT__ <<
"Illegal username '" << targetUser <<
"'" << __E__;
3750 __COUTV__(targetUser);
3754 if(doEmail && targetUser ==
"*")
3757 for(
const auto& user : Users_)
3759 if(user.email_.size() > 5 &&
3760 user.email_.find(
'@') != std::string::npos &&
3761 user.email_.find(
'.') != std::string::npos)
3763 __COUT__ <<
"Adding " << user.displayName_
3764 <<
" email: " << user.email_ << __E__;
3765 targetEmails.emplace(user.email_);
3770 else if(targetUser.find(
':') != std::string::npos)
3773 __COUT__ <<
"Treating as group email target: " << targetUser << __E__;
3775 std::map<std::string, WebUsers::permissionLevel_t> targetGroupMap;
3782 if(targetGroupMap.size() == 1)
3787 for(
const auto& user : Users_)
3789 WebUsers::permissionLevel_t userLevel =
3791 targetGroupMap.begin()->first);
3795 __COUTV__((
int)userLevel);
3796 __COUTV__(targetGroupMap.begin()->first);
3798 if(userLevel != WebUsers::PERMISSION_LEVEL_INACTIVE &&
3799 userLevel >= targetGroupMap.begin()->second &&
3800 user.email_.size() > 5 &&
3801 user.email_.find(
'@') != std::string::npos &&
3802 user.email_.find(
'.') != std::string::npos)
3806 targetEmails.emplace(user.email_);
3807 __COUT__ <<
"Adding " << user.displayName_
3808 <<
" email: " << user.email_ << __E__;
3810 addSystemMessageToMap(user.displayName_, fullMessage);
3815 __COUT__ <<
"target Group Map from '" << targetUser <<
"' is empty."
3823 addSystemMessageToMap(targetUser, fullMessage);
3827 for(
const auto& user : Users_)
3829 if(user.displayName_ == targetUser)
3831 if(user.email_.size() > 5 &&
3832 user.email_.find(
'@') != std::string::npos &&
3833 user.email_.find(
'.') != std::string::npos)
3835 targetEmails.emplace(user.email_);
3836 __COUT__ <<
"Adding " << user.displayName_
3837 <<
" email: " << user.email_ << __E__;
3846 __COUTV__(targetEmails.size());
3848 if(doEmail && targetEmails.size())
3852 std::string toList =
"";
3853 bool addComma =
false;
3854 for(
const auto& email : targetEmails)
3863 std::string filename = (std::string)WEB_LOGIN_DB_PATH +
3864 (std::string)USERS_DB_PATH +
"/.tmp_email.txt";
3865 FILE* fp = fopen(filename.c_str(),
"w");
3868 __SS__ <<
"Could not open email file: " << filename << __E__;
3878 fprintf(fp,
"To: %s\n", toList.c_str());
3879 fprintf(fp,
"Subject: %s\n", subject.c_str());
3880 fprintf(fp,
"Content-Type: text/html\n");
3881 fprintf(fp,
"\n<html><pre>%s</pre></html>", message.c_str());
3887 __COUT_WARN__ <<
"Do email was attempted, but no target users had email "
3888 "addresses specified!"
3897 void WebUsers::addSystemMessageToMap(
const std::string& targetUser,
3898 const std::string& fullMessage)
3901 std::lock_guard<std::mutex> lock(systemMessageLock_);
3903 __COUT__ <<
"Before number of users with system messages: " << systemMessages_.size()
3904 <<
", first user has "
3905 << (systemMessages_.size() ? systemMessages_.begin()->second.size() : 0)
3906 <<
" messages." << __E__;
3908 auto it = systemMessages_.find(targetUser);
3911 if(it != systemMessages_.end() && it->second.size() &&
3912 it->second[it->second.size() - 1].message_ == fullMessage)
3915 if(it == systemMessages_.end())
3917 systemMessages_.emplace(
3918 std::pair<std::string , std::vector<SystemMessage>>(
3919 targetUser, std::vector<SystemMessage>({SystemMessage(fullMessage)})));
3920 __COUTT__ << targetUser <<
" Current System Messages count = " << 1 << __E__;
3925 it->second.push_back(SystemMessage(fullMessage));
3926 __COUTT__ << it->first <<
" Current System Messages count = " << it->second.size()
3930 __COUT__ <<
"After number of users with system messages: " << systemMessages_.size()
3931 <<
", first user has "
3932 << (systemMessages_.size() ? systemMessages_.begin()->second.size() : 0)
3933 <<
" messages." << __E__;
3942 std::lock_guard<std::mutex> lock(systemMessageLock_);
3944 __COUTT__ <<
"GetLast number of users with system messages: "
3945 << systemMessages_.size() <<
", first user has "
3946 << (systemMessages_.size() ? systemMessages_.begin()->second.size() : 0)
3947 <<
" messages." << __E__;
3949 auto it = systemMessages_.find(
"*");
3950 if(it == systemMessages_.end() || it->second.size() == 0)
3951 return std::make_pair(
"", 0);
3953 return std::make_pair(it->second.back().message_, it->second.back().creationTime_);
3962 std::string retStr =
"";
3965 std::lock_guard<std::mutex> lock(systemMessageLock_);
3967 for(
auto& userSysMessages : systemMessages_)
3969 for(
auto& userSysMessage : userSysMessages.second)
3971 if(userSysMessage.deliveredRemote_)
3976 retStr += userSysMessages.first;
3977 retStr +=
"|" + std::to_string(userSysMessage.creationTime_);
3978 retStr +=
"|" + userSysMessage.message_;
3979 userSysMessage.deliveredRemote_ =
true;
3994 __COUTS__(20) <<
"Current System Messages: " << targetUser << __E__;
3995 std::string retStr =
"";
4001 std::lock_guard<std::mutex> lock(systemMessageLock_);
4003 __COUTS__(20) <<
"Number of users with system messages: "
4004 << systemMessages_.size() << __E__;
4007 auto it = systemMessages_.find(
"*");
4008 for(uint64_t i = 0; it != systemMessages_.end() && i < it->second.size(); ++i)
4013 sprintf(tmp,
"%lu", it->second[i].creationTime_);
4014 retStr += std::string(tmp) +
"|" + it->second[i].message_;
4020 __COUTVS__(20, targetUser);
4021 it = systemMessages_.find(targetUser);
4024 for(
auto systemMessagePair : systemMessages_)
4025 __COUTS__(20) << systemMessagePair.first <<
" "
4026 << systemMessagePair.second.size() <<
" "
4027 << (systemMessagePair.second.size()
4028 ? systemMessagePair.second[0].message_
4032 if(it != systemMessages_.end())
4034 __COUTS__(20) <<
"Message count: " << it->second.size() <<
", Last Message: "
4035 << (it->second.size() ? it->second.back().message_ :
"")
4039 for(uint64_t i = 0; it != systemMessages_.end() && i < it->second.size(); ++i)
4044 sprintf(tmp,
"%lu", it->second[i].creationTime_);
4045 retStr += std::string(tmp) +
"|" + it->second[i].message_;
4047 it->second[i].delivered_ =
true;
4052 __COUTS__(20) <<
"retStr: " << retStr << __E__;
4054 systemMessageCleanup();
4062 void WebUsers::systemMessageCleanup()
4065 std::lock_guard<std::mutex> lock(systemMessageLock_);
4067 __COUTT__ <<
"Before cleanup number of users with system messages: "
4068 << systemMessages_.size() <<
", first user has "
4069 << (systemMessages_.size() ? systemMessages_.begin()->second.size() : 0)
4070 <<
" messages." << __E__;
4071 for(
auto& userMessagesPair : systemMessages_)
4073 for(uint64_t i = 0; i < userMessagesPair.second.size(); ++i)
4074 if((userMessagesPair.first !=
"*" &&
4075 userMessagesPair.second[i].delivered_) ||
4079 __COUTT__ << userMessagesPair.first
4080 <<
" at time: " << userMessagesPair.second[i].creationTime_
4081 <<
" system messages: " << userMessagesPair.second.size()
4085 userMessagesPair.second.erase(userMessagesPair.second.begin() + i);
4089 __COUTT__ <<
"User '" << userMessagesPair.first
4090 <<
"' remaining system messages: " << userMessagesPair.second.size()
4093 __COUTT__ <<
"After cleanup number of users with system messages: "
4094 << systemMessages_.size() <<
", first user has "
4095 << (systemMessages_.size() ? systemMessages_.begin()->second.size() : 0)
4096 <<
" messages." << __E__;
4104 void WebUsers::loadSecuritySelection()
4106 std::string securityFileName = SECURITY_FILE_NAME;
4107 FILE* fp = fopen(securityFileName.c_str(),
"r");
4108 char line[100] =
"";
4110 fgets(line, 100, fp);
4114 while(i < strlen(line) && line[i] >=
'A' && line[i] <=
'z')
4118 if(strcmp(line, SECURITY_TYPE_NONE.c_str()) == 0 ||
4119 strcmp(line, SECURITY_TYPE_DIGEST_ACCESS.c_str()) == 0)
4120 securityType_ = line;
4122 securityType_ = SECURITY_TYPE_DEFAULT;
4124 __COUT__ <<
"The current security type is " << securityType_ << __E__;
4129 if(securityType_ == SECURITY_TYPE_NONE)
4130 CareAboutCookieCodes_ =
false;
4132 CareAboutCookieCodes_ =
true;
4134 __COUT__ <<
"CareAboutCookieCodes_: " << CareAboutCookieCodes_ << __E__;
4136 loadIPAddressSecurity();
4142 void WebUsers::loadIPAddressSecurity()
4144 ipAccessAccept_.clear();
4145 ipAccessReject_.clear();
4146 ipAccessBlacklist_.clear();
4148 FILE* fp = fopen((IP_ACCEPT_FILE).c_str(),
"r");
4154 while(fgets(line, 300, fp))
4158 if(len > 2 && line[len - 1] ==
'\n')
4159 line[len - 1] =
'\0';
4160 ipAccessAccept_.emplace(line);
4167 __COUTV__(ipAccessAccept_.size());
4169 fp = fopen((IP_REJECT_FILE).c_str(),
"r");
4172 while(fgets(line, 300, fp))
4176 if(len > 2 && line[len - 1] ==
'\n')
4177 line[len - 1] =
'\0';
4178 ipAccessReject_.emplace(line);
4185 __COUTV__(ipAccessReject_.size());
4187 fp = fopen((IP_BLACKLIST_FILE).c_str(),
"r");
4190 while(fgets(line, 300, fp))
4194 if(len > 2 && line[len - 1] ==
'\n')
4195 line[len - 1] =
'\0';
4196 ipAccessBlacklist_.emplace(line);
4203 __COUTV__(ipAccessBlacklist_.size());
4207 void WebUsers::NACDisplayThread(
const std::string& nac,
const std::string& user)
4218 std::this_thread::sleep_for(std::chrono::seconds(2));
4220 <<
"\n******************************************************************** "
4223 <<
"\n******************************************************************** "
4225 __COUT__ <<
"\n\nNew account code = " << nac <<
" for user: " << user <<
"\n"
4228 <<
"\n******************************************************************** "
4231 <<
"\n******************************************************************** "
4237 void WebUsers::deleteUserData()
4239 __COUT__ <<
"$$$$$$$$$$$$$$ Deleting ALL service user data... $$$$$$$$$$$$" << __E__;
4243 (
"rm -rf " + (std::string)WEB_LOGIN_DB_PATH + HASHES_DB_PATH +
"/*").c_str());
4245 (
"rm -rf " + (std::string)WEB_LOGIN_DB_PATH + USERS_DB_PATH +
"/*").c_str());
4247 (
"rm -rf " + (std::string)WEB_LOGIN_DB_PATH + USERS_LOGIN_HISTORY_PATH +
"/*")
4250 (
"rm -rf " + (std::string)WEB_LOGIN_DB_PATH + USERS_PREFERENCES_PATH +
"/*")
4252 std::system((
"rm -rf " + (std::string)WEB_LOGIN_DB_PATH + TOOLTIP_DB_PATH).c_str());
4254 std::string serviceDataPath = __ENV__(
"SERVICE_DATA_PATH");
4256 std::system((
"rm -rf " + std::string(serviceDataPath) +
"/MacroData/").c_str());
4257 std::system((
"rm -rf " + std::string(serviceDataPath) +
"/MacroHistory/").c_str());
4258 std::system((
"rm -rf " + std::string(serviceDataPath) +
"/MacroExport/").c_str());
4262 (
"rm -rf " + std::string(serviceDataPath) +
"/ConsolePreferences/").c_str());
4265 std::system((
"rm -rf " + std::string(serviceDataPath) +
"/CodeEditorData/").c_str());
4268 std::system((
"rm -rf " + std::string(serviceDataPath) +
"/OtsWizardData/").c_str());
4271 std::system((
"rm -rf " + std::string(serviceDataPath) +
"/ProgressBarData/").c_str());
4274 std::system((
"rm -rf " + std::string(serviceDataPath) +
"/RunNumber/").c_str());
4275 std::system((
"rm -rf " + std::string(serviceDataPath) +
"/RunControlData/").c_str());
4278 std::system((
"rm -rf " + std::string(serviceDataPath) +
"/VisualizerData/").c_str());
4285 std::system((
"rm -rf " + std::string(__ENV__(
"LOGBOOK_DATA_PATH")) +
"/").c_str());
4287 __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::string getActiveUsernamesString(void)
All active usernames.
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)
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)
std::string getActiveUserDisplayNamesString(void)
All active display names.
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()