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 if(userInfo.requireLock_ && userInfo.usernameWithLock_ ==
"")
226 __COUT_INFO__ <<
"Auto-taking lock for user '" << userInfo.username_
227 <<
"' because no user has the lock and lock is required." << __E__;
229 userInfo.usernameWithLock_ = userInfo.username_;
233 goto HANDLE_ACCESS_FAILURE;
237 HANDLE_ACCESS_FAILURE:
239 if(!userInfo.automatedCommand_)
240 __COUT_ERR__ <<
"Failed request (requestType = " << userInfo.requestType_
241 <<
"): " << out->str() << __E__;
252 userInfo.ip_ = cgi.getEnvironment().getRemoteAddr();
255 userInfo.username_ =
"";
256 userInfo.displayName_ =
"";
257 userInfo.usernameWithLock_ =
"";
271 std::ostringstream* out,
275 const std::string& wizardModeSequence )
281 if(userInfo.requireSecurity_ && userInfo.permissionsThreshold_ > 1)
287 if(isWizardMode && wizardModeSequence.size() < 8)
290 *out << WebUsers::REQ_NO_PERMISSION_RESPONSE;
291 __COUT__ <<
"User (@" << userInfo.ip_ <<
") has attempted requestType '"
292 << userInfo.requestType_
293 <<
"' which requires sufficient security enabled. Please enable the "
295 " sequence of at least 8 characters."
300 else if(!isWizardMode &&
301 (userInfo.username_ == WebUsers::DEFAULT_ADMIN_USERNAME ||
302 userInfo.username_ == WebUsers::DEFAULT_ITERATOR_USERNAME ||
303 userInfo.username_ == WebUsers::DEFAULT_STATECHANGER_USERNAME))
306 *out << WebUsers::REQ_NO_PERMISSION_RESPONSE;
307 __COUT__ <<
"User (@" << userInfo.ip_ <<
") has attempted requestType '"
308 << userInfo.requestType_
309 <<
"' which requires sufficient security enabled. Please enable "
311 " logins (Note: the user admin is disallowed in an attempt to "
312 "force personal accountability for edits)."
320 if(!userInfo.automatedCommand_)
322 __COUTT__ <<
"requestType ==========>>> " << userInfo.requestType_ << __E__;
323 __COUTTV__((
unsigned int)userInfo.permissionLevel_);
324 __COUTTV__((
unsigned int)userInfo.permissionsThreshold_);
328 if(!isWizardMode && !userInfo.allowNoUser_ &&
329 userInfo.cookieCode_.length() != WebUsers::COOKIE_CODE_LENGTH &&
331 userInfo.cookieCode_ ==
335 __COUT__ <<
"User (@" << userInfo.ip_
336 <<
") has invalid cookie code: " << userInfo.cookieCode_ << std::endl;
337 *out << WebUsers::REQ_NO_LOGIN_RESPONSE;
341 if(!userInfo.allowNoUser_ &&
342 (userInfo.permissionLevel_ == 0 ||
343 userInfo.permissionsThreshold_ == 0 ||
344 userInfo.permissionLevel_ < userInfo.permissionsThreshold_))
347 *out << WebUsers::REQ_NO_PERMISSION_RESPONSE;
348 __COUT_INFO__ <<
"User (@" << userInfo.ip_
349 <<
") has insufficient permissions for requestType '"
350 << userInfo.requestType_ <<
"' : user level is "
351 << (
unsigned int)userInfo.permissionLevel_ <<
", "
352 << (
unsigned int)userInfo.permissionsThreshold_ <<
" required."
360 userInfo.username_ = WebUsers::DEFAULT_ADMIN_USERNAME;
361 userInfo.displayName_ =
"Admin";
362 userInfo.usernameWithLock_ = userInfo.username_;
370 if(userInfo.allowNoUser_)
371 xmldoc->setHeader(WebUsers::REQ_ALLOW_NO_USER);
373 xmldoc->setHeader(userInfo.cookieCode_);
376 if(userInfo.allowNoUser_)
378 if(userInfo.automatedCommand_)
379 __COUTT__ <<
"Allowing anonymous access." << __E__;
390 if((userInfo.checkLock_ || userInfo.requireLock_) &&
391 userInfo.usernameWithLock_ !=
"" &&
392 userInfo.usernameWithLock_ != userInfo.username_)
394 *out << WebUsers::REQ_USER_LOCKOUT_RESPONSE;
395 __COUT_INFO__ <<
"User '" << userInfo.username_ <<
"' is locked out. '"
396 << userInfo.usernameWithLock_ <<
"' has lock." << std::endl;
400 if(userInfo.requireLock_ && userInfo.usernameWithLock_ != userInfo.username_)
402 *out << WebUsers::REQ_LOCK_REQUIRED_RESPONSE;
403 __COUT_INFO__ <<
"User '" << userInfo.username_
404 <<
"' must have lock to proceed. ('" << userInfo.usernameWithLock_
405 <<
"' has lock.)" << std::endl;
420 fn = (std::string)WEB_LOGIN_DB_PATH + (std::string)USERS_ACTIVE_SESSIONS_FILE;
421 __COUT__ << fn << __E__;
423 FILE* fp = fopen(fn.c_str(),
"w");
426 __COUT_ERR__ <<
"Error! Persistent active sessions could not be saved to file: "
432 fprintf(fp,
"%d\n", version);
433 for(
unsigned int i = 0; i < ActiveSessions_.size(); ++i)
441 fprintf(fp,
"%s\n", ActiveSessions_[i].cookieCode_.c_str());
442 fprintf(fp,
"%s\n", ActiveSessions_[i].ip_.c_str());
443 fprintf(fp,
"%lu\n", ActiveSessions_[i].userId_);
444 fprintf(fp,
"%lu\n", ActiveSessions_[i].sessionIndex_);
445 fprintf(fp,
"%ld\n", ActiveSessions_[i].startTime_);
448 __COUT__ <<
"Active Sessions saved with size " << ActiveSessions_.size() << __E__;
460 fn = (std::string)WEB_LOGIN_DB_PATH + (std::string)USERS_ACTIVE_SESSIONS_FILE;
461 __COUT__ << fn << __E__;
462 FILE* fp = fopen(fn.c_str(),
"r");
466 <<
"Persistent active sessions were not found to be loaded at file: " << fn
473 const int LINELEN = 1000;
475 fgets(line, LINELEN, fp);
476 sscanf(line,
"%d", &version);
479 __COUT__ <<
"Extracting active sessions..." << __E__;
481 while(fgets(line, LINELEN, fp))
484 line[strlen(line) - 1] =
'\0';
485 if(strlen(line) != COOKIE_CODE_LENGTH)
487 __COUT__ <<
"Illegal cookie code found: " << line << __E__;
493 ActiveSessions_.back().cookieCode_ = line;
495 fgets(line, LINELEN, fp);
497 line[strlen(line) - 1] =
'\0';
498 ActiveSessions_.back().ip_ = line;
500 fgets(line, LINELEN, fp);
501 sscanf(line,
"%lu", &(ActiveSessions_.back().userId_));
503 fgets(line, LINELEN, fp);
504 sscanf(line,
"%lu", &(ActiveSessions_.back().sessionIndex_));
506 fgets(line, LINELEN, fp);
507 sscanf(line,
"%ld", &(ActiveSessions_.back().startTime_));
510 __COUT__ <<
"Active Sessions loaded with size " << ActiveSessions_.size() << __E__;
514 fp = fopen(fn.c_str(),
"w");
523 bool WebUsers::loadDatabases()
528 const unsigned int LINE_LEN = 1000;
530 unsigned int i, si, c, len, f;
541 fn = (std::string)WEB_LOGIN_DB_PATH + (std::string)HASHES_DB_FILE;
542 __COUT__ << fn << __E__;
543 fp = fopen(fn.c_str(),
"r");
546 mkdir(((std::string)WEB_LOGIN_DB_PATH + (std::string)HASHES_DB_PATH).c_str(),
548 __COUT__ << ((std::string)WEB_LOGIN_DB_PATH + (std::string)HASHES_DB_PATH).c_str()
550 fp = fopen(fn.c_str(),
"w");
553 __COUT__ <<
"Hashes database created: " << fn << __E__;
555 saveToDatabase(fp, HASHES_DB_GLOBAL_STRING,
"", DB_SAVE_OPEN);
556 saveToDatabase(fp, HASHES_DB_GLOBAL_STRING,
"", DB_SAVE_CLOSE);
563 while(fgets(line, LINE_LEN, fp))
565 if(strlen(line) < SHA512_DIGEST_LENGTH)
571 for(i = 0; i < len; ++i)
579 while(i < len && line[i] !=
'<')
591 Hashes_.push_back(Hash());
592 Hashes_.back().hash_ = &line[si];
595 sscanf(&line[si],
"%ld", &Hashes_.back().accessTime_);
598 __COUT__ << Hashes_.size() <<
" Hashes found." << __E__;
612 fn = (std::string)WEB_LOGIN_DB_PATH + (std::string)USERS_DB_FILE;
613 fp = fopen(fn.c_str(),
"r");
616 mkdir(((std::string)WEB_LOGIN_DB_PATH + (std::string)USERS_DB_PATH).c_str(),
618 __COUT__ << ((std::string)WEB_LOGIN_DB_PATH + (std::string)USERS_DB_PATH).c_str()
620 fp = fopen(fn.c_str(),
"w");
623 __COUT__ <<
"Users database created: " << fn << __E__;
625 saveToDatabase(fp, USERS_DB_GLOBAL_STRING,
"", DB_SAVE_OPEN);
627 sprintf(nidStr,
"%lu", usersNextUserId_);
628 saveToDatabase(fp, USERS_DB_NEXT_UID_STRING, nidStr, DB_SAVE_OPEN_AND_CLOSE);
629 saveToDatabase(fp, USERS_DB_GLOBAL_STRING,
"", DB_SAVE_CLOSE);
633 DEFAULT_ADMIN_DISPLAY_NAME,
634 DEFAULT_ADMIN_EMAIL);
638 __COUT__ <<
"Users database: " << fn << __E__;
642 char salt[] =
"nextUserId";
643 while(fgets(line, LINE_LEN, fp))
645 if(strlen(line) < strlen(salt) * 2)
648 for(i = 0; i < strlen(salt); ++i)
649 if(line[i + 1] != salt[i])
652 if(i == strlen(salt))
657 while(i < LINE_LEN && line[i] !=
'\0' && line[i] !=
'<')
660 sscanf(&line[si],
"%lu", &usersNextUserId_);
665 __COUT__ <<
"Found Users database next user Id: " << usersNextUserId_ << __E__;
669 while(fgets(line, LINE_LEN, fp))
671 if(strlen(line) < 30)
679 __COUT__ <<
"Line buffer too small: " << len << __E__;
685 for(i = 0; i < len; ++i)
689 if(c == 0 || c % 2 == 1)
693 while(i < len && line[i] !=
'<')
705 Users_.push_back(User());
706 Users_.back().username_ = &line[si];
709 Users_.back().displayName_ = &line[si];
711 Users_.back().salt_ = &line[si];
713 sscanf(&line[si],
"%lu", &Users_.back().userId_);
716 std::map<std::string, permissionLevel_t>& lastPermissionsMap =
717 Users_.back().permissions_;
718 StringMacros::getMapFromString<permissionLevel_t>(
719 &line[si], lastPermissionsMap);
727 if(lastPermissionsMap.find(WebUsers::DEFAULT_USER_GROUP) ==
728 lastPermissionsMap.end())
731 <<
"User '" << Users_.back().username_
732 <<
"' is not a member of the default user group '"
733 << WebUsers::DEFAULT_USER_GROUP
734 <<
".' Assuming user account is inactive (permission "
736 << WebUsers::PERMISSION_LEVEL_INACTIVE <<
")." << __E__;
737 lastPermissionsMap[WebUsers::DEFAULT_USER_GROUP] =
738 WebUsers::PERMISSION_LEVEL_INACTIVE;
741 if(Users_.back().username_ == DEFAULT_ADMIN_USERNAME)
745 std::map<std::string ,
746 WebUsers::permissionLevel_t>
747 initPermissions = {{WebUsers::DEFAULT_USER_GROUP,
750 Users_.back().permissions_ = initPermissions;
754 sscanf(&line[si],
"%ld", &Users_.back().lastLoginAttempt_);
756 sscanf(&line[si],
"%ld", &Users_.back().accountCreationTime_);
758 sscanf(&line[si],
"%hhu", &Users_.back().loginFailureCount_);
760 sscanf(&line[si],
"%ld", &Users_.back().accessModifierTime());
762 Users_.back().loadModifierUsername(&line[si]);
764 Users_.back().email_ = &line[si];
771 __COUT__ << Users_.size() <<
" Users found." << __E__;
772 for(
size_t ii = 0; ii < Users_.size(); ++ii)
775 "User [" << Users_[ii].userId_ <<
"] \tName: " << std::left
776 << std::setfill(
' ') << std::setw(20) << Users_[ii].username_
777 <<
"\tDisplay Name: " << std::left << std::setfill(
' ') << std::setw(30)
778 << Users_[ii].displayName_ <<
"\tEmail: " << std::left
779 << std::setfill(
' ') << std::setw(30) << Users_[ii].email_
780 <<
"\tNAC: " << std::left << std::setfill(
' ') << std::setw(5)
781 << Users_[ii].getNewAccountCode()
782 <<
"\tFailedCount: " << (int)Users_[ii].loginFailureCount_
803 void WebUsers::saveLoginFailureCounts()
806 (std::string)WEB_LOGIN_DB_PATH + (std::string)USERS_LOGIN_FAILURE_FILE;
808 FILE* fp = fopen(fn.c_str(),
"w");
811 __COUT_ERR__ <<
"Failed to open login failure counts file for writing: " << fn
815 for(uint64_t i = 0; i < Users_.size(); ++i)
817 if(Users_[i].loginFailureCount_ > 0)
818 fprintf(fp,
"%lu %hhu\n", Users_[i].userId_, Users_[i].loginFailureCount_);
827 void WebUsers::loadLoginFailureCounts()
830 (std::string)WEB_LOGIN_DB_PATH + (std::string)USERS_LOGIN_FAILURE_FILE;
832 FILE* fp = fopen(fn.c_str(),
"r");
835 __COUT__ <<
"No login failure counts file found (this is normal on first run): "
841 for(
auto& user : Users_)
842 user.loginFailureCount_ = 0;
846 while(fscanf(fp,
"%lu %u", &uid, &count) == 2)
848 for(
auto& user : Users_)
850 if(user.userId_ == uid)
852 user.loginFailureCount_ = (
unsigned char)count;
858 __COUT__ <<
"Loaded login failure counts from " << fn << __E__;
863 void WebUsers::saveToDatabase(FILE* fp,
864 const std::string& field,
865 const std::string& value,
872 std::string newLine = addNewLine ?
"\n" :
"";
874 if(type == DB_SAVE_OPEN_AND_CLOSE)
881 else if(type == DB_SAVE_OPEN)
882 fprintf(fp,
"<%s>%s%s", field.c_str(), value.c_str(), newLine.c_str());
883 else if(type == DB_SAVE_CLOSE)
884 fprintf(fp,
"</%s>%s", field.c_str(), newLine.c_str());
893 bool WebUsers::saveDatabaseToFile(uint8_t db)
898 (std::string)WEB_LOGIN_DB_PATH +
899 ((db == DB_USERS) ? (std::string)USERS_DB_FILE : (std::string)HASHES_DB_FILE);
901 __COUT__ <<
"Save Database Filename: " << fn << __E__;
907 sprintf(dayAppend,
".%lu.bkup", time(0) / (3600 * 24));
908 std::string bkup_fn = (std::string)WEB_LOGIN_DB_PATH +
909 (std::string)WEB_LOGIN_BKUP_DB_PATH +
910 ((db == DB_USERS) ? (std::string)USERS_DB_FILE
911 : (std::string)HASHES_DB_FILE) +
912 (std::string)dayAppend;
914 __COUT__ <<
"Backup file: " << bkup_fn << __E__;
916 std::string shell_command =
"mv " + fn +
" " + bkup_fn;
917 system(shell_command.c_str());
920 FILE* fp = fopen(fn.c_str(),
"wb");
928 saveToDatabase(fp, USERS_DB_GLOBAL_STRING,
"", DB_SAVE_OPEN);
930 sprintf(fldStr,
"%lu", usersNextUserId_);
931 saveToDatabase(fp, USERS_DB_NEXT_UID_STRING, fldStr, DB_SAVE_OPEN_AND_CLOSE);
933 __COUT__ <<
"Saving " << Users_.size() <<
" Users." << __E__;
935 for(uint64_t i = 0; i < Users_.size(); ++i)
939 saveToDatabase(fp, USERS_DB_ENTRY_STRING,
"", DB_SAVE_OPEN,
false);
941 for(
unsigned int f = 0; f < WebUsers::UsersDatabaseEntryFields_.size(); ++f)
946 WebUsers::UsersDatabaseEntryFields_[f],
948 DB_SAVE_OPEN_AND_CLOSE,
952 WebUsers::UsersDatabaseEntryFields_[f],
953 Users_[i].displayName_,
954 DB_SAVE_OPEN_AND_CLOSE,
958 WebUsers::UsersDatabaseEntryFields_[f],
960 DB_SAVE_OPEN_AND_CLOSE,
964 sprintf(fldStr,
"%lu", Users_[i].userId_);
966 WebUsers::UsersDatabaseEntryFields_[f],
968 DB_SAVE_OPEN_AND_CLOSE,
973 WebUsers::UsersDatabaseEntryFields_[f],
977 DB_SAVE_OPEN_AND_CLOSE,
981 sprintf(fldStr,
"%lu", Users_[i].lastLoginAttempt_);
983 WebUsers::UsersDatabaseEntryFields_[f],
985 DB_SAVE_OPEN_AND_CLOSE,
990 sprintf(fldStr,
"%lu", Users_[i].accountCreationTime_);
992 WebUsers::UsersDatabaseEntryFields_[f],
994 DB_SAVE_OPEN_AND_CLOSE,
999 sprintf(fldStr,
"%hhu", Users_[i].loginFailureCount_);
1001 WebUsers::UsersDatabaseEntryFields_[f],
1003 DB_SAVE_OPEN_AND_CLOSE,
1008 sprintf(fldStr,
"%lu", Users_[i].getModifierTime());
1010 WebUsers::UsersDatabaseEntryFields_[f],
1012 DB_SAVE_OPEN_AND_CLOSE,
1017 WebUsers::UsersDatabaseEntryFields_[f],
1018 Users_[i].getModifierUsername(),
1019 DB_SAVE_OPEN_AND_CLOSE,
1023 WebUsers::UsersDatabaseEntryFields_[f],
1025 DB_SAVE_OPEN_AND_CLOSE,
1029 saveToDatabase(fp, USERS_DB_ENTRY_STRING,
"", DB_SAVE_CLOSE);
1032 saveToDatabase(fp, USERS_DB_GLOBAL_STRING,
"", DB_SAVE_CLOSE);
1036 saveToDatabase(fp, HASHES_DB_GLOBAL_STRING,
"", DB_SAVE_OPEN);
1038 __COUT__ <<
"Saving " << Hashes_.size() <<
" Hashes." << __E__;
1039 for(uint64_t i = 0; i < Hashes_.size(); ++i)
1041 __COUT__ <<
"Saving " << Hashes_[i].hash_ <<
" Hash." << __E__;
1042 saveToDatabase(fp, HASHES_DB_ENTRY_STRING,
"", DB_SAVE_OPEN,
false);
1043 for(
unsigned int f = 0; f < WebUsers::HashesDatabaseEntryFields_.size(); ++f)
1047 WebUsers::HashesDatabaseEntryFields_[f],
1049 DB_SAVE_OPEN_AND_CLOSE,
1053 sprintf(fldStr,
"%lu", Hashes_[i].accessTime_);
1055 WebUsers::HashesDatabaseEntryFields_[f],
1057 DB_SAVE_OPEN_AND_CLOSE,
1061 saveToDatabase(fp, HASHES_DB_ENTRY_STRING,
"", DB_SAVE_CLOSE);
1064 saveToDatabase(fp, HASHES_DB_GLOBAL_STRING,
"", DB_SAVE_CLOSE);
1080 const std::string& displayName,
1081 const std::string& email)
1083 __COUT__ <<
"Creating account: " << username << __E__;
1086 if((i = searchUsersDatabaseForUsername(username)) != NOT_FOUND_IN_DATABASE ||
1087 username == WebUsers::DEFAULT_ITERATOR_USERNAME ||
1088 username == WebUsers::DEFAULT_STATECHANGER_USERNAME)
1091 __SS__ <<
"Username '" << username
1092 <<
"' already exists! Please choose a unique username." << __E__;
1097 if((i = searchUsersDatabaseForDisplayName(displayName)) != NOT_FOUND_IN_DATABASE)
1100 __SS__ <<
"Display Name '" << displayName
1101 <<
"' already exists! Please choose a unique display name." << __E__;
1106 Users_.push_back(
User());
1108 Users_.back().username_ = username;
1109 Users_.back().displayName_ = displayName;
1110 Users_.back().email_ = email;
1113 std::map<std::string , WebUsers::permissionLevel_t> initPermissions = {
1114 {WebUsers::DEFAULT_USER_GROUP,
1115 (Users_.size() ? WebUsers::PERMISSION_LEVEL_NOVICE
1118 Users_.back().permissions_ = initPermissions;
1119 Users_.back().userId_ = usersNextUserId_++;
1120 if(usersNextUserId_ >= ACCOUNT_ERROR_THRESHOLD)
1122 __SS__ <<
"usersNextUserId_ wrap around!! Too many users??? Notify Admins."
1125 usersNextUserId_ = 1;
1129 Users_.back().accountCreationTime_ = time(0);
1131 if(!saveDatabaseToFile(DB_USERS))
1133 __SS__ <<
"Failed to save User DB!" << __E__;
1144 bool WebUsers::deleteAccount(
const std::string& username,
const std::string& displayName)
1146 uint64_t i = searchUsersDatabaseForUsername(username);
1147 if(i == NOT_FOUND_IN_DATABASE)
1149 if(Users_[i].displayName_ != displayName)
1154 Users_.erase(Users_.begin() + i);
1157 return saveDatabaseToFile(DB_USERS);
1161 unsigned int WebUsers::hexByteStrToInt(
const char* h)
1164 char hs[3] = {h[0], h[1],
'\0'};
1165 sscanf(hs,
"%X", &rv);
1170 void WebUsers::intToHexStr(
unsigned char i,
char* h) { sprintf(h,
"%2.2X", i); }
1183 std::string& jumbledUser,
1184 const std::string& jumbledPw,
1185 std::string& newAccountCode,
1186 const std::string& ip)
1191 __COUT_ERR__ <<
"rejected ip: " << ip << __E__;
1192 return ACCOUNT_BLACKLISTED;
1197 if(!CareAboutCookieCodes_)
1201 newAccountCode = genCookieCode();
1208 if((i = searchLoginSessionDatabaseForUUID(uuid)) == NOT_FOUND_IN_DATABASE)
1210 __COUT_ERR__ <<
"Login attempt failed. Session uuid '" << uuid
1211 <<
"' is not found or inactive." << __E__;
1212 newAccountCode =
"1";
1214 incrementIpBlacklistCount(ip);
1216 return NOT_FOUND_IN_DATABASE;
1218 ++LoginSessions_[i].loginAttempts_;
1220 std::string user = dejumble(jumbledUser, LoginSessions_[i].id_);
1222 std::string pw = dejumble(jumbledPw, LoginSessions_[i].id_);
1225 if((i = searchUsersDatabaseForUsername(user)) == NOT_FOUND_IN_DATABASE)
1227 __COUT_ERR__ <<
"user: " << user <<
" is not found" << __E__;
1229 incrementIpBlacklistCount(ip);
1231 return NOT_FOUND_IN_DATABASE;
1234 ipBlacklistCounts_[ip] = 0;
1236 Users_[i].lastLoginAttempt_ = time(0);
1238 if(isInactiveForGroup(Users_[i].permissions_))
1240 __COUT_ERR__ <<
"User '" << user
1241 <<
"' account INACTIVE (could be due to failed logins)" << __E__;
1242 return ACCOUNT_INACTIVE;
1245 if(Users_[i].salt_ ==
"")
1247 __COUT__ <<
"First login attempt for user: " << user << __E__;
1249 if(newAccountCode != Users_[i].getNewAccountCode())
1251 __COUT__ <<
"New account code did not match: "
1252 << Users_[i].getNewAccountCode() <<
" != " << newAccountCode
1257 return NOT_FOUND_IN_DATABASE;
1263 while(!addToHashesDatabase(
1264 sha512(user, pw, Users_[i].salt_)))
1269 Users_[i].salt_ =
"";
1272 __COUT__ <<
"\tHash added: " << Hashes_.back().hash_ << __E__;
1276 std::string salt = Users_[i].salt_;
1278 if(searchHashesDatabaseForHash(sha512(user, pw, salt)) == NOT_FOUND_IN_DATABASE)
1280 __COUT__ <<
"Failed login for " << user <<
" with permissions "
1284 if(++Users_[i].loginFailureCount_ != (
unsigned char)-1)
1285 ++Users_[i].loginFailureCount_;
1287 if(Users_[i].loginFailureCount_ >= USERS_MAX_LOGIN_FAILURES)
1288 Users_[i].permissions_[WebUsers::DEFAULT_USER_GROUP] =
1289 WebUsers::PERMISSION_LEVEL_INACTIVE;
1291 __COUT_INFO__ <<
"User/pw for user '" << user
1292 <<
"' was not correct (Failed Attempt #"
1293 << (int)Users_[i].loginFailureCount_ <<
" of "
1294 << (
int)USERS_MAX_LOGIN_FAILURES <<
" allowed)." << __E__;
1296 __COUTV__(isInactiveForGroup(Users_[i].permissions_));
1297 if(isInactiveForGroup(Users_[i].permissions_))
1299 __COUT_INFO__ <<
"Account '" << user
1300 <<
"' has been marked inactive due to too many failed "
1301 "login attempts (Failed Attempt #"
1302 << (int)Users_[i].loginFailureCount_
1303 <<
")! Note only admins can reactivate accounts." << __E__;
1306 saveDatabaseToFile(DB_USERS);
1310 return NOT_FOUND_IN_DATABASE;
1314 __COUT_INFO__ <<
"Login successful for: " << user << __E__;
1317 if(Users_[i].loginFailureCount_ != 0)
1319 Users_[i].loginFailureCount_ = 0;
1320 saveLoginFailureCounts();
1324 for(
int h = 0; h < 2; ++h)
1326 std::string fn = (std::string)WEB_LOGIN_DB_PATH +
1327 (std::string)USERS_LOGIN_HISTORY_PATH +
1328 (h ? USERS_GLOBAL_HISTORY_FILE : Users_[i].username_) +
"." +
1329 (std::string)USERS_LOGIN_HISTORY_FILETYPE;
1336 (h ? USERS_GLOBAL_HISTORY_SIZE : USERS_LOGIN_HISTORY_SIZE))
1340 __COUT__ <<
"No previous login history found." << __E__;
1346 "Time=%lu Username=%s Permissions=%s UID=%lu",
1348 Users_[i].username_.c_str(),
1353 "Time=%lu displayName=%s Permissions=%s UID=%lu",
1355 Users_[i].displayName_.c_str(),
1358 histXml.addTextElementToData(PREF_XML_LOGIN_HISTORY_FIELD, entryStr);
1370 jumbledUser = Users_[i].displayName_;
1371 newAccountCode = createNewActiveSession(Users_[i].userId_,
1374 __COUTTV__(ActiveSessions_.size());
1376 if(ActiveSessions_.size() == 1)
1378 __COUT__ <<
"Attempting to auto-lock for first login user '"
1379 << Users_[i].username_ <<
"'... " << __E__;
1383 return Users_[i].userId_;
1394 std::string& cookieCode,
1396 const std::string& ip)
1400 __COUT_ERR__ <<
"rejected ip: " << ip << __E__;
1401 return NOT_FOUND_IN_DATABASE;
1406 if(!CareAboutCookieCodes_)
1410 cookieCode = genCookieCode();
1416 __COUT__ <<
"Rejecting cert logon with blank fingerprint" << __E__;
1418 incrementIpBlacklistCount(ip);
1420 return NOT_FOUND_IN_DATABASE;
1426 if((i = searchLoginSessionDatabaseForUUID(uuid)) == NOT_FOUND_IN_DATABASE)
1428 __COUT__ <<
"uuid: " << uuid <<
" is not found" << __E__;
1431 incrementIpBlacklistCount(ip);
1433 return NOT_FOUND_IN_DATABASE;
1435 ++LoginSessions_[i].loginAttempts_;
1437 email = getUserEmailFromFingerprint(email);
1438 __COUT__ <<
"DejumbledEmail = " << email << __E__;
1441 __COUT__ <<
"Rejecting logon with unknown fingerprint" << __E__;
1443 incrementIpBlacklistCount(ip);
1445 return NOT_FOUND_IN_DATABASE;
1449 if((i = searchUsersDatabaseForUserEmail(email)) == NOT_FOUND_IN_DATABASE)
1451 __COUT__ <<
"email: " << email <<
" is not found" << __E__;
1453 incrementIpBlacklistCount(ip);
1455 return NOT_FOUND_IN_DATABASE;
1458 ipBlacklistCounts_[ip] = 0;
1462 Users_[i].lastLoginAttempt_ = time(0);
1463 if(isInactiveForGroup(Users_[i].permissions_))
1465 __COUT__ <<
"User '" << user
1466 <<
"' account INACTIVE (could be due to failed logins)." << __E__;
1467 return NOT_FOUND_IN_DATABASE;
1470 if(Users_[i].salt_ ==
"")
1472 return NOT_FOUND_IN_DATABASE;
1475 __COUT__ <<
"Login successful for: " << user << __E__;
1478 if(Users_[i].loginFailureCount_ != 0)
1480 Users_[i].loginFailureCount_ = 0;
1481 saveLoginFailureCounts();
1485 for(
int h = 0; h < 2; ++h)
1487 std::string fn = (std::string)WEB_LOGIN_DB_PATH +
1488 (std::string)USERS_LOGIN_HISTORY_PATH +
1489 (h ? USERS_GLOBAL_HISTORY_FILE : Users_[i].username_) +
"." +
1490 (std::string)USERS_LOGIN_HISTORY_FILETYPE;
1497 (h ? USERS_GLOBAL_HISTORY_SIZE : USERS_LOGIN_HISTORY_SIZE))
1501 __COUT__ <<
"No previous login history found." << __E__;
1507 "Time=%lu Username=%s Permissions=%s UID=%lu",
1509 Users_[i].username_.c_str(),
1514 "Time=%lu displayName=%s Permissions=%s UID=%lu",
1516 Users_[i].displayName_.c_str(),
1519 histXml.addTextElementToData(PREF_XML_LOGIN_HISTORY_FIELD, entryStr);
1531 email = Users_[i].displayName_;
1532 cookieCode = createNewActiveSession(Users_[i].userId_,
1534 return Users_[i].userId_;
1540 uint64_t WebUsers::searchActiveSessionDatabaseForCookie(
1541 const std::string& cookieCode)
const
1544 for(; i < ActiveSessions_.size(); ++i)
1545 if(ActiveSessions_[i].cookieCode_ == cookieCode)
1547 return (i == ActiveSessions_.size()) ? NOT_FOUND_IN_DATABASE : i;
1565 uint64_t WebUsers::checkRemoteLoginVerification(std::string& cookieCode,
1568 const std::string& ip)
1570 __COUTVS__(2, cookieCode);
1571 remoteLoginVerificationEnabledBlackoutTime_ = 0;
1572 if(!remoteLoginVerificationSocket_)
1577 <<
"Illegal remote login verification port found in remote destination "
1579 <<
". Please check remote settings." << __E__;
1582 __COUT_INFO__ <<
"Instantiating Remote Gateway login verification socket! "
1583 "Validation requests will go to "
1587 remoteLoginVerificationSocket_ =
1588 std::make_unique<TransceiverSocket>(remoteLoginVerificationIP_);
1589 remoteLoginVerificationSocket_->initialize();
1591 remoteLoginVerificationSocketTarget_ = std::make_unique<Socket>(
1597 auto lockHandling = [
this, refresh](std::string username,
1598 uint64_t verifiedUserId) -> uint64_t {
1599 __COUTT__ <<
"lambda lockHandling()" << __E__;
1600 __COUTTV__(ActiveSessions_.size());
1601 __COUTTV__(RemoteSessions_.size());
1603 if((!CareAboutCookieCodes_)
1605 (usersUsernameWithLock_ == DEFAULT_ADMIN_USERNAME ||
1606 usersUsernameWithLock_ ==
"") &&
1607 usersUsernameWithLock_ != username)
1609 __COUT_INFO__ <<
"Overriding local user-with-lock '" << usersUsernameWithLock_
1610 <<
"' with remote user-with-lock 'Remote:" << username <<
"'"
1612 usersUsernameWithLock_ =
1616 getUserWithLock() +
" has locked REMOTE ots (overriding anonymous " +
1617 DEFAULT_ADMIN_USERNAME +
" user).");
1619 else if((ActiveSessions_.size() == 0 &&
1620 RemoteSessions_.size() == 1)
1621 && refresh && (usersUsernameWithLock_ ==
"") &&
1622 usersUsernameWithLock_ != username)
1624 __COUT_INFO__ <<
"Overriding local user-with-lock '" << usersUsernameWithLock_
1625 <<
"' with remote user-with-lock 'Remote:" << username <<
"'"
1627 usersUsernameWithLock_ =
1631 getUserWithLock() +
" has locked REMOTE ots (which was unlocked).");
1633 return verifiedUserId;
1638 __COUTTV__(cookieCode);
1639 __COUTTV__(RemoteSessions_.size());
1640 auto it = RemoteSessions_.find(cookieCode);
1641 if(it != RemoteSessions_.end())
1643 __COUTT__ <<
"cookieCode still active locally!" << __E__;
1644 __COUTTV__(it->second.userId_);
1645 uint64_t j = searchUsersDatabaseForUserId(it->second.userId_);
1646 if(j == NOT_FOUND_IN_DATABASE)
1648 __SS__ <<
"Could not find cache entry for remote user ID '"
1649 << it->second.userId_ <<
"' - notify admins." << __E__;
1652 __COUTTV__(Users_[j].username_);
1655 return lockHandling(Users_[j].username_, it->second.userId_);
1660 __COUTTV__(doNotGoRemote);
1662 return NOT_FOUND_IN_DATABASE;
1673 std::string request =
"loginVerify," + cookieCode +
"," + (refresh ?
"1" :
"0") +
1679 std::string requestResponseString = remoteLoginVerificationSocket_->sendAndReceive(
1680 *remoteLoginVerificationSocketTarget_, request, 10 );
1681 __COUTV__(requestResponseString);
1684 std::vector<std::string> rxParams =
1688 if(rxParams.size() != 6)
1690 __COUT__ <<
"Remote login response indicates rejected: " << rxParams.size()
1692 return NOT_FOUND_IN_DATABASE;
1704 __COUTTV__(rxParams[2]);
1705 __COUTTV__(usersUsernameWithLock_);
1708 std::string username = rxParams[3];
1709 __COUTTV__(username);
1710 uint64_t j = searchUsersDatabaseForUsername(username);
1711 if(j == NOT_FOUND_IN_DATABASE)
1713 __COUT_INFO__ <<
"Creating User entry for remote user '" << username
1714 <<
"' in local user list to track user preferences." << __E__;
1718 j = Users_.size() - 1;
1721 Users_[j].lastLoginAttempt_ = time(0);
1722 Users_[j].setModifier(
"REMOTE_GATEWAY");
1727 .permissions_.clear();
1729 Users_[j].permissions_);
1731 __COUTV__(Users_[j].username_);
1732 __COUTV__(Users_[j].userId_);
1736 cookieCode = rxParams[0];
1737 __COUTTV__(cookieCode);
1738 ActiveSession& newRemoteSession =
1739 RemoteSessions_[cookieCode];
1740 newRemoteSession.cookieCode_ = cookieCode;
1741 newRemoteSession.ip_ = ip;
1742 newRemoteSession.userId_ = Users_[j].userId_;
1743 sscanf(rxParams[5].c_str(),
"%lu", &newRemoteSession.sessionIndex_);
1744 newRemoteSession.startTime_ = time(0);
1747 return lockHandling(Users_[j].username_, Users_[j].userId_);
1756 if((u = searchUsersDatabaseForUsername(username)) == NOT_FOUND_IN_DATABASE)
1766 __COUTT__ <<
"isUserIdActive? " << uid << __E__;
1769 for(
const auto& remoteSession : RemoteSessions_)
1770 if(remoteSession.second.userId_ == uid)
1775 for(; i < ActiveSessions_.size(); ++i)
1776 if(ActiveSessions_[i].userId_ == uid)
1784 uint64_t WebUsers::searchUsersDatabaseForUsername(
const std::string& username)
const
1787 for(; i < Users_.size(); ++i)
1788 if(Users_[i].username_ == username)
1790 return (i == Users_.size()) ? NOT_FOUND_IN_DATABASE : i;
1796 uint64_t WebUsers::searchUsersDatabaseForDisplayName(
const std::string& displayName)
const
1799 for(; i < Users_.size(); ++i)
1800 if(Users_[i].displayName_ == displayName)
1802 return (i == Users_.size()) ? NOT_FOUND_IN_DATABASE : i;
1808 uint64_t WebUsers::searchUsersDatabaseForUserEmail(
const std::string& useremail)
const
1811 for(; i < Users_.size(); ++i)
1812 if(Users_[i].email_ == useremail)
1814 return (i == Users_.size()) ? NOT_FOUND_IN_DATABASE : i;
1820 uint64_t WebUsers::searchUsersDatabaseForUserId(uint64_t uid)
const
1823 for(; i < Users_.size(); ++i)
1824 if(Users_[i].userId_ == uid)
1826 return (i == Users_.size()) ? NOT_FOUND_IN_DATABASE : i;
1832 uint64_t WebUsers::searchLoginSessionDatabaseForUUID(
const std::string& uuid)
const
1835 for(; i < LoginSessions_.size(); ++i)
1836 if(LoginSessions_[i].uuid_ == uuid)
1838 return (i == LoginSessions_.size()) ? NOT_FOUND_IN_DATABASE : i;
1844 uint64_t WebUsers::searchHashesDatabaseForHash(
const std::string& hash)
1848 for(; i < Hashes_.size(); ++i)
1849 if(Hashes_[i].hash_ == hash)
1854 if(i < Hashes_.size())
1855 Hashes_[i].accessTime_ =
1856 ((time(0) + (rand() % 2 ? 1 : -1) * (rand() % 30 * 24 * 60 * 60)) &
1857 0x0FFFFFFFFFE000000);
1862 return (i == Hashes_.size()) ? NOT_FOUND_IN_DATABASE : i;
1869 bool WebUsers::addToHashesDatabase(
const std::string& hash)
1871 if(searchHashesDatabaseForHash(hash) != NOT_FOUND_IN_DATABASE)
1873 __COUT__ <<
"Hash collision: " << hash << __E__;
1876 Hashes_.push_back(Hash());
1877 Hashes_.back().hash_ = hash;
1878 Hashes_.back().accessTime_ =
1879 ((time(0) + (rand() % 2 ? 1 : -1) * (rand() % 30 * 24 * 60 * 60)) &
1880 0x0FFFFFFFFFE000000);
1883 return saveDatabaseToFile(DB_HASHES);
1888 std::string WebUsers::genCookieCode()
1891 std::string cc =
"";
1892 for(uint32_t i = 0; i < COOKIE_CODE_LENGTH / 2; ++i)
1894 intToHexStr(rand(), hexStr);
1904 std::string WebUsers::createNewActiveSession(uint64_t uid,
1905 const std::string& ip,
1909 ActiveSessions_.push_back(ActiveSession());
1910 ActiveSessions_.back().cookieCode_ = genCookieCode();
1911 ActiveSessions_.back().ip_ = ip;
1912 ActiveSessions_.back().userId_ = uid;
1913 ActiveSessions_.back().startTime_ = time(0);
1916 ActiveSessions_.back().sessionIndex_ = asIndex;
1921 for(uint64_t j = 0; j < ActiveSessions_.size(); ++j)
1922 if(ActiveSessions_[j].userId_ == uid &&
1923 max < ActiveSessions_[j].sessionIndex_)
1924 max = ActiveSessions_[j].sessionIndex_;
1926 ActiveSessions_.back().sessionIndex_ = (max ? max + 1 : 1);
1929 return ActiveSessions_.back().cookieCode_;
1956 std::string WebUsers::refreshCookieCode(
unsigned int i,
bool enableRefresh)
1959 for(uint64_t j = ActiveSessions_.size() - 1; j != (uint64_t)-1;
1961 if(ActiveSessions_[j].userId_ == ActiveSessions_[i].userId_ &&
1962 ActiveSessions_[j].sessionIndex_ ==
1963 ActiveSessions_[i].sessionIndex_)
1968 if(enableRefresh && (time(0) - ActiveSessions_[j].startTime_ >
1969 ACTIVE_SESSION_EXPIRATION_TIME / 2))
1973 ActiveSessions_[j].startTime_ =
1974 time(0) - ACTIVE_SESSION_EXPIRATION_TIME +
1975 ACTIVE_SESSION_COOKIE_OVERLAP_TIME;
1981 return createNewActiveSession(ActiveSessions_[i].userId_,
1982 ActiveSessions_[i].ip_,
1983 ActiveSessions_[i].sessionIndex_);
1986 return ActiveSessions_[j].cookieCode_;
1998 std::string& cookieCode,
1999 std::string& username)
2001 if(!CareAboutCookieCodes_)
2008 if(!ActiveSessions_.size())
2009 return NOT_FOUND_IN_DATABASE;
2014 if((i = searchLoginSessionDatabaseForUUID(uuid)) == NOT_FOUND_IN_DATABASE)
2016 __COUT__ <<
"uuid not found: " << uuid << __E__;
2017 return NOT_FOUND_IN_DATABASE;
2021 dejumble(username, LoginSessions_[i].id_);
2024 if((i = searchActiveSessionDatabaseForCookie(cookieCode)) == NOT_FOUND_IN_DATABASE)
2026 __COUT__ <<
"Cookie code not found" << __E__;
2027 return NOT_FOUND_IN_DATABASE;
2031 if((j = searchUsersDatabaseForUserId(ActiveSessions_[i].userId_)) ==
2032 NOT_FOUND_IN_DATABASE)
2034 __COUT__ <<
"User ID not found" << __E__;
2035 return NOT_FOUND_IN_DATABASE;
2039 if(Users_[j].username_ != username)
2041 __COUT__ <<
"cookieCode: " << cookieCode <<
" was.." << __E__;
2042 __COUT__ <<
"username: " << username <<
" is not found" << __E__;
2043 return NOT_FOUND_IN_DATABASE;
2046 username = Users_[j].displayName_;
2047 cookieCode = refreshCookieCode(i);
2048 return Users_[j].userId_;
2057 std::vector<uint64_t> uniqueAsi;
2060 for(i = 0; i < ActiveSessions_.size(); ++i)
2061 if(ActiveSessions_[i].userId_ == uid)
2066 for(j = 0; j < uniqueAsi.size(); ++j)
2067 if(uniqueAsi[j] == ActiveSessions_[i].sessionIndex_)
2074 uniqueAsi.push_back(ActiveSessions_[i].sessionIndex_);
2077 __COUT__ <<
"Found " << uniqueAsi.size() <<
" active sessions for uid " << uid
2080 return uniqueAsi.size();
2096 if(time(0) > ipSecurityLastLoadTime_ +
2099 ipSecurityLastLoadTime_ = time(0);
2100 loadIPAddressSecurity();
2103 for(
const auto& acceptIp : ipAccessAccept_)
2106 __COUTV__(acceptIp);
2109 for(
const auto& rejectIp : ipAccessReject_)
2112 __COUTV__(rejectIp);
2115 for(
const auto& blacklistIp : ipAccessBlacklist_)
2118 __COUTV__(blacklistIp);
2128 void WebUsers::incrementIpBlacklistCount(
const std::string& ip)
2130 if(ipAccessBlacklist_.find(ip) != ipAccessBlacklist_.end())
2134 auto it = ipBlacklistCounts_.find(ip);
2135 if(it == ipBlacklistCounts_.end())
2137 __COUT__ <<
"First error for ip '" << ip <<
"'" << __E__;
2138 ipBlacklistCounts_[ip] = 1;
2144 if(it->second >= IP_BLACKLIST_COUNT_THRESHOLD)
2146 __COUT_WARN__ <<
"Adding IP '" << ip <<
"' to blacklist!" << __E__;
2148 ipAccessBlacklist_.emplace(ip);
2149 __COUTV__(ipAccessBlacklist_.size());
2152 FILE* fp = fopen((IP_BLACKLIST_FILE).c_str(),
"a");
2155 __COUT_ERR__ <<
"IP black list file '" << IP_BLACKLIST_FILE
2156 <<
"' could not be opened." << __E__;
2159 fprintf(fp,
"%s\n", ip.c_str());
2170 if((i = searchUsersDatabaseForUserId(uid)) == NOT_FOUND_IN_DATABASE)
2172 return Users_[i].displayName_;
2180 if((i = searchUsersDatabaseForUserId(uid)) == NOT_FOUND_IN_DATABASE)
2182 return Users_[i].username_;
2197 bool logoutOtherUserSessions,
2199 const std::string& ip)
2204 if((i = searchActiveSessionDatabaseForCookie(cookieCode)) == NOT_FOUND_IN_DATABASE)
2206 __COUT__ <<
"Cookie code not found" << __E__;
2208 incrementIpBlacklistCount(ip);
2210 return NOT_FOUND_IN_DATABASE;
2213 ipBlacklistCounts_[ip] = 0;
2216 if(ActiveSessions_[i].ip_ != ip)
2218 __COUT__ <<
"IP does not match active session" << __E__;
2219 return NOT_FOUND_IN_DATABASE;
2228 uint64_t asi = ActiveSessions_[i].sessionIndex_;
2229 uint64_t uid = ActiveSessions_[i].userId_;
2232 uint64_t logoutCount = 0;
2235 while(i < ActiveSessions_.size())
2237 if((logoutOtherUserSessions && ActiveSessions_[i].userId_ == uid &&
2238 ActiveSessions_[i].sessionIndex_ != asi) ||
2239 (!logoutOtherUserSessions && ActiveSessions_[i].userId_ == uid &&
2240 ActiveSessions_[i].sessionIndex_ == asi))
2242 __COUT__ <<
"Logging out of active session " << ActiveSessions_[i].userId_
2243 <<
"-" << ActiveSessions_[i].sessionIndex_ << __E__;
2244 ActiveSessions_.erase(ActiveSessions_.begin() + i);
2251 __COUT__ <<
"Found and removed active session count = " << logoutCount << __E__;
2270 std::string& cookieCode,
2271 std::map<std::string /*groupName*/, WebUsers::permissionLevel_t>* userPermissions,
2273 const std::string& ip,
2276 std::string* userWithLock,
2277 uint64_t* userSessionIndex)
2285 __COUT_ERR__ <<
"User IP rejected." << __E__;
2286 cookieCode = REQ_NO_LOGIN_RESPONSE;
2292 uint64_t i, j, userId = NOT_FOUND_IN_DATABASE, userSession = NOT_FOUND_IN_DATABASE;
2294 __COUTTV__(CareAboutCookieCodes_);
2295 __COUTT__ <<
"refresh=" << refresh <<
", doNotGoRemote=" << doNotGoRemote << __E__;
2296 __COUTVS__(2, cookieCode);
2300 __COUTTV__(localEnableRemoteLogin);
2305 if(localEnableRemoteLogin &&
2306 time(0) > remoteLoginVerificationEnabledBlackoutTime_ &&
2307 (userId = checkRemoteLoginVerification(
2308 cookieCode, refresh, doNotGoRemote, ip)) != NOT_FOUND_IN_DATABASE)
2311 __COUTT__ <<
"Remote login session verified." << __E__;
2312 userSession = RemoteSessions_.at(cookieCode).sessionIndex_;
2317 std::string err =
"";
2322 catch(
const std::exception& e)
2327 __COUT_WARN__ <<
"Ignoring exception during remote login verification. " << err
2331 if(!CareAboutCookieCodes_ && localEnableRemoteLogin &&
2332 remoteLoginVerificationEnabledBlackoutTime_ == 0)
2335 localEnableRemoteLogin =
false;
2336 remoteLoginVerificationEnabledBlackoutTime_ = time(0) + 10;
2337 __COUT_INFO__ <<
"Disabled remote login until "
2339 remoteLoginVerificationEnabledBlackoutTime_)
2343 __COUTTV__(localEnableRemoteLogin);
2345 if(localEnableRemoteLogin && userId == NOT_FOUND_IN_DATABASE)
2346 __COUTT__ <<
"Remote login verification failed." << __E__;
2348 if(!CareAboutCookieCodes_ &&
2349 userId == NOT_FOUND_IN_DATABASE)
2353 std::map<std::string , WebUsers::permissionLevel_t>(
2358 *userWithLock = usersUsernameWithLock_;
2359 if(userSessionIndex)
2360 *userSessionIndex = 0;
2362 if(cookieCode.size() != COOKIE_CODE_LENGTH)
2363 cookieCode = genCookieCode();
2365 if(localEnableRemoteLogin)
2367 cookieCode = WebUsers::
2375 if(userId == NOT_FOUND_IN_DATABASE)
2378 if((i = searchActiveSessionDatabaseForCookie(cookieCode)) ==
2379 NOT_FOUND_IN_DATABASE)
2381 __COUT_ERR__ <<
"Cookie code not found" << __E__;
2382 cookieCode = REQ_NO_LOGIN_RESPONSE;
2384 incrementIpBlacklistCount(ip);
2389 ipBlacklistCounts_[ip] = 0;
2392 if(ip !=
"0" && ActiveSessions_[i].ip_ != ip)
2394 __COUTV__(ActiveSessions_[i].ip_);
2396 __COUT_ERR__ <<
"IP does not match active session." << __E__;
2397 cookieCode = REQ_NO_LOGIN_RESPONSE;
2401 userId = ActiveSessions_[i].userId_;
2402 userSession = ActiveSessions_[i].sessionIndex_;
2403 cookieCode = refreshCookieCode(i, refresh);
2404 __COUTT__ <<
"Login session verified." << __E__;
2410 if((j = searchUsersDatabaseForUserId(userId)) == NOT_FOUND_IN_DATABASE)
2412 __COUT_ERR__ <<
"After login verification, User ID not found! Notify admins."
2414 cookieCode = REQ_NO_LOGIN_RESPONSE;
2418 std::map<std::string , WebUsers::permissionLevel_t> tmpPerm =
2421 if(isInactiveForGroup(tmpPerm))
2423 __COUTT__ <<
"Inactive user identified." << __E__;
2424 cookieCode = REQ_NO_PERMISSION_RESPONSE;
2430 *userPermissions = tmpPerm;
2434 *userWithLock = usersUsernameWithLock_;
2435 if(userSessionIndex)
2436 *userSessionIndex = userSession;
2453 if(loggedOutUsernames)
2455 for(i = 0; i < UsersLoggedOutUsernames_.size(); ++i)
2456 loggedOutUsernames->push_back(UsersLoggedOutUsernames_[i]);
2457 UsersLoggedOutUsernames_.clear();
2461 for(i = 0; i < LoginSessions_.size(); ++i)
2462 if(LoginSessions_[i].startTime_ + LOGIN_SESSION_EXPIRATION_TIME <
2464 LoginSessions_[i].loginAttempts_ > LOGIN_SESSION_ATTEMPTS_MAX)
2466 __COUT__ <<
"Found expired login sessions: #" << (i + 1) <<
" of "
2467 << LoginSessions_.size() << __E__;
2471 LoginSessions_.erase(LoginSessions_.begin() + i);
2484 for(i = 0; i < ActiveSessions_.size(); ++i)
2485 if(ActiveSessions_[i].startTime_ + ACTIVE_SESSION_EXPIRATION_TIME <=
2495 __COUT__ <<
"Found expired active sessions: #" << (i + 1) <<
" of "
2496 << ActiveSessions_.size() << __E__;
2497 __COUTTV__(ActiveSessions_[i].cookieCode_);
2499 tmpUid = ActiveSessions_[i].userId_;
2500 ActiveSessions_.erase(ActiveSessions_.begin() + i);
2505 if(loggedOutUsernames)
2506 loggedOutUsernames->push_back(
2507 Users_[searchUsersDatabaseForUserId(tmpUid)].username_);
2509 UsersLoggedOutUsernames_.push_back(
2510 Users_[searchUsersDatabaseForUserId(tmpUid)].username_);
2531 if(CareAboutCookieCodes_ && usersUsernameWithLock_ !=
"" &&
2539 usersUsernameWithLock_ =
"";
2549 std::vector<std::string> toErase;
2550 for(
const auto& remoteSession : RemoteSessions_)
2551 if(remoteSession.second.startTime_ + ACTIVE_SESSION_EXPIRATION_TIME / 4 <=
2554 __COUT__ <<
"Found expired remote active sessions: #" << remoteSession.first
2555 <<
" in " << RemoteSessions_.size() << __E__;
2556 toErase.push_back(remoteSession.first);
2558 for(
const auto& eraseId : toErase)
2559 RemoteSessions_.erase(eraseId);
2570 const std::string& ip)
2576 for(; i < LoginSessions_.size(); ++i)
2577 if(LoginSessions_[i].uuid_ == UUID)
2580 if(i != LoginSessions_.size())
2582 __COUT_ERR__ <<
"UUID: " << UUID <<
" is not unique" << __E__;
2588 LoginSessions_.back().uuid_ = UUID;
2592 std::string sid =
"";
2593 for(i = 0; i < SESSION_ID_LENGTH / 2; ++i)
2595 intToHexStr(rand(), hexStr);
2598 LoginSessions_.back().id_ = sid;
2599 LoginSessions_.back().ip_ = ip;
2600 LoginSessions_.back().startTime_ = time(0);
2601 LoginSessions_.back().loginAttempts_ = 0;
2611 std::string WebUsers::sha512(
const std::string& user,
2612 const std::string& password,
2615 SHA512_CTX sha512_context;
2620 SHA512_Init(&sha512_context);
2622 for(
unsigned int i = 0; i < 8; ++i)
2623 sha512_context.h[i] += rand();
2625 for(
unsigned int i = 0; i <
sizeof(SHA512_CTX); ++i)
2627 intToHexStr((uint8_t)(((uint8_t*)(&sha512_context))[i]), hexStr);
2629 salt.append(hexStr);
2637 for(
unsigned int i = 0; i <
sizeof(SHA512_CTX); ++i)
2638 ((uint8_t*)(&sha512_context))[i] = hexByteStrToInt(&(salt.c_str()[i * 2]));
2641 std::string strToHash = salt + user + password;
2644 unsigned char hash[SHA512_DIGEST_LENGTH];
2646 char retHash[SHA512_DIGEST_LENGTH * 2 + 1];
2650 SHA512_Update(&sha512_context, strToHash.c_str(), strToHash.length());
2652 SHA512_Final(hash, &sha512_context);
2656 for(i = 0; i < SHA512_DIGEST_LENGTH; i++)
2657 sprintf(retHash + (i * 2),
"%02x", hash[i]);
2660 retHash[SHA512_DIGEST_LENGTH * 2] =
'\0';
2671 std::string WebUsers::dejumble(
const std::string& u,
const std::string& s)
2673 if(s.length() != SESSION_ID_LENGTH)
2676 const int ss = s.length() / 2;
2677 int p = hexByteStrToInt(&(s.c_str()[0])) % ss;
2678 int n = hexByteStrToInt(&(s.c_str()[p * 2])) % ss;
2679 int len = (hexByteStrToInt(&(u.c_str()[p * 2])) - p - n + ss * 3) % ss;
2681 std::vector<bool> x(ss);
2682 for(
int i = 0; i < ss; ++i)
2686 int c = hexByteStrToInt(&(u.c_str()[p * 2]));
2688 std::string user =
"";
2690 for(
int l = 0; l < len; ++l)
2692 p = (p + hexByteStrToInt(&(s.c_str()[p * 2]))) % ss;
2696 n = hexByteStrToInt(&(s.c_str()[p * 2]));
2697 user.append(1, (hexByteStrToInt(&(u.c_str()[p * 2])) - c - n + ss * 4) % ss);
2698 c = hexByteStrToInt(&(u.c_str()[p * 2]));
2707 std::map<std::string , WebUsers::permissionLevel_t>
2710 uint64_t userIndex = searchUsersDatabaseForUserId(uid);
2711 if(userIndex < Users_.size())
2712 return Users_[userIndex].permissions_;
2715 std::map<std::string , WebUsers::permissionLevel_t> retErrorMap;
2716 retErrorMap[WebUsers::DEFAULT_USER_GROUP] = WebUsers::PERMISSION_LEVEL_INACTIVE;
2753 WebUsers::permissionLevel_t WebUsers::getPermissionLevelForGroup(
2754 const std::map<std::string /*groupName*/, WebUsers::permissionLevel_t>& permissionMap,
2755 const std::string& groupName)
2757 auto it = permissionMap.find(groupName);
2758 if(it == permissionMap.end())
2760 __COUT__ <<
"Group name '" << groupName
2761 <<
"' not found - assuming inactive user in this group." << __E__;
2762 return WebUsers::PERMISSION_LEVEL_INACTIVE;
2768 bool WebUsers::isInactiveForGroup(
2769 const std::map<std::string /*groupName*/, WebUsers::permissionLevel_t>& permissionMap,
2770 const std::string& groupName)
2772 return getPermissionLevelForGroup(permissionMap, groupName) ==
2773 WebUsers::PERMISSION_LEVEL_INACTIVE;
2777 bool WebUsers::isAdminForGroup(
2778 const std::map<std::string /*groupName*/, WebUsers::permissionLevel_t>& permissionMap,
2779 const std::string& groupName)
2781 return getPermissionLevelForGroup(permissionMap, groupName) ==
2788 std::string WebUsers::getTooltipFilename(
const std::string& username,
2789 const std::string& srcFile,
2790 const std::string& srcFunc,
2791 const std::string& srcId)
2793 std::string filename = (std::string)WEB_LOGIN_DB_PATH + TOOLTIP_DB_PATH +
"/";
2797 mkdir(((std::string)WEB_LOGIN_DB_PATH).c_str(), 0755);
2798 mkdir(((std::string)WEB_LOGIN_DB_PATH + USERS_DB_PATH).c_str(), 0755);
2799 mkdir(filename.c_str(), 0755);
2801 for(
const char& c : username)
2803 (c >=
'a' && c <=
'z') || (c >=
'A' && c <=
'Z') || (c >=
'0' && c <=
'9'))
2808 mkdir(filename.c_str(), 0755);
2810 for(
const char& c : srcFile)
2812 (c >=
'a' && c <=
'z') || (c >=
'A' && c <=
'Z') || (c >=
'0' && c <=
'9'))
2815 for(
const char& c : srcFunc)
2817 (c >=
'a' && c <=
'z') || (c >=
'A' && c <=
'Z') || (c >=
'0' && c <=
'9'))
2820 for(
const char& c : srcId)
2822 (c >=
'a' && c <=
'z') || (c >=
'A' && c <=
'Z') || (c >=
'0' && c <=
'9'))
2829 std::string ots::WebUsers::getUserEmailFromFingerprint(
const std::string& fingerprint)
2831 __COUT__ <<
"Checking if user fingerprint " << fingerprint <<
" is in memory database"
2833 if(certFingerprints_.count(fingerprint))
2835 return certFingerprints_[fingerprint];
2838 __COUT__ <<
"Going to read credential database " << WEB_LOGIN_CERTDATA_PATH << __E__;
2839 std::ifstream f(WEB_LOGIN_CERTDATA_PATH);
2847 if(fp !=
"NOKEY" && fp !=
"")
2849 __COUT__ <<
"Adding user " << email <<
" to list with fingerprint " << fp
2851 certFingerprints_[fp] = email;
2857 remove(WEB_LOGIN_CERTDATA_PATH.c_str());
2860 __COUT__ <<
"Checking again if fingerprint is in memory database" << __E__;
2861 if(certFingerprints_.count(fingerprint))
2863 return certFingerprints_[fingerprint];
2866 __COUT__ <<
"Could not match fingerprint, returning null email" << __E__;
2875 const std::string& srcFile,
2876 const std::string& srcFunc,
2877 const std::string& srcId,
2879 bool temporarySilence)
2881 std::string filename;
2882 bool isForAll = (srcFile ==
"ALL" && srcFunc ==
"ALL" && srcId ==
"ALL");
2886 __COUT__ <<
"Disabling ALL tooltips for user '" << username <<
"' is now set to "
2887 << doNeverShow <<
" (temporarySilence=" << temporarySilence <<
")"
2889 filename = getTooltipFilename(username, SILENCE_ALL_TOOLTIPS_FILENAME,
"",
"");
2893 filename = getTooltipFilename(username, srcFile, srcFunc, srcId);
2894 __COUT__ <<
"Setting tooltip never show for user '" << username <<
"' to "
2895 << doNeverShow <<
" (temporarySilence=" << temporarySilence <<
")"
2900 __COUTTV__(doNeverShow);
2901 __COUTTV__(temporarySilence);
2903 __COUTTV__(srcFunc);
2904 __COUTTV__(srcFile);
2905 __COUTTV__(filename);
2908 FILE* fp = fopen(filename.c_str(),
"w");
2911 if(temporarySilence)
2914 time(0) + 7 * 24 * 60 * 60);
2915 else if(!isForAll && doNeverShow && username == WebUsers::DEFAULT_ADMIN_USERNAME)
2918 fprintf(fp,
"%ld", time(0) + 30 * 24 * 60 * 60);
2920 __COUT__ <<
"User '" << username
2921 <<
"' may be a shared account, so max silence duration for tooltips "
2922 "is 30 days. Silencing now."
2926 fputc(doNeverShow ?
'1' :
'0', fp);
2930 __COUT_ERR__ <<
"Big problem with tooltips! File not accessible: " << filename
2943 const std::string& srcFile,
2944 const std::string& srcFunc,
2945 const std::string& srcId)
2947 if(srcId ==
"ALWAYS")
2950 xmldoc->addTextElementToData(
"ShowTooltip",
"1");
2955 std::string silencefilename =
2956 getTooltipFilename(username, SILENCE_ALL_TOOLTIPS_FILENAME,
"",
"");
2960 __COUTTV__(username);
2962 __COUTTV__(srcFunc);
2963 __COUTTV__(srcFile);
2964 __COUTTV__(silencefilename);
2967 FILE* silencefp = fopen(silencefilename.c_str(),
"r");
2968 if(silencefp != NULL)
2972 fgets(line, 100, silencefp);
2973 sscanf(line,
"%ld", &val);
2977 xmldoc->addTextElementToData(
"ShowTooltip",
"0");
2983 std::string filename = getTooltipFilename(username, srcFile, srcFunc, srcId);
2984 FILE* fp = fopen(filename.c_str(),
"r");
2989 fgets(line, 100, fp);
2990 sscanf(line,
"%ld", &val);
2993 __COUT__ <<
"tooltip value read = " << val <<
" vs time(0)=" << time(0) << __E__;
2997 xmldoc->addTextElementToData(
"ShowTooltip",
2998 val == 1 ?
"0" : (time(0) > val ?
"1" :
"0"));
3002 xmldoc->addTextElementToData(
"ShowTooltip",
"1");
3012 (
"rm -rf " + (std::string)WEB_LOGIN_DB_PATH + TOOLTIP_DB_PATH +
"/" + userNeedle)
3014 __COUT__ <<
"Successfully reset Tooltips for user " << userNeedle << __E__;
3022 std::string silencefilename = getTooltipFilename(
3023 username, SILENCE_ALL_TOOLTIPS_FILENAME,
"",
"");
3025 __COUTV__(silencefilename);
3026 FILE* silencefp = fopen(silencefilename.c_str(),
"w");
3027 if(silencefp != NULL)
3029 fputs(
"1", silencefp);
3060 bool includeAccounts,
3061 std::map<std::string /*groupName*/, WebUsers::permissionLevel_t>
3064 if(permissionMap.size() == 0)
3066 __COUTT__ <<
"Getting local permissions for user " << uid << __E__;
3071 if(isInactiveForGroup(permissionMap))
3074 uint64_t userIndex = searchUsersDatabaseForUserId(uid);
3075 __COUT__ <<
"Gettings settings for user: " << Users_[userIndex].username_ << __E__;
3077 std::string fn = (std::string)WEB_LOGIN_DB_PATH +
3078 (std::string)USERS_PREFERENCES_PATH + Users_[userIndex].username_ +
3079 "." + (std::string)USERS_PREFERENCES_FILETYPE;
3083 __COUT__ <<
"Preferences file: " << fn << __E__;
3087 __COUT__ <<
"Preferences are defaults." << __E__;
3089 xmldoc->addTextElementToData(PREF_XML_BGCOLOR_FIELD, PREF_XML_BGCOLOR_DEFAULT);
3090 xmldoc->addTextElementToData(PREF_XML_DBCOLOR_FIELD, PREF_XML_DBCOLOR_DEFAULT);
3091 xmldoc->addTextElementToData(PREF_XML_WINCOLOR_FIELD, PREF_XML_WINCOLOR_DEFAULT);
3092 xmldoc->addTextElementToData(PREF_XML_LAYOUT_FIELD, PREF_XML_LAYOUT_DEFAULT);
3096 __COUT__ <<
"Saved Preferences found." << __E__;
3101 if(includeAccounts && isAdminForGroup(permissionMap))
3103 __COUT__ <<
"Admin on our hands" << __E__;
3105 xmldoc->addTextElementToData(PREF_XML_ACCOUNTS_FIELD,
"");
3107 if(Users_.size() == 0)
3109 __COUT__ <<
"Missing users? Attempting to load database" << __E__;
3114 for(uint64_t i = 0; i < Users_.size(); ++i)
3117 "username", Users_[i].username_, PREF_XML_ACCOUNTS_FIELD);
3119 "display_name", Users_[i].displayName_, PREF_XML_ACCOUNTS_FIELD);
3121 if(Users_[i].email_.size() > i)
3124 "useremail", Users_[i].email_, PREF_XML_ACCOUNTS_FIELD);
3134 PREF_XML_ACCOUNTS_FIELD);
3137 "nac", Users_[i].getNewAccountCode().c_str(), PREF_XML_ACCOUNTS_FIELD);
3142 fn = (std::string)WEB_LOGIN_DB_PATH + (std::string)USERS_PREFERENCES_PATH +
3143 (std::string)SYSTEM_PREFERENCES_PREFIX +
"." +
3144 (std::string)USERS_PREFERENCES_FILETYPE;
3147 __COUT__ <<
"System Preferences are defaults." << __E__;
3149 xmldoc->addTextElementToData(PREF_XML_SYSLAYOUT_FIELD,
3150 PREF_XML_SYSLAYOUT_DEFAULT);
3154 __COUT__ <<
"Saved System Preferences found." << __E__;
3161 xmldoc->addTextElementToData(PREF_XML_PERMISSIONS_FIELD,
3165 xmldoc->addTextElementToData(PREF_XML_USERLOCK_FIELD, usersUsernameWithLock_);
3168 xmldoc->addTextElementToData(PREF_XML_USERNAME_FIELD,
getUsersUsername(uid));
3174 xmldoc->addTextElementToData(
"ots_remote_address",
3175 remoteLoginVerificationIP_ +
":" +
3184 const std::string& preferenceName,
3185 const std::string& preferenceValue)
3187 uint64_t userIndex = searchUsersDatabaseForUserId(uid);
3192 std::string safePreferenceName =
"";
3193 for(
const auto& c : preferenceName)
3194 if((c >=
'a' && c <=
'z') || (c >=
'A' && c <=
'Z') || (c >=
'0' && c <=
'9') ||
3195 (c >=
'-' || c <=
'_'))
3196 safePreferenceName += c;
3198 std::string dir = (std::string)WEB_LOGIN_DB_PATH +
3199 (std::string)USERS_PREFERENCES_PATH +
"generic_" +
3200 safePreferenceName +
"/";
3203 mkdir(dir.c_str(), 0755);
3205 std::string fn = Users_[userIndex].username_ +
"_" + safePreferenceName +
"." +
3206 (std::string)USERS_PREFERENCES_FILETYPE;
3208 __COUT__ <<
"Preferences file: " << (dir + fn) << __E__;
3210 FILE* fp = fopen((dir + fn).c_str(),
"w");
3213 fprintf(fp,
"%s", preferenceValue.c_str());
3217 __COUT_ERR__ <<
"Preferences file could not be opened for writing!" << __E__;
3225 const std::string& preferenceName,
3228 uint64_t userIndex = searchUsersDatabaseForUserId(uid);
3233 std::string safePreferenceName =
"";
3234 for(
const auto& c : preferenceName)
3235 if((c >=
'a' && c <=
'z') || (c >=
'A' && c <=
'Z') || (c >=
'0' && c <=
'9') ||
3236 (c >=
'-' || c <=
'_'))
3237 safePreferenceName += c;
3239 std::string dir = (std::string)WEB_LOGIN_DB_PATH +
3240 (std::string)USERS_PREFERENCES_PATH +
"generic_" +
3241 safePreferenceName +
"/";
3243 std::string fn = Users_[userIndex].username_ +
"_" + safePreferenceName +
"." +
3244 (std::string)USERS_PREFERENCES_FILETYPE;
3246 __COUT__ <<
"Preferences file: " << (dir + fn) << __E__;
3249 FILE* fp = fopen((dir + fn).c_str(),
"r");
3252 fseek(fp, 0, SEEK_END);
3253 const long size = ftell(fp);
3254 char* line =
new char
3258 fread(line, 1, size, fp);
3261 std::string retVal(line, size);
3264 __COUT__ <<
"Read value (sz = " << retVal.size() <<
") " << retVal << __E__;
3266 xmldoc->addTextElementToData(safePreferenceName, retVal);
3270 __COUT__ <<
"Using default value." << __E__;
3274 xmldoc->addTextElementToData(safePreferenceName,
"");
3281 const std::string& bgcolor,
3282 const std::string& dbcolor,
3283 const std::string& wincolor,
3284 const std::string& layout,
3285 const std::string& syslayout,
3286 const std::string& aliaslayout,
3287 const std::string& sysaliaslayout)
3289 std::map<std::string , WebUsers::permissionLevel_t> permissionMap =
3291 if(isInactiveForGroup(permissionMap))
3294 uint64_t userIndex = searchUsersDatabaseForUserId(uid);
3295 __COUT__ <<
"Changing settings for user: " << Users_[userIndex].username_ << __E__;
3297 std::string fn = (std::string)WEB_LOGIN_DB_PATH +
3298 (std::string)USERS_PREFERENCES_PATH + Users_[userIndex].username_ +
3299 "." + (std::string)USERS_PREFERENCES_FILETYPE;
3301 __COUT__ <<
"Preferences file: " << fn << __E__;
3304 prefXml.addTextElementToData(PREF_XML_BGCOLOR_FIELD, bgcolor);
3305 prefXml.addTextElementToData(PREF_XML_DBCOLOR_FIELD, dbcolor);
3306 prefXml.addTextElementToData(PREF_XML_WINCOLOR_FIELD, wincolor);
3307 prefXml.addTextElementToData(PREF_XML_LAYOUT_FIELD, layout);
3308 prefXml.addTextElementToData(PREF_XML_ALIAS_LAYOUT_FIELD, aliaslayout);
3313 if(!isAdminForGroup(permissionMap))
3317 fn = (std::string)WEB_LOGIN_DB_PATH + (std::string)USERS_PREFERENCES_PATH +
3318 (std::string)SYSTEM_PREFERENCES_PREFIX +
"." +
3319 (std::string)USERS_PREFERENCES_FILETYPE;
3322 sysPrefXml.addTextElementToData(PREF_XML_SYSLAYOUT_FIELD, syslayout);
3323 sysPrefXml.addTextElementToData(PREF_XML_SYSALIAS_LAYOUT_FIELD, sysaliaslayout);
3335 std::map<std::string , WebUsers::permissionLevel_t> permissionMap =
3341 __COUTV__(actingUser);
3343 __COUTV__(usersUsernameWithLock_);
3345 __COUTV__(username);
3346 __COUTV__(isUserActive);
3349 (isUserActive || !WebUsers::CareAboutCookieCodes_))
3351 if(!WebUsers::CareAboutCookieCodes_ && !isUserActive &&
3353 DEFAULT_ADMIN_USERNAME)
3356 <<
"User '" << actingUser
3357 <<
"' tried to lock for a user other than admin in wiz mode. Not allowed."
3361 else if(!isAdminForGroup(permissionMap) &&
3362 actingUser != username)
3364 __COUT_ERR__ <<
"A non-admin user '" << actingUser
3365 <<
"' tried to lock for a user other than self. Not allowed."
3369 usersUsernameWithLock_ = username;
3371 else if(!lock && usersUsernameWithLock_ == username)
3372 usersUsernameWithLock_ =
"";
3376 __COUT_INFO__ <<
"User '" << username <<
"' is inactive so not giving lock."
3379 __COUT_ERR__ <<
"Failed to lock for user '" << username <<
".'" << __E__;
3383 __COUT_INFO__ <<
"User '" << username <<
"' has locked out the system!" << __E__;
3387 std::string securityFileName = USER_WITH_LOCK_FILE;
3388 FILE* fp = fopen(securityFileName.c_str(),
"w");
3391 __COUT_INFO__ <<
"USER_WITH_LOCK_FILE " << USER_WITH_LOCK_FILE
3392 <<
" not found. Ignoring." << __E__;
3396 fprintf(fp,
"%s", usersUsernameWithLock_.c_str());
3407 const std::string& username,
3408 const std::string& displayname,
3409 const std::string& email,
3410 const std::string& permissions)
3412 std::map<std::string , WebUsers::permissionLevel_t> permissionMap =
3414 if(!isAdminForGroup(permissionMap))
3417 __SS__ <<
"Only admins can modify user settings." << __E__;
3421 uint64_t i = searchUsersDatabaseForUserId(actingUid);
3422 uint64_t modi = searchUsersDatabaseForUsername(username);
3427 __COUT_INFO__ <<
"Admin password reset." << __E__;
3428 Users_[modi].setModifier(Users_[i].username_);
3429 Users_[modi].salt_ =
"";
3430 Users_[modi].loginFailureCount_ = 0;
3431 saveDatabaseToFile(DB_USERS);
3434 __SS__ <<
"Cannot modify first user" << __E__;
3438 if(username.length() < USERNAME_LENGTH)
3440 __SS__ <<
"Invalid Username, must be length " << USERNAME_LENGTH << __E__;
3443 if(displayname.length() < DISPLAY_NAME_LENGTH)
3445 __SS__ <<
"Invalid Display Name; must be length " << DISPLAY_NAME_LENGTH << __E__;
3449 __COUT__ <<
"Input Permissions: " << permissions << __E__;
3450 std::map<std::string , WebUsers::permissionLevel_t> newPermissionsMap;
3454 case MOD_TYPE_UPDATE:
3456 __COUT__ <<
"MOD_TYPE_UPDATE " << username <<
" := " << permissions << __E__;
3458 if(modi == NOT_FOUND_IN_DATABASE)
3460 __SS__ <<
"User not found!? Should not happen." << __E__;
3466 for(uint64_t i = 0; i < Users_.size(); ++i)
3469 else if(Users_[i].displayName_ == displayname)
3471 __SS__ <<
"Display Name '" << displayname
3472 <<
"' already exists! Please choose a unique display name."
3478 Users_[modi].displayName_ = displayname;
3479 Users_[modi].email_ = email;
3483 bool wasInactive = isInactiveForGroup(Users_[modi].permissions_);
3486 if(newPermissionsMap.size() == 0)
3487 Users_[modi].permissions_[WebUsers::DEFAULT_USER_GROUP] =
3488 std::atoi(permissions.c_str());
3489 else if(newPermissionsMap.size() == 1 &&
3490 newPermissionsMap.find(WebUsers::DEFAULT_USER_GROUP) ==
3491 newPermissionsMap.end())
3493 if(newPermissionsMap.begin()->first ==
"")
3494 Users_[modi].permissions_[WebUsers::DEFAULT_USER_GROUP] =
3495 newPermissionsMap.begin()->second;
3498 newPermissionsMap[WebUsers::DEFAULT_USER_GROUP] =
3499 newPermissionsMap.begin()->second;
3500 Users_[modi].permissions_ = newPermissionsMap;
3504 Users_[modi].permissions_ = newPermissionsMap;
3509 !isInactiveForGroup(Users_[modi].permissions_))
3511 __COUT__ <<
"Reactivating " << username << __E__;
3512 Users_[modi].loginFailureCount_ = 0;
3513 Users_[modi].salt_ =
"";
3519 if(i == NOT_FOUND_IN_DATABASE)
3521 __SS__ <<
"Master User not found!? Should not happen." << __E__;
3524 Users_[modi].setModifier(Users_[i].username_);
3530 __COUT__ <<
"MOD_TYPE_ADD " << username <<
" - " << displayname << __E__;
3535 if(i == NOT_FOUND_IN_DATABASE)
3537 __SS__ <<
"Master User not found!? Should not happen." << __E__;
3540 Users_.back().setModifier(Users_[i].username_);
3543 if(permissions.size())
3546 actingUid, MOD_TYPE_UPDATE, username, displayname, email, permissions);
3550 case MOD_TYPE_DELETE:
3551 __COUT__ <<
"MOD_TYPE_DELETE " << username <<
" - " << displayname << __E__;
3552 deleteAccount(username, displayname);
3555 __SS__ <<
"Undefined command - do nothing " << username << __E__;
3559 saveDatabaseToFile(DB_USERS);
3560 loadSecuritySelection();
3568 std::set<unsigned int> activeUserIndices;
3569 for(uint64_t i = 0; i < ActiveSessions_.size(); ++i)
3570 activeUserIndices.emplace(
3571 searchUsersDatabaseForUserId(ActiveSessions_[i].userId_));
3573 for(
const auto& sessionPair : RemoteSessions_)
3574 activeUserIndices.emplace(
3575 searchUsersDatabaseForUserId(sessionPair.second.userId_));
3576 return activeUserIndices.size();
3584 std::set<unsigned int> activeUserIndices;
3585 for(uint64_t i = 0; i < ActiveSessions_.size(); ++i)
3586 activeUserIndices.emplace(
3587 searchUsersDatabaseForUserId(ActiveSessions_[i].userId_));
3589 for(
const auto& sessionPair : RemoteSessions_)
3590 activeUserIndices.emplace(
3591 searchUsersDatabaseForUserId(sessionPair.second.userId_));
3593 std::string activeUsersString =
"";
3594 bool addComma =
false;
3595 for(
const auto& i : activeUserIndices)
3597 if(i >= Users_.size())
3601 activeUsersString +=
",";
3605 activeUsersString += Users_[i].displayName_;
3607 if(activeUserIndices.size() == 0 &&
3609 WebUsers::SECURITY_TYPE_NONE)
3610 activeUsersString += WebUsers::DEFAULT_ADMIN_DISPLAY_NAME;
3612 __COUTVS__(20, activeUsersString);
3613 return activeUsersString;
3621 std::set<unsigned int> activeUserIndices;
3622 for(uint64_t i = 0; i < ActiveSessions_.size(); ++i)
3623 activeUserIndices.emplace(
3624 searchUsersDatabaseForUserId(ActiveSessions_[i].userId_));
3626 for(
const auto& sessionPair : RemoteSessions_)
3627 activeUserIndices.emplace(
3628 searchUsersDatabaseForUserId(sessionPair.second.userId_));
3630 std::string activeUsersString =
"";
3631 bool addComma =
false;
3632 for(
const auto& i : activeUserIndices)
3634 if(i >= Users_.size())
3638 activeUsersString +=
",";
3642 activeUsersString += Users_[i].username_;
3644 if(activeUserIndices.size() == 0 &&
3646 WebUsers::SECURITY_TYPE_NONE)
3647 activeUsersString += WebUsers::DEFAULT_ADMIN_USERNAME;
3649 __COUTVS__(20, activeUsersString);
3650 return activeUsersString;
3658 uint64_t uid = searchUsersDatabaseForUsername(DEFAULT_ADMIN_USERNAME);
3665 void WebUsers::loadUserWithLock()
3667 char username[300] =
"";
3669 std::string securityFileName = USER_WITH_LOCK_FILE;
3670 FILE* fp = fopen(securityFileName.c_str(),
"r");
3673 __COUT_INFO__ <<
"USER_WITH_LOCK_FILE " << USER_WITH_LOCK_FILE
3674 <<
" not found. Defaulting to admin lock." << __E__;
3677 sprintf(username,
"%s", DEFAULT_ADMIN_USERNAME.c_str());
3681 fgets(username, 300, fp);
3688 __COUT__ <<
"Attempting to load username with lock: " << username << __E__;
3690 if(strlen(username) == 0)
3692 __COUT_INFO__ <<
"Loaded state for user-with-lock is unlocked." << __E__;
3696 uint64_t i = searchUsersDatabaseForUsername(username);
3697 if(i == NOT_FOUND_IN_DATABASE)
3699 __COUT_INFO__ <<
"username " << username <<
" not found in database. Ignoring."
3703 __COUT__ <<
"Setting lock" << __E__;
3711 const std::string& message)
3720 const std::string& subject,
3721 const std::string& message,
3724 std::vector<std::string> targetUsers;
3734 const std::string& subject,
3735 const std::string& message,
3738 systemMessageCleanup();
3740 std::string fullMessage = StringMacros::encodeURIComponent(
3741 (subject ==
"" ?
"" : (subject +
": ")) + message);
3744 std::cout << __COUT_HDR_FL__ <<
"addSystemMessage() fullMessage: " << fullMessage
3748 std::set<std::string> targetEmails;
3750 for(
const auto& targetUser : targetUsers)
3754 if(targetUser ==
"" || (targetUser !=
"*" && targetUser.size() < 3))
3756 __COUT__ <<
"Illegal username '" << targetUser <<
"'" << __E__;
3759 __COUTTV__(targetUser);
3763 if(doEmail && targetUser ==
"*")
3766 for(
const auto& user : Users_)
3768 if(user.email_.size() > 5 &&
3769 user.email_.find(
'@') != std::string::npos &&
3770 user.email_.find(
'.') != std::string::npos)
3772 __COUT__ <<
"Adding " << user.displayName_
3773 <<
" email: " << user.email_ << __E__;
3774 targetEmails.emplace(user.email_);
3779 else if(targetUser.find(
':') != std::string::npos)
3782 __COUT__ <<
"Treating as group email target: " << targetUser << __E__;
3784 std::map<std::string, WebUsers::permissionLevel_t> targetGroupMap;
3791 if(targetGroupMap.size() == 1)
3796 for(
const auto& user : Users_)
3798 WebUsers::permissionLevel_t userLevel =
3800 targetGroupMap.begin()->first);
3804 __COUTV__((
int)userLevel);
3805 __COUTV__(targetGroupMap.begin()->first);
3807 if(userLevel != WebUsers::PERMISSION_LEVEL_INACTIVE &&
3808 userLevel >= targetGroupMap.begin()->second &&
3809 user.email_.size() > 5 &&
3810 user.email_.find(
'@') != std::string::npos &&
3811 user.email_.find(
'.') != std::string::npos)
3815 targetEmails.emplace(user.email_);
3816 __COUT__ <<
"Adding " << user.displayName_
3817 <<
" email: " << user.email_ << __E__;
3819 addSystemMessageToMap(user.displayName_, fullMessage);
3824 __COUT__ <<
"target Group Map from '" << targetUser <<
"' is empty."
3832 addSystemMessageToMap(targetUser, fullMessage);
3836 for(
const auto& user : Users_)
3838 if(user.displayName_ == targetUser)
3840 if(user.email_.size() > 5 &&
3841 user.email_.find(
'@') != std::string::npos &&
3842 user.email_.find(
'.') != std::string::npos)
3844 targetEmails.emplace(user.email_);
3845 __COUT__ <<
"Adding " << user.displayName_
3846 <<
" email: " << user.email_ << __E__;
3855 __COUTV__(targetEmails.size());
3857 if(doEmail && targetEmails.size())
3861 std::string toList =
"";
3862 bool addComma =
false;
3863 for(
const auto& email : targetEmails)
3872 std::string filename = (std::string)WEB_LOGIN_DB_PATH +
3873 (std::string)USERS_DB_PATH +
"/.tmp_email.txt";
3874 FILE* fp = fopen(filename.c_str(),
"w");
3877 __SS__ <<
"Could not open email file: " << filename << __E__;
3887 fprintf(fp,
"To: %s\n", toList.c_str());
3888 fprintf(fp,
"Subject: %s\n", subject.c_str());
3889 fprintf(fp,
"Content-Type: text/html\n");
3890 fprintf(fp,
"\n<html><pre>%s</pre></html>", message.c_str());
3896 __COUT_WARN__ <<
"Do email was attempted, but no target users had email "
3897 "addresses specified!"
3906 void WebUsers::addSystemMessageToMap(
const std::string& targetUser,
3907 const std::string& fullMessage)
3910 std::lock_guard<std::mutex> lock(systemMessageLock_);
3912 __COUTT__ <<
"Before number of users with system messages: " << systemMessages_.size()
3913 <<
", first user has "
3914 << (systemMessages_.size() ? systemMessages_.begin()->second.size() : 0)
3915 <<
" messages." << __E__;
3917 auto it = systemMessages_.find(targetUser);
3920 if(it != systemMessages_.end() && it->second.size() &&
3921 it->second[it->second.size() - 1].message_ == fullMessage)
3924 if(it == systemMessages_.end())
3926 systemMessages_.emplace(
3927 std::pair<std::string , std::vector<SystemMessage>>(
3928 targetUser, std::vector<SystemMessage>({SystemMessage(fullMessage)})));
3929 __COUTT__ << targetUser <<
" Current System Messages count = " << 1 << __E__;
3934 it->second.push_back(SystemMessage(fullMessage));
3935 __COUTT__ << it->first <<
" Current System Messages count = " << it->second.size()
3939 __COUTT__ <<
"After number of users with system messages: " << systemMessages_.size()
3940 <<
", first user has "
3941 << (systemMessages_.size() ? systemMessages_.begin()->second.size() : 0)
3942 <<
" messages." << __E__;
3951 std::lock_guard<std::mutex> lock(systemMessageLock_);
3953 __COUTT__ <<
"GetLast number of users with system messages: "
3954 << systemMessages_.size() <<
", first user has "
3955 << (systemMessages_.size() ? systemMessages_.begin()->second.size() : 0)
3956 <<
" messages." << __E__;
3958 auto it = systemMessages_.find(
"*");
3959 if(it == systemMessages_.end() || it->second.size() == 0)
3960 return std::make_pair(
"", 0);
3962 return std::make_pair(it->second.back().message_, it->second.back().creationTime_);
3971 std::string retStr =
"";
3974 std::lock_guard<std::mutex> lock(systemMessageLock_);
3976 for(
auto& userSysMessages : systemMessages_)
3978 for(
auto& userSysMessage : userSysMessages.second)
3980 if(userSysMessage.deliveredRemote_)
3985 retStr += userSysMessages.first;
3986 retStr +=
"|" + std::to_string(userSysMessage.creationTime_);
3987 retStr +=
"|" + userSysMessage.message_;
3988 userSysMessage.deliveredRemote_ =
true;
4003 __COUTS__(20) <<
"Current System Messages: " << targetUser << __E__;
4004 std::string retStr =
"";
4010 std::lock_guard<std::mutex> lock(systemMessageLock_);
4012 __COUTS__(20) <<
"Number of users with system messages: "
4013 << systemMessages_.size() << __E__;
4016 auto it = systemMessages_.find(
"*");
4017 for(uint64_t i = 0; it != systemMessages_.end() && i < it->second.size(); ++i)
4022 sprintf(tmp,
"%lu", it->second[i].creationTime_);
4023 retStr += std::string(tmp) +
"|" + it->second[i].message_;
4029 __COUTVS__(20, targetUser);
4030 it = systemMessages_.find(targetUser);
4033 for(
auto systemMessagePair : systemMessages_)
4034 __COUTS__(20) << systemMessagePair.first <<
" "
4035 << systemMessagePair.second.size() <<
" "
4036 << (systemMessagePair.second.size()
4037 ? systemMessagePair.second[0].message_
4041 if(it != systemMessages_.end())
4043 __COUTS__(20) <<
"Message count: " << it->second.size() <<
", Last Message: "
4044 << (it->second.size() ? it->second.back().message_ :
"")
4048 for(uint64_t i = 0; it != systemMessages_.end() && i < it->second.size(); ++i)
4053 sprintf(tmp,
"%lu", it->second[i].creationTime_);
4054 retStr += std::string(tmp) +
"|" + it->second[i].message_;
4057 if(!it->second[i].delivered_)
4058 it->second[i].firstDeliveryTime_ = time(0);
4059 it->second[i].delivered_ =
true;
4064 __COUTS__(20) <<
"retStr: " << retStr << __E__;
4066 systemMessageCleanup();
4074 void WebUsers::systemMessageCleanup()
4077 std::lock_guard<std::mutex> lock(systemMessageLock_);
4079 const time_t now = time(0);
4081 __COUTT__ <<
"Before cleanup number of users with system messages: "
4082 << systemMessages_.size() <<
", first user has "
4083 << (systemMessages_.size() ? systemMessages_.begin()->second.size() : 0)
4084 <<
" messages." << __E__;
4085 for(
auto& userMessagesPair : systemMessages_)
4087 for(uint64_t i = 0; i < userMessagesPair.second.size(); ++i)
4089 bool shouldRemove =
false;
4091 if(userMessagesPair.first ==
"*")
4096 shouldRemove =
true;
4103 if(userMessagesPair.second[i].delivered_ &&
4104 userMessagesPair.second[i].firstDeliveryTime_ +
4107 shouldRemove =
true;
4109 else if(userMessagesPair.second[i].creationTime_ +
4112 shouldRemove =
true;
4117 __COUTT__ << userMessagesPair.first
4118 <<
" at time: " << userMessagesPair.second[i].creationTime_
4119 <<
" system messages: " << userMessagesPair.second.size()
4123 userMessagesPair.second.erase(userMessagesPair.second.begin() + i);
4128 __COUTT__ <<
"User '" << userMessagesPair.first
4129 <<
"' remaining system messages: " << userMessagesPair.second.size()
4132 __COUTT__ <<
"After cleanup number of users with system messages: "
4133 << systemMessages_.size() <<
", first user has "
4134 << (systemMessages_.size() ? systemMessages_.begin()->second.size() : 0)
4135 <<
" messages." << __E__;
4143 void WebUsers::loadSecuritySelection()
4145 std::string securityFileName = SECURITY_FILE_NAME;
4146 FILE* fp = fopen(securityFileName.c_str(),
"r");
4147 char line[100] =
"";
4149 fgets(line, 100, fp);
4153 while(i < strlen(line) && line[i] >=
'A' && line[i] <=
'z')
4157 if(strcmp(line, SECURITY_TYPE_NONE.c_str()) == 0 ||
4158 strcmp(line, SECURITY_TYPE_DIGEST_ACCESS.c_str()) == 0)
4159 securityType_ = line;
4161 securityType_ = SECURITY_TYPE_DEFAULT;
4163 __COUT__ <<
"The current security type is " << securityType_ << __E__;
4168 if(securityType_ == SECURITY_TYPE_NONE)
4169 CareAboutCookieCodes_ =
false;
4171 CareAboutCookieCodes_ =
true;
4173 __COUT__ <<
"CareAboutCookieCodes_: " << CareAboutCookieCodes_ << __E__;
4175 loadIPAddressSecurity();
4181 void WebUsers::loadIPAddressSecurity()
4183 ipAccessAccept_.clear();
4184 ipAccessReject_.clear();
4185 ipAccessBlacklist_.clear();
4187 FILE* fp = fopen((IP_ACCEPT_FILE).c_str(),
"r");
4193 while(fgets(line, 300, fp))
4197 if(len > 2 && line[len - 1] ==
'\n')
4198 line[len - 1] =
'\0';
4199 ipAccessAccept_.emplace(line);
4206 __COUTV__(ipAccessAccept_.size());
4208 fp = fopen((IP_REJECT_FILE).c_str(),
"r");
4211 while(fgets(line, 300, fp))
4215 if(len > 2 && line[len - 1] ==
'\n')
4216 line[len - 1] =
'\0';
4217 ipAccessReject_.emplace(line);
4224 __COUTV__(ipAccessReject_.size());
4226 fp = fopen((IP_BLACKLIST_FILE).c_str(),
"r");
4229 while(fgets(line, 300, fp))
4233 if(len > 2 && line[len - 1] ==
'\n')
4234 line[len - 1] =
'\0';
4235 ipAccessBlacklist_.emplace(line);
4242 __COUTV__(ipAccessBlacklist_.size());
4246 void WebUsers::NACDisplayThread(
const std::string& nac,
const std::string& user)
4257 std::this_thread::sleep_for(std::chrono::seconds(2));
4259 <<
"\n******************************************************************** "
4262 <<
"\n******************************************************************** "
4264 __COUT__ <<
"\n\nNew account code = " << nac <<
" for user: " << user <<
"\n"
4267 <<
"\n******************************************************************** "
4270 <<
"\n******************************************************************** "
4276 void WebUsers::deleteUserData()
4278 __COUT__ <<
"$$$$$$$$$$$$$$ Deleting ALL service user data... $$$$$$$$$$$$" << __E__;
4282 (
"rm -rf " + (std::string)WEB_LOGIN_DB_PATH + HASHES_DB_PATH +
"/*").c_str());
4284 (
"rm -rf " + (std::string)WEB_LOGIN_DB_PATH + USERS_DB_PATH +
"/*").c_str());
4286 (
"rm -rf " + (std::string)WEB_LOGIN_DB_PATH + USERS_LOGIN_HISTORY_PATH +
"/*")
4289 (
"rm -rf " + (std::string)WEB_LOGIN_DB_PATH + USERS_PREFERENCES_PATH +
"/*")
4291 std::system((
"rm -rf " + (std::string)WEB_LOGIN_DB_PATH + TOOLTIP_DB_PATH).c_str());
4293 std::string serviceDataPath = __ENV__(
"SERVICE_DATA_PATH");
4295 std::system((
"rm -rf " + std::string(serviceDataPath) +
"/MacroData/").c_str());
4296 std::system((
"rm -rf " + std::string(serviceDataPath) +
"/MacroHistory/").c_str());
4297 std::system((
"rm -rf " + std::string(serviceDataPath) +
"/MacroExport/").c_str());
4301 (
"rm -rf " + std::string(serviceDataPath) +
"/ConsolePreferences/").c_str());
4304 std::system((
"rm -rf " + std::string(serviceDataPath) +
"/CodeEditorData/").c_str());
4307 std::system((
"rm -rf " + std::string(serviceDataPath) +
"/OtsWizardData/").c_str());
4310 std::system((
"rm -rf " + std::string(serviceDataPath) +
"/ProgressBarData/").c_str());
4313 std::system((
"rm -rf " + std::string(serviceDataPath) +
"/RunNumber/").c_str());
4314 std::system((
"rm -rf " + std::string(serviceDataPath) +
"/RunControlData/").c_str());
4317 std::system((
"rm -rf " + std::string(serviceDataPath) +
"/VisualizerData/").c_str());
4324 std::system((
"rm -rf " + std::string(__ENV__(
"LOGBOOK_DATA_PATH")) +
"/").c_str());
4326 __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
@ SYS_CLEANUP_USER_MESSAGE_TIME
15 seconds - allows multiple browser tabs/devices to receive the same message
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()