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