Przeglądaj źródła

Converted CredentialsCache.Sessions into ConcurrentDictionary

frogsoftware 9 miesięcy temu
rodzic
commit
7a1918bee4
1 zmienionych plików z 124 dodań i 125 usunięć
  1. 124 125
      InABox.Server/CredentialsCache.cs

+ 124 - 125
InABox.Server/CredentialsCache.cs

@@ -1,9 +1,7 @@
 using System.Collections.Concurrent;
 using System.Security.Cryptography;
-using InABox.API;
 using InABox.Core;
 using InABox.Database;
-using Microsoft.Exchange.WebServices.Data;
 
 namespace InABox.API
 {
@@ -11,14 +9,15 @@ namespace InABox.API
     public static class CredentialsCache
     {
 
-        private static ConcurrentBag<User> _cache;
-        private static readonly User BypassedUser = new() { ID = CoreUtils.FullGuid, UserID = "" };
+        private static ConcurrentBag<User>? cache;
+        
+        private static readonly User BYPASSED_USER = new() { ID = CoreUtils.FullGuid, UserID = "" };
 
         private static void EnsureCache(bool force)
         {
-            if (_cache == null || force)
+            if (cache == null || force)
             {
-                var table = DbFactory.NewProvider(Logger.Main).Query(
+                var _table = DbFactory.NewProvider(Logger.Main).Query(
                     null,
                     Columns.None<User>().Add(
                         x => x.ID,
@@ -33,9 +32,9 @@ namespace InABox.API
                         x => x.PasswordExpiration
                     )
                 );
-                _cache = new ConcurrentBag<User>();
-                foreach (var row in table.Rows)
-                    _cache.Add(row.ToObject<User>());
+                cache = new ConcurrentBag<User>();
+                foreach (var _row in _table.Rows)
+                    cache.Add(_row.ToObject<User>());
             }
         }
 
@@ -47,75 +46,75 @@ namespace InABox.API
             if (userid.IsBase64String() && password.IsBase64String())
                 try
                 {
-                    if (Encryption.Decrypt(userid, "wCq9rryEJEuHIifYrxRjxg", out var sUserTicks) &&
-                        Encryption.Decrypt(password, "7mhvLnqMwkCAzN+zNGlyyg", out var sPassTicks))
-                        if (long.TryParse(sUserTicks, out var userticks) && long.TryParse(sPassTicks, out var passticks))
-                            if (userticks == passticks)
+                    if (Encryption.Decrypt(userid, "wCq9rryEJEuHIifYrxRjxg", out var _decryptedUser) &&
+                        Encryption.Decrypt(password, "7mhvLnqMwkCAzN+zNGlyyg", out var _decryptedPass))
+                        if (long.TryParse(_decryptedUser, out var _userticks) && long.TryParse(_decryptedPass, out var _passticks))
+                            if (_userticks == _passticks)
                             {
-                                var remotedate = new DateTime(userticks);
-                                var localdate = DateTime.Now.ToUniversalTime();
-                                if (remotedate >= localdate.AddDays(-1) && remotedate <= localdate.AddDays(1))
+                                var _remotedate = new DateTime(_userticks);
+                                var _localdate = DateTime.Now.ToUniversalTime();
+                                if (_remotedate >= _localdate.AddDays(-1) && _remotedate <= _localdate.AddDays(1))
                                     return true;
                             }
                 }
-                catch (Exception e)
+                catch (Exception _exception)
                 {
-                    Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
+                    Logger.Send(LogType.Error, "", $"*** Unknown Error: {_exception.Message}\n{_exception.StackTrace}");
                 }
 
             return false;
         }
 
-        public static Guid Validate(Guid sessionID, out string? userID)
+        public static Guid Validate(Guid sessionId, out string? userId)
         {
             EnsureCache(false);
-            if(!sessions.TryGetValue(sessionID, out var session) || !session.Valid)
+            if(!sessions.TryGetValue(sessionId, out var _session) || !_session.Valid)
             {
-                userID = null;
+                userId = null;
                 return Guid.Empty;
             }
-            if(session.Expiry < DateTime.Now)
+            if(_session.Expiry < DateTime.Now)
             {
-                sessions.Remove(sessionID);
-                userID = null;
+                sessions.Remove(sessionId, out var _);
+                userId = null;
                 return Guid.Empty;
             }
-            userID = session.UserID;
-            return session.User;
+            userId = _session.UserID;
+            return _session.User;
         }
 
-        public static User? Validate(Guid sessionID)
+        public static User? Validate(Guid sessionId)
         {
             EnsureCache(false);
-            if (!sessions.TryGetValue(sessionID, out var session) || !session.Valid)
+            if (!sessions.TryGetValue(sessionId, out var _session) || !_session.Valid)
             {
                 return null;
             }
-            if (session.Expiry < DateTime.Now)
+            if (_session.Expiry < DateTime.Now)
             {
-                sessions.Remove(sessionID);
+                sessions.Remove(sessionId, out var _);
                 return null;
             }
-            if(session.User == CoreUtils.FullGuid)
+            if(_session.User == CoreUtils.FullGuid)
             {
-                return BypassedUser;
+                return BYPASSED_USER;
             }
-            return _cache.FirstOrDefault(x => x.ID == session.User);
+            return cache?.FirstOrDefault(x => x.ID == _session.User);
         }
 
         /// <summary>
         /// Validate a given session, and refresh the session expiry if valid; use for database queries that need to refresh the user's expiry time.
         /// </summary>
-        /// <param name="sessionID"></param>
+        /// <param name="sessionId"></param>
         /// <returns></returns>
-        public static User? ValidateAndRefresh(Guid sessionID)
+        public static User? ValidateAndRefresh(Guid sessionId)
         {
-            var user = Validate(sessionID);
-            if(user is not null)
+            var _user = Validate(sessionId);
+            if(_user is not null)
             {
-                RefreshSessionExpiry(sessionID);
+                RefreshSessionExpiry(sessionId);
             }
-            return user;
+            return _user;
         }
 
         public static User? ValidateUser(string? pin)
@@ -123,7 +122,7 @@ namespace InABox.API
             if (String.IsNullOrWhiteSpace(pin))
                 return null;
             EnsureCache(false);
-            return _cache.FirstOrDefault(x => string.Equals(x.PIN, pin));
+            return cache?.FirstOrDefault(x => string.Equals(x.PIN, pin));
         }
 
         public static User? ValidateUser(string? userId, string? password)
@@ -132,15 +131,15 @@ namespace InABox.API
                 return null;
 
             if (IsBypassed(userId, password))
-                return BypassedUser;
+                return BYPASSED_USER;
             
             EnsureCache(false);
-            return _cache.FirstOrDefault(x => string.Equals(x.UserID, userId) && string.Equals(x.Password, password));
+            return cache?.FirstOrDefault(x => string.Equals(x.UserID, userId) && string.Equals(x.Password, password));
         }
 
         public static void LogoutUser(Guid userGuid)
         {
-            sessions.Remove(userGuid);
+            sessions.Remove(userGuid, out var _);
         }
 
         public static void Refresh(bool force)
@@ -154,14 +153,14 @@ namespace InABox.API
         {
             public Guid User { get; init; }
 
-            public string UserID { get; init; }
+            public string UserID { get; init; } = "";
 
             public bool Valid { get; set; }
 
             public DateTime Expiry { get; set; }
         }
         // SessionID => Session
-        private static Dictionary<Guid, Session> sessions = new();
+        private static ConcurrentDictionary<Guid, Session> sessions = new();
 
         public static TimeSpan SessionExpiry = TimeSpan.FromHours(8);
 
@@ -174,10 +173,10 @@ namespace InABox.API
 
         private static void CheckSessionExpiries()
         {
-            var now = DateTime.Now;
-            sessions = sessions
-                .Where(x => x.Value.Expiry >= now)
-                .ToDictionary(x => x.Key, x => x.Value);
+            var _expiredkeys = sessions
+                .Where(x => x.Value.Expiry < DateTime.Now);
+            foreach (var _expiredkey in _expiredkeys)
+                sessions.TryRemove(_expiredkey);
         }
 
         public static void SetSessionExpiryTime(TimeSpan expiry)
@@ -187,11 +186,11 @@ namespace InABox.API
 
         public static void RefreshSessionExpiry(Guid sessionID)
         {
-            if (sessions.TryGetValue(sessionID, out var session))
+            if (sessions.TryGetValue(sessionID, out var _session))
             {
-                if (session.Expiry != DateTime.MaxValue)
+                if (_session.Expiry != DateTime.MaxValue)
                 {
-                    session.Expiry = DateTime.Now + SessionExpiry;
+                    _session.Expiry = DateTime.Now + SessionExpiry;
                 }
             }
         }
@@ -203,17 +202,17 @@ namespace InABox.API
             {
                 if (CacheFile != null)
                 {
-                    var json = Serialization.Serialize(sessions.Where(x => x.Value.Expiry != DateTime.MaxValue).ToDictionary(x => x.Key, x => x.Value));
-                    File.WriteAllText(CacheFile, json);
+                    var _json = Serialization.Serialize(sessions.Where(x => x.Value.Expiry != DateTime.MaxValue).ToDictionary(x => x.Key, x => x.Value));
+                    File.WriteAllText(CacheFile, _json);
                 }
                 else
                 {
                     Logger.Send(LogType.Error, "", "Error while saving session cache: No Cache file set!");
                 }
             }
-            catch (Exception e)
+            catch (Exception _exception)
             {
-                Logger.Send(LogType.Error, "", $"Error while saving session cache: {e.Message}");
+                Logger.Send(LogType.Error, "", $"Error while saving session cache: {_exception.Message}");
             }
         }
 
@@ -223,8 +222,10 @@ namespace InABox.API
             {
                 if (CacheFile != null)
                 {
-                    sessions = Serialization.Deserialize<Dictionary<Guid, Session>>(new FileStream(CacheFile, FileMode.Open))
+                    var _cachedData = Serialization.Deserialize<Dictionary<Guid, Session>>(new FileStream(CacheFile, FileMode.Open))?
                         .Where(x => x.Value.Expiry != DateTime.MaxValue).ToDictionary(x => x.Key, x => x.Value);
+                    if (_cachedData != null)
+                        sessions.AddRange(_cachedData);
                     CheckSessionExpiries();
                 }
                 else
@@ -245,11 +246,11 @@ namespace InABox.API
 
         public static Guid NewSession(User user, bool valid = true, DateTime? expiry = null)
         {
-            var session = Guid.NewGuid();
+            var _id = Guid.NewGuid();
 
-            sessions[session] = new() { User = user.ID, Valid = valid, Expiry = expiry ?? (DateTime.Now + SessionExpiry), UserID = user.UserID };
+            sessions[_id] = new() { User = user.ID, Valid = valid, Expiry = expiry ?? (DateTime.Now + SessionExpiry), UserID = user.UserID };
 
-            return session;
+            return _id;
         }
 
         public static bool SessionExists(Guid session)
@@ -273,17 +274,17 @@ namespace InABox.API
             {
                 Code = code;
                 Expiry = expiry;
-                TriesLeft = TwoFATries;
+                TriesLeft = TWO_FA_TRIES;
             }
         }
 
-        private static Dictionary<Guid, AuthenticationCode> authenticationCodes = new();
+        private static readonly ConcurrentDictionary<Guid, AuthenticationCode> authenticationCodes = new();
 
-        private static readonly int TwoFATries = 3;
+        private static readonly int TWO_FA_TRIES = 3;
 
-        public static readonly int CodeLength = 6;
+        public static readonly int CODE_LENGTH = 6;
 
-        private static readonly TimeSpan Expiry2FACodeTime = TimeSpan.FromMinutes(15);
+        private static readonly TimeSpan EXPIRY2_FA_CODE_TIME = TimeSpan.FromMinutes(15);
 
         private static Dictionary<SMSProviderType, ISMSProvider> SMSProviders { get; set; } = new();
 
@@ -294,56 +295,54 @@ namespace InABox.API
 
         private static string GenerateCode()
         {
-            var random = new Random(DateTime.Now.Millisecond);
-            var code = "";
-            for (int i = 0; i < CodeLength; i++)
-            {
-                code += random.Next(10).ToString();
-            }
-            return code;
+            var _random = new Random(DateTime.Now.Millisecond);
+            var _code = "";
+            for (int _char = 0; _char < CODE_LENGTH; _char++)
+                _code += _random.Next(10).ToString();
+            return _code;
         }
 
         public static Guid? SendCode(Guid userGuid, out string? recipient)
         {
             EnsureCache(false);
-            var user = _cache.FirstOrDefault(x => x.ID == userGuid);
-            if(user == null)
+            var _user = cache?.FirstOrDefault(x => x.ID == userGuid);
+            if(_user == null)
             {
                 Logger.Send(LogType.Error, "", "Cannot send code; user does not exist!");
                 recipient = null;
                 return null;
             }
 
-            var session = NewSession(user, false);
-            Logger.Send(LogType.Information, "", $"New login session {session} for {user.UserID}");
+            var _newSession = NewSession(_user, false);
+            Logger.Send(LogType.Information, "", $"New login session {_newSession} for {_user.UserID}");
 
-            if (user.TwoFactorAuthenticationType != TwoFactorAuthenticationType.GoogleAuthenticator)
+            if (_user.TwoFactorAuthenticationType != TwoFactorAuthenticationType.GoogleAuthenticator)
             {
-                var smsProvider = SMSProviders
-                    .Where(x => x.Value.TwoFactorAuthenticationType == user.TwoFactorAuthenticationType)
+                var _smsProvider = SMSProviders
+                    .Where(x => x.Value.TwoFactorAuthenticationType == _user.TwoFactorAuthenticationType)
                     .Select(x => x.Value).FirstOrDefault();
-                if (smsProvider == null)
+                if (_smsProvider == null)
                 {
                     Logger.Send(LogType.Error, "", "Cannot send code; user requests a 2FA method which is not supported!");
                     recipient = null;
                     return null;
                 }
 
-                var code = GenerateCode();
+                var _code = GenerateCode();
 
-                Logger.Send(LogType.Information, "", $"Code for session {userGuid} is {code}");
-                authenticationCodes.Add(session, new AuthenticationCode(code, DateTime.Now + Expiry2FACodeTime));
+                Logger.Send(LogType.Information, "", $"Code for session {userGuid} is {_code}");
+                authenticationCodes[_newSession] = new AuthenticationCode(_code, DateTime.Now + EXPIRY2_FA_CODE_TIME);
 
-                var recAddr = user.Recipient2FA;
-                if (smsProvider.SendMessage(recAddr, $"Your authentication code is {code}. This code will expire in {Expiry2FACodeTime.Minutes} minutes."))
+                var _recipientAddress = _user.Recipient2FA;
+                if (_smsProvider.SendMessage(_recipientAddress, $"Your authentication code is {_code}. This code will expire in {EXPIRY2_FA_CODE_TIME.Minutes} minutes."))
                 {
                     Logger.Send(LogType.Information, "", "Code sent!");
 
-                    var first = recAddr[..3];
-                    var last = recAddr[^3..];
+                    var _first = _recipientAddress[..3];
+                    var _last = _recipientAddress[^3..];
 
-                    recipient = first + new string('*', recAddr.Length - 6) + last;
-                    return session;
+                    recipient = _first + new string('*', _recipientAddress.Length - 6) + _last;
+                    return _newSession;
                 }
                 else
                 {
@@ -356,43 +355,43 @@ namespace InABox.API
             {
                 Logger.Send(LogType.Information, "", $"Google authenticator is being used");
                 recipient = "Google Authenticator";
-                return session;
+                return _newSession;
             }
         }
 
-        private static readonly int CodeModulo = (int)Math.Pow(10, CodeLength);
+        private static readonly int CODE_MODULO = (int)Math.Pow(10, CODE_LENGTH);
 
         private static string GenerateGoogleAuthenticatorCode(long time, byte[] key)
         {
-            var window = time / 30;
-            var hex = window.ToString("x");
-            if (hex.Length < 16)
+            var _window = time / 30;
+            var _hex = _window.ToString("x");
+            if (_hex.Length < 16)
             {
-                hex = hex.PadLeft(16, '0');
+                _hex = _hex.PadLeft(16, '0');
             }
-            var bytes = Convert.FromHexString(hex);
-            var hash = new HMACSHA1(key).ComputeHash(bytes);
+            var _bytes = Convert.FromHexString(_hex);
+            var _hash = new HMACSHA1(key).ComputeHash(_bytes);
 
-            var offset = hash[hash.Length - 1] & 0xf;
-            var selected = new byte[4];
-            Buffer.BlockCopy(hash, offset, selected, 0, 4);
+            var _offset = _hash.Last() & 0xf;
+            var _selected = new byte[4];
+            Buffer.BlockCopy(_hash, _offset, _selected, 0, 4);
             if (BitConverter.IsLittleEndian)
             {
-                Array.Reverse(selected);
+                Array.Reverse(_selected);
             }
 
-            var integer = BitConverter.ToInt32(selected, 0);
-            var truncated = integer & 0x7fffffff;
+            var _integer = BitConverter.ToInt32(_selected, 0);
+            var _truncated = _integer & 0x7fffffff;
 
-            return (truncated % CodeModulo).ToString().PadLeft(CodeLength, '0');
+            return (_truncated % CODE_MODULO).ToString().PadLeft(CODE_LENGTH, '0');
         }
 
         private static bool CheckAuthenticationCode(byte[] token, string code)
         {
-            var time = DateTimeOffset.Now.ToUnixTimeSeconds();
-            for (long i = time - 30; i <= time; i += 30)
+            var _time = DateTimeOffset.Now.ToUnixTimeSeconds();
+            for (long _l = _time - 30; _l <= _time; _l += 30)
             {
-                if(GenerateGoogleAuthenticatorCode(i, token) == code)
+                if(GenerateGoogleAuthenticatorCode(_l, token) == code)
                 {
                     return true;
                 }
@@ -402,49 +401,49 @@ namespace InABox.API
 
         public static bool ValidateCode(Guid sessionID, string code)
         {
-            if (!sessions.TryGetValue(sessionID, out var session))
+            if (!sessions.TryGetValue(sessionID, out var _session))
             {
                 return false;
             }
 
-            bool valid;
-            if(authenticationCodes.TryGetValue(sessionID, out var result))
+            bool _valid;
+            if(authenticationCodes.TryGetValue(sessionID, out var _result))
             {
-                if (result.Code != code)
+                if (_result.Code != code)
                 {
-                    result.TriesLeft--;
-                    if (result.TriesLeft == 0)
+                    _result.TriesLeft--;
+                    if (_result.TriesLeft == 0)
                     {
-                        authenticationCodes.Remove(sessionID);
+                        authenticationCodes.Remove(sessionID, out _);
                     }
-                    valid = false;
+                    _valid = false;
                 }
-                else if (result.Expiry < DateTime.Now)
+                else if (_result.Expiry < DateTime.Now)
                 {
-                    authenticationCodes.Remove(sessionID);
-                    valid = false;
+                    authenticationCodes.Remove(sessionID, out _);
+                    _valid = false;
                 }
                 else
                 {
-                    valid = true;
+                    _valid = true;
                 }
             }
             else
             {
-                var user = _cache.FirstOrDefault(x => x.ID == session.User);
-                if(user?.TwoFactorAuthenticationType == TwoFactorAuthenticationType.GoogleAuthenticator)
+                var _user = cache?.FirstOrDefault(x => x.ID == _session.User);
+                if (_user?.TwoFactorAuthenticationType == TwoFactorAuthenticationType.GoogleAuthenticator)
                 {
-                    valid = CheckAuthenticationCode(user.AuthenticatorToken, code);
+                    _valid = CheckAuthenticationCode(_user.AuthenticatorToken, code);
                 }
                 else
                 {
-                    valid = false;
+                    _valid = false;
                 }
             }
 
-            if (valid)
+            if (_valid)
             {
-                session.Valid = true;
+                _session.Valid = true;
 
                 return true;
             }