otsdaq  v1_01_02
 All Classes Namespaces Functions
WebUsers.h
1 #ifndef _ots_Utilities_WebUsers_h_
2 #define _ots_Utilities_WebUsers_h_
3 
4 #include "otsdaq-core/MessageFacility/MessageFacility.h"
5 #include "otsdaq-core/Macros/CoutHeaderMacros.h"
6 #include "otsdaq-core/SOAPUtilities/SOAPMessenger.h"
7 
8 #include <string>
9 #include <vector>
10 #include <iostream>
11 
12 #define WEB_LOGIN_DB_PATH std::string(getenv("SERVICE_DATA_PATH")) + "/LoginData/"
13 #define HASHES_DB_PATH "HashesData/"
14 #define USERS_DB_PATH "UsersData/"
15 #define USERS_LOGIN_HISTORY_PATH USERS_DB_PATH + "UserLoginHistoryData/"
16 #define USERS_PREFERENCES_PATH USERS_DB_PATH + "UserPreferencesData/"
17 #define TOOLTIP_DB_PATH USERS_DB_PATH + "/TooltipData/"
18 
19 
20 
21 //TODO -- include IP address handling!? Note from RAR -- I think IP addresses are being recorded now upon login.
22 
23 namespace ots
24 {
25 
26 class HttpXmlDocument;
27 
28 class WebUsers
29 {
30 public:
31  WebUsers();
32 
33  enum {
34  SESSION_ID_LENGTH = 512,
35  COOKIE_CODE_LENGTH = 512,
36  NOT_FOUND_IN_DATABASE = uint64_t(-1),
37  USERNAME_LENGTH = 4,
38  DISPLAY_NAME_LENGTH = 4,
39  };
40 
41  enum {
42  DB_SAVE_OPEN_AND_CLOSE,
43  DB_SAVE_OPEN,
44  DB_SAVE_CLOSE
45  };
46 
47  enum {
48  DB_USERS,
49  DB_HASHES
50  };
51 
52  enum {
53  MOD_TYPE_UPDATE,
54  MOD_TYPE_ADD,
55  MOD_TYPE_DELETE
56  };
57 
58  static const std::string DEFAULT_ADMIN_USERNAME;
59  static const std::string DEFAULT_ADMIN_DISPLAY_NAME;
60 
61  static const std::string REQ_NO_LOGIN_RESPONSE;
62  static const std::string REQ_NO_PERMISSION_RESPONSE;
63  static const std::string REQ_USER_LOCKOUT_RESPONSE;
64 
65  static const std::string SECURITY_TYPE_NONE;
66  static const std::string SECURITY_TYPE_DIGEST_ACCESS;
67  static const std::string SECURITY_TYPE_KERBEROS;
68 
69  bool createNewAccount (std::string username, std::string displayName);
70  void cleanupExpiredEntries (std::vector<std::string> *loggedOutUsernames = 0);
71  std::string createNewLoginSession (std::string uuid, std::string ip = "0");
72 
73  uint64_t attemptActiveSession (std::string uuid, std::string &jumbledUser, std::string jumbledPw, std::string &newAccountCode);
74  uint64_t isCookieCodeActiveForLogin (std::string uuid, std::string &cookieCode,std::string &username);
75  bool cookieCodeIsActiveForRequest (std::string &cookieCode, uint8_t *userPermissions = 0, uint64_t *uid = 0, std::string ip = "0", bool refresh = true, std::string *userWithLock = 0);
76  uint64_t cookieCodeLogout (std::string cookieCode, bool logoutOtherUserSessions, uint64_t *uid = 0, std::string ip = "0");
77 
78  std::string getUsersDisplayName (uint64_t uid);
79  std::string getUsersUsername (uint64_t uid);
80  uint64_t getActiveSessionCountForUser (uint64_t uid);
81  uint8_t getPermissionsForUser (uint64_t uid);
82  void insertSettingsForUser (uint64_t uid, HttpXmlDocument *xmldoc,bool includeAccounts=false);
83  std::string getGenericPreference (uint64_t uid, const std::string &preferenceName, HttpXmlDocument *xmldoc = 0) const;
84 
85  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);
86  void setGenericPreference (uint64_t uid, const std::string &preferenceName, const std::string &preferenceValue);
87  static void tooltipCheckForUsername (const std::string& username, HttpXmlDocument *xmldoc, const std::string &srcFile, const std::string &srcFunc, const std::string &srcId);
88  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);
89 
90  void modifyAccountSettings (uint64_t uid_master, uint8_t cmd_type, std::string username, std::string displayname, std::string permissions);
91  bool setUserWithLock (uint64_t uid_master, bool lock, std::string username);
92  std::string getUserWithLock () { return usersUsernameWithLock_; }
93 
94  std::string getActiveUsersString ();
95 
96  bool getUserInfoForCookie (std::string &cookieCode, std::string *userName, std::string *displayName = 0, uint64_t *activeSessionIndex = 0);
97 
98  bool isUsernameActive (std::string username) const;
99  bool isUserIdActive (uint64_t uid) const;
100  uint64_t getAdminUserID ();
101  std::string getSecurity ();
102 
103  static void deleteUserData ();
104  static void resetAllUserTooltips (const std::string &userNeedle = "*");
105 
106  static void NACDisplayThread (std::string nac, std::string user);
107 
108 private:
109  void loadSecuritySelection ();
110  void loadUserWithLock ();
111  unsigned int hexByteStrToInt (const char *h);
112  void intToHexStr (uint8_t i, char *h);
113  std::string sha512 (std::string user, std::string password, std::string &salt);
114  std::string dejumble (std::string jumbledUser, std::string sessionId);
115  std::string createNewActiveSession (uint64_t uid,std::string ip = "0", uint64_t asIndex = 0);
116  bool addToHashesDatabase (std::string hash);
117  std::string genCookieCode ();
118  std::string refreshCookieCode (unsigned int i, bool enableRefresh = true);
119  void removeActiveSessionEntry (unsigned int i);
120  void removeLoginSessionEntry (unsigned int i);
121  bool deleteAccount (std::string username, std::string displayName);
122 
123  void saveToDatabase (FILE * fp, std::string field, std::string value, uint8_t type = DB_SAVE_OPEN_AND_CLOSE, bool addNewLine = true);
124  bool saveDatabaseToFile (uint8_t db);
125  bool loadDatabases ();
126 
127  uint64_t searchUsersDatabaseForUsername (std::string username) const;
128  uint64_t searchUsersDatabaseForUserId (uint64_t uid) const;
129  uint64_t searchLoginSessionDatabaseForUUID (std::string uuid) const;
130  uint64_t searchHashesDatabaseForHash (std::string hash);
131  uint64_t searchActiveSessionDatabaseForCookie (std::string cookieCode) const;
132 
133  static std::string getTooltipFilename (const std::string& username, const std::string &srcFile, const std::string &srcFunc, const std::string &srcId);
134 
135 
136 
137  std::vector<std::string> UsersDatabaseEntryFields,HashesDatabaseEntryFields;
138  bool CareAboutCookieCodes_;
139  std::string securityType_;
140 
141  //"Login Session" database associations ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
142  //Generate random sessionId when receive a unique user ID (UUID)
143  //reject UUID that have been used recently (e.g. last 5 minutes)
144  //Maintain list of active sessionIds and associated UUID
145  //remove from list if been idle after some time or login attempts (e.g. 5 minutes or 3 login attempts)
146  //maybe track IP address, to block multiple failed login attempts from same IP.
147  //Use sessionId to un-jumble login attempts, lookup using UUID
148  std::vector<std::string> LoginSessionIdVector, LoginSessionUUIDVector, LoginSessionIpVector;
149  std::vector<time_t> LoginSessionStartTimeVector;
150  std::vector<uint8_t> LoginSessionAttemptsVector;
151  enum {
152  LOGIN_SESSION_EXPIRATION_TIME = 5*60, //5 minutes
153  LOGIN_SESSION_ATTEMPTS_MAX = 5, //5 attempts on same session, forces new session
154  };
155 
156  //"Active Session" database associations ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
157  //Maintain list of valid cookieCodes and associated user
158  //all request must come with a valid cookieCode, else server fails request
159  //On logout request, invalidate cookieCode
160  //cookieCode expires after some idle time (e.g. 5 minutes) and
161  //is renewed and possibly changed each request
162  //"single user - multiple locations" issue resolved using ActiveSessionIndex
163  //where each independent login starts a new thread of cookieCodes tagged with ActiveSessionIndex
164  //if cookieCode not refreshed, then return most recent cookie code
165  std::vector<std::string> ActiveSessionCookieCodeVector, ActiveSessionIpVector;
166  std::vector<uint64_t> ActiveSessionUserIdVector, ActiveSessionIndex;
167  std::vector<time_t> ActiveSessionStartTimeVector;
168  enum {
169  ACTIVE_SESSION_EXPIRATION_TIME = 120*60, //120 minutes, cookie is changed every half period of ACTIVE_SESSION_EXPIRATION_TIME
170  ACTIVE_SESSION_COOKIE_OVERLAP_TIME = 10*60, //10 minutes of overlap when new cookie is generated
171  ACTIVE_SESSION_STALE_COOKIE_LIMIT = 10, //10 stale cookies allowed for each active user
172  };
173 
174  //"Users" database associations ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
175  //Maintain list of acceptable Usernames and associate:
176  //permissions index (e.g. users, experts, masters) 0 to 255
177  //0 := account inactive, not allowed to login (could be due to too many failed login attempts)
178  //Last Login attempt time, and last USERS_LOGIN_HISTORY_SIZE successful logins
179  //Name to display
180  //random salt, before first login salt is empty string ""
181  //Keep count of login attempt failures. Limit failures per unit time (e.g. 5 per hour)
182  //Preferences (e.g. color scheme, etc)
183  //Username appends to preferences file, and login history file
184  //UsersLastModifierUsernameVector - is username of last master user to modify something about account
185  //UsersLastModifierTimeVector - is time of last modify by a master user
186  std::vector<std::string> UsersUsernameVector, UsersDisplayNameVector, UsersSaltVector, UsersLastModifierUsernameVector;
187  std::vector<uint8_t> UsersPermissionsVector;
188  std::vector<uint64_t> UsersUserIdVector;
189  std::vector<time_t> UsersLastLoginAttemptVector, UsersAccountCreatedTimeVector, UsersLastModifiedTimeVector;
190  std::vector<uint8_t> UsersLoginFailureCountVector;
191  uint64_t usersNextUserId_;
192  enum {
193  USERS_LOGIN_HISTORY_SIZE = 20,
194  USERS_GLOBAL_HISTORY_SIZE = 1000,
195  USERS_MAX_LOGIN_FAILURES = 20,
196  };
197  std::string usersUsernameWithLock_;
198 
199  std::vector<std::string> UsersLoggedOutUsernames_;
200 
201  //"Hashes" database associations ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
202  //Maintain list of acceptable encoded (SHA-512) salt+user+pw's
203  std::vector<std::string> HashesVector;
204  std::vector<time_t> HashesAccessTimeVector;
205 };
206 
207 const std::string WebUsers::REQ_NO_LOGIN_RESPONSE = "NoLogin";
208 const std::string WebUsers::REQ_NO_PERMISSION_RESPONSE = "NoPermission";
209 const std::string WebUsers::REQ_USER_LOCKOUT_RESPONSE = "UserLockout";
210 
211 const std::string WebUsers::SECURITY_TYPE_NONE = "NoSecurity";
212 const std::string WebUsers::SECURITY_TYPE_DIGEST_ACCESS = "DigestAccessAuthentication";
213 const std::string WebUsers::SECURITY_TYPE_KERBEROS = "Kerberos";
214 
215 
216 void WebUsers::deleteUserData ()
217 {
218  //delete Login data
219  std::system(("rm -f " + (std::string)WEB_LOGIN_DB_PATH + HASHES_DB_PATH + "/*").c_str());
220  std::system(("rm -f " + (std::string)WEB_LOGIN_DB_PATH + USERS_DB_PATH + "/*").c_str());
221  std::system(("rm -f " + (std::string)WEB_LOGIN_DB_PATH + USERS_LOGIN_HISTORY_PATH + "/*").c_str());
222  std::system(("rm -f " + (std::string)WEB_LOGIN_DB_PATH + USERS_PREFERENCES_PATH + "/*").c_str());
223  std::system(("rm -rf " + (std::string)WEB_LOGIN_DB_PATH + TOOLTIP_DB_PATH).c_str());
224 
225  std::string serviceDataPath = getenv("SERVICE_DATA_PATH");
226  //delete macro maker folders
227  std::system(("rm -rf " + std::string(serviceDataPath) + "/MacroData/").c_str());
228  std::system(("rm -rf " + std::string(serviceDataPath) + "/MacroHistory/").c_str());
229  std::system(("rm -rf " + std::string(serviceDataPath) + "/MacroExport/").c_str());
230 
231  //delete console folders
232  std::system(("rm -rf " + std::string(serviceDataPath) + "/ConsolePreferences/").c_str());
233 
234  //delete wizard folders
235  std::system(("rm -rf " + std::string(serviceDataPath) + "/OtsWizardData/").c_str());
236 
237  //delete progress bar folders
238  std::system(("rm -rf " + std::string(serviceDataPath) + "/ProgressBarData/").c_str());
239 
240  //delete The Supervisor run folders
241  std::system(("rm -rf " + std::string(serviceDataPath) + "/RunNumber/").c_str());
242  std::system(("rm -rf " + std::string(serviceDataPath) + "/RunControlData/").c_str());
243 
244  //delete Visualizer folders
245  std::system(("rm -rf " + std::string(serviceDataPath) + "/VisualizerData/").c_str());
246 
247  //delete active groups file
248  std::system(("rm -f " + std::string(serviceDataPath) + "/ActiveConfigurationGroups.cfg").c_str());
249 
250  //delete Logbook folders
251  std::system(("rm -rf " + std::string(getenv("LOGBOOK_DATA_PATH")) + "/").c_str());
252 
253  std::cout << __COUT_HDR_FL__ << "$$$$$$$$$$$$$$ Successfully deleted ALL service user data $$$$$$$$$$$$" << std::endl;
254 }
255 }
256 
257 #endif