public async Task <Result <bool> > DeleteUploadAsync(string username, int id, string ipAddress, int failureCount) { var result = false; // Escape condition for recursive call if exception is thrown. if (failureCount >= Constants.OperationRetry) { return(SystemUtilityService.CreateResult(Constants.UploadDeletionFailedMessage, result, true)); } try { result = await _uploadService.DeleteUploadsAsync(new List <int>() { id }).ConfigureAwait(false); } catch (Exception ex) { // Log exception. await _loggingManager.LogAsync(DateTime.UtcNow.ToString(Constants.LoggingFormatString), Constants.DeleteUploadOperation, username, ipAddress, ex.ToString()).ConfigureAwait(false); // Recursively retry the operation until the maximum amount of retries is reached. await ContinueUploadProgressAsync(username, id, ipAddress, ++failureCount).ConfigureAwait(false); } // Log the fact that the operation was successful. await _loggingManager.LogAsync(DateTime.UtcNow.ToString(Constants.LoggingFormatString), Constants.DeleteUploadOperation, username, ipAddress).ConfigureAwait(false); return(SystemUtilityService.CreateResult(Constants.UploadDeletionSuccessMessage, result, false)); }
public Result <bool> ValidateToken(string token, string username) { try { if (_sessionService.TokenIsExpired(token)) { return(SystemUtilityService.CreateResult(Constants.ResetLinkExpired, false, false)); } var tokenUsername = _authorizationService.DecryptJWT(token)[Constants.IdKey]; if (username != tokenUsername) { return(SystemUtilityService.CreateResult(Constants.UsernameNotMatchResetLink, false, false)); } return(SystemUtilityService.CreateResult(null, true, false)); } catch (Exception e) { Console.WriteLine("ValidateToken:" + e.Message); Console.WriteLine("ValidateToken:" + e.StackTrace); return(SystemUtilityService.CreateResult(Constants.SystemErrorUserMessage, false, true)); } }
public async Task <Result <UploadObject> > ContinueUploadProgressAsync(string username, int id, string ipAddress, int failureCount) { var result = new UploadObject(Constants.NoValueDatetime, Constants.NoValueString, Constants.NoValueInt, Constants.NoValueString, Constants.NoValueInt, Constants.NoValueString, Constants.NoValueDouble, Constants.NoValueString, Constants.NoValueString, Constants.NoValueInt, Constants.NoValueInt, Constants.NoValueBool, Constants.NoValueString); // Escape condition for recursive call if exception is thrown. if (failureCount >= Constants.OperationRetry) { return(SystemUtilityService.CreateResult(Constants.UploadRetrievalFailedMessage, result, true)); } try { result = await _uploadService.ContinueUploadProgressAsync(id).ConfigureAwait(false); } catch (Exception ex) { // Log exception. await _loggingManager.LogAsync(DateTime.UtcNow.ToString(Constants.LoggingFormatString), Constants.ContinueDraftOperation, username, ipAddress, ex.ToString()).ConfigureAwait(false); // Recursively retry the operation until the maximum amount of retries is reached. await ContinueUploadProgressAsync(username, id, ipAddress, ++failureCount).ConfigureAwait(false); } // Log the fact that the operation was successful. await _loggingManager.LogAsync(DateTime.UtcNow.ToString(Constants.LoggingFormatString), Constants.ContinueDraftOperation, username, ipAddress).ConfigureAwait(false); return(SystemUtilityService.CreateResult(Constants.UploadRetrievalSuccessMessage, result, false)); }
public async Task <Result <AnalysisResult> > AnalyzeImageAsync(Image image, string username, string ipAddress, int failureCount) { var result = new AnalysisResult(new List <string>(), Constants.NoValueString, Constants.NoValueString); // Escape condition for recursive call if exception is thrown. if (failureCount >= Constants.OperationRetry) { return(SystemUtilityService.CreateResult(Constants.AnalyzationFailedMessage, result, true)); } try { result = await _googleImageAnalysisService.AnalyzeAsync(image, Constants.ExogredientCategories).ConfigureAwait(false); } catch (Exception ex) { // Log exception. await _loggingManager.LogAsync(DateTime.UtcNow.ToString(Constants.LoggingFormatString), Constants.AnalyzeImageOperation, username, ipAddress, ex.ToString()).ConfigureAwait(false); // Recursively retry the operation until the maximum amount of retries is reached. await AnalyzeImageAsync(image, username, ipAddress, ++failureCount).ConfigureAwait(false); } // Log the fact that the operation was successful. await _loggingManager.LogAsync(DateTime.UtcNow.ToString(Constants.LoggingFormatString), Constants.AnalyzeImageOperation, username, ipAddress).ConfigureAwait(false); return(SystemUtilityService.CreateResult(Constants.AnalyzationSuccessMessage, result, false)); }
public async Task SystemUtilityService_NotifySystemAdminAsync_SendEmailToSystemAdminSuccess(string body) { // Act: Check that a successfull message to system admin returns true. bool notifyResult = await SystemUtilityService.NotifySystemAdminAsync(body, Constants.SystemAdminEmailAddress).ConfigureAwait(false); Assert.IsTrue(notifyResult); }
public async Task <Result <bool> > SendPhoneCodeAsync(string username, string phoneNumber, string ipAddress, int currentNumExceptions) { try { await _verificationService.SendCallVerificationAsync(username, phoneNumber).ConfigureAwait(false); _ = _loggingManager.LogAsync(DateTime.UtcNow.ToString(Constants.LoggingFormatString), Constants.SendPhoneCodeOperation, username, ipAddress).ConfigureAwait(false); return(SystemUtilityService.CreateResult(Constants.SendPhoneCodeSuccessUserMessage, true, false)); } catch (Exception e) { Console.WriteLine(e.Message); Console.WriteLine(e.StackTrace); _ = _loggingManager.LogAsync(DateTime.UtcNow.ToString(Constants.LoggingFormatString), Constants.SendPhoneCodeOperation, username, ipAddress, e.Message).ConfigureAwait(false); if (currentNumExceptions + 1 >= Constants.MaximumOperationRetries) { await SystemUtilityService.NotifySystemAdminAsync($"{Constants.SendPhoneCodeOperation} failed a maximum number of times for {username}.", Constants.SystemAdminEmailAddress).ConfigureAwait(false); } return(SystemUtilityService.CreateResult(Constants.SystemErrorUserMessage, false, true)); } }
/// <summary> /// Method to get all the years and months pertaining to that year that has snapshots. /// If it fails, there are 3 retries before admin is notified of error. /// </summary> /// <returns>A json formatted string with the data.</returns> public async Task <string> GetYearMonthAsync() { int currentNumExceptions = 0; var snapshotYearMonth = ""; while (currentNumExceptions < 4) { currentNumExceptions++; try { snapshotYearMonth = await _snapshotService.GetYearAndMonthAsync().ConfigureAwait(false); } catch (Exception e) { await _loggingManager.LogAsync(DateTime.UtcNow.ToString(Constants.LoggingFormatString), Constants.ReadMultiSnapshotOperation, Constants.SystemIdentifier, Constants.LocalHost, e.Message).ConfigureAwait(false); // Increment the amount of tries and then check if the 3 retries are up. // If it is, notify system admin. currentNumExceptions++; if (currentNumExceptions >= Constants.MaximumOperationRetries) { await SystemUtilityService.NotifySystemAdminAsync($"{Constants.ReadMultiSnapshotOperation} failed a maximum number of times for {Constants.LocalHost}.", Constants.SystemAdminEmailAddress).ConfigureAwait(false); } } } return(snapshotYearMonth); }
public async Task SystemUtilityService_IsCorruptedPassword_IsCorruptedAsyncSuccess(string plaintextPassword) { // Act bool result = await SystemUtilityService.IsCorruptedPasswordAsync(plaintextPassword).ConfigureAwait(false); // Assert Assert.IsTrue(result); }
/// <summary> /// Asynchronously logs to the data store and flat file. /// </summary> /// <param name="timestamp">The timestamp of the operation.</param> /// <param name="operation">The type of the operation.</param> /// <param name="identifier">The identifier of the operation's performer.</param> /// <param name="ipAddress">The ip address of the operation's performer.</param> /// <param name="errorType">The type of error that occurred during the operation (default = no error)</param> /// <returns>Task (bool) whether the logging operation was successful.</returns> public async Task <bool> LogAsync(string timestamp, string operation, string identifier, string ipAddress, string errorType = Constants.NoError) { // Attempt logging to both the data store and the flat file and track the results. bool ffLoggingResult = await _ffLoggingService.LogToFlatFileAsync(timestamp, operation, identifier, ipAddress, errorType, Constants.LogFolder, Constants.LogFileType).ConfigureAwait(false); bool dsLoggingResult = await _dsLoggingService.LogToDataStoreAsync(timestamp, operation, identifier, ipAddress, errorType).ConfigureAwait(false); int count = 0; // Retry whichever one failed, a maximum number of times. while (!(ffLoggingResult && dsLoggingResult) && count < Constants.LoggingRetriesAmount) { if (!ffLoggingResult) { ffLoggingResult = await _ffLoggingService.LogToFlatFileAsync(timestamp, operation, identifier, ipAddress, errorType, Constants.LogFolder, Constants.LogFileType).ConfigureAwait(false); } if (!dsLoggingResult) { dsLoggingResult = await _dsLoggingService.LogToDataStoreAsync(timestamp, operation, identifier, ipAddress, errorType).ConfigureAwait(false); } count++; } // If both succeeded we are finished. if (ffLoggingResult && dsLoggingResult) { return(true); } else { // Otherwise, if both failed notify the system admin. if (!ffLoggingResult && !dsLoggingResult) { await SystemUtilityService.NotifySystemAdminAsync($"Data Store and Flat File Logging failure for the following information:\n\n\t{timestamp}, {operation}, {identifier}, {ipAddress}, {errorType}", Constants.SystemAdminEmailAddress).ConfigureAwait(false); } else { // Otherwise rollback whichever one succeeded and notify the system admin. bool rollbackSuccess = false; if (ffLoggingResult) { rollbackSuccess = await _ffLoggingService.DeleteFromFlatFileAsync(timestamp, operation, identifier, ipAddress, errorType, Constants.LogFolder, Constants.LogFileType).ConfigureAwait(false); } if (dsLoggingResult) { rollbackSuccess = await _dsLoggingService.DeleteLogFromDataStoreAsync(timestamp, operation, identifier, ipAddress, errorType).ConfigureAwait(false); } await SystemUtilityService.NotifySystemAdminAsync($"{(ffLoggingResult ? "Flat File" : "Data Store")} Logging failure for the following information:\n\n\t{timestamp}, {operation}, {identifier}, {ipAddress}, {errorType}\n\nRollback status: {(rollbackSuccess ? "successful" : "failed")}", Constants.SystemAdminEmailAddress).ConfigureAwait(false); } return(false); } }
public async Task <Result <bool> > UpdatePasswordAsync(string username, string ipAddress, string hashedPassword, string proxyPassword, string salt, int currentNumExceptions) { try { bool updateSuccess = false; // Check the length of their password. if (!StringUtilityService.CheckLength(proxyPassword, Constants.MaximumPasswordCharacters, Constants.MinimumPasswordCharacters)) { _ = _loggingManager.LogAsync(DateTime.UtcNow.ToString(Constants.LoggingFormatString), Constants.UpdatePasswordOperation, username, ipAddress, Constants.InvalidPasswordLengthLogMessage).ConfigureAwait(false); return(SystemUtilityService.CreateResult(Constants.InvalidPasswordLengthUserMessage, updateSuccess, false)); } updateSuccess = true; await _userManagementService.ChangePasswordAsync(username, hashedPassword, salt).ConfigureAwait(false); _ = _loggingManager.LogAsync(DateTime.UtcNow.ToString(Constants.LoggingFormatString), Constants.UpdatePasswordOperation, username, ipAddress).ConfigureAwait(false); return(SystemUtilityService.CreateResult(Constants.UpdatePasswordSuccessUserMessage, updateSuccess, false)); } catch (Exception e) { Console.WriteLine("UpdatePassword:"******"UpdatePassword:"******"{Constants.UpdatePasswordOperation} failed a maximum number of times for {username}.", Constants.SystemAdminEmailAddress).ConfigureAwait(false); } return(SystemUtilityService.CreateResult(Constants.SystemErrorUserMessage, false, true)); } }
public void SystemUtilityService_CreateResult_CreateAccurateResult(string message, string data, bool exceptionOccured) { // Act Result <string> resultObject = SystemUtilityService.CreateResult <string>(message, data, exceptionOccured); // Assert: Check that the result we created matches the inputs. bool result; if (resultObject.Message == message && resultObject.Data == data && resultObject.ExceptionOccurred == exceptionOccured) { result = true; } else { result = false; } Assert.IsTrue(result); }
public async Task <Result <bool> > CreateUploadAsync(UploadPost post, int failureCount) { var result = false; // Escape condition for recursive call if exception is thrown. if (failureCount >= Constants.OperationRetry) { return(SystemUtilityService.CreateResult(Constants.UploadCreationErrorMessage, result, true)); } try { if (!await _userManagementService.CheckUserExistenceAsync(post.Username).ConfigureAwait(false)) { // Log the fact user was invalid. await _loggingManager.LogAsync(DateTime.UtcNow.ToString(Constants.LoggingFormatString), Constants.CreateUploadOperation, post.Username, post.IPAddress, Constants.UploadUserDNESystemMessage).ConfigureAwait(false); return(SystemUtilityService.CreateResult(Constants.UploadUserDNEUserMessage, result, false)); } var latLong = LocationUtilityService.GetImageLatitudeAndLongitude(post.Image); var latitude = latLong.Item1; var longitude = latLong.Item2; var withinScope = LocationUtilityService.CheckLocationWithinPolygon(latitude, longitude, Constants.CurrentScopePolygon); if (!withinScope) { // Log the fact that scope was violated. await _loggingManager.LogAsync(DateTime.UtcNow.ToString(Constants.LoggingFormatString), Constants.CreateUploadOperation, post.Username, post.IPAddress, Constants.ImageNotWithinScopeSystemMessage).ConfigureAwait(false); return(SystemUtilityService.CreateResult(Constants.ImageNotWithinScopeUserMessage, result, false)); } var storeID = await _storeService.FindStoreAsync(latitude, longitude).ConfigureAwait(false); if (storeID == Constants.NoStoreFoundCode) { // Log the fact that scope was violated. await _loggingManager.LogAsync(DateTime.UtcNow.ToString(Constants.LoggingFormatString), Constants.CreateUploadOperation, post.Username, post.IPAddress, Constants.NoStoreFoundSystemMessage).ConfigureAwait(false); return(SystemUtilityService.CreateResult(Constants.NoStoreFoundUserMessage, result, false)); } var imagePath = Constants.PhotoFolder + "\\" + post.Username + "_" + TimeUtilityService.CurrentUnixTime() + post.FileExtension; var uploadDTO = new UploadDTO(imagePath, post.Image, post.Category, post.Name, (DateTime)post.PostTime, post.Username, post.Description, post.Rating, post.Price, post.PriceUnit, post.ImageSize); var verification = _uploadService.VerifyUpload(uploadDTO, Constants.MaximumPhotoCharacters, Constants.MinimumPhotoCharacters, Constants.MinimumImageSizeMB, Constants.MaximumImageSizeMB, Constants.ValidImageExtensions, Constants.IngredientNameMaximumCharacters, Constants.IngredientNameMinimumCharacters, Constants.MaximumIngredientPrice, Constants.DescriptionMaximumCharacters, Constants.DescriptionMinimumCharacters, Constants.ExogredientCategories, Constants.ExogredientPriceUnits, Constants.ValidTimeBufferMinutes, Constants.MaximumRating, Constants.MinimumRating); if (!verification.VerificationStatus) { // Log the fact that scope was violated. await _loggingManager.LogAsync(DateTime.UtcNow.ToString(Constants.LoggingFormatString), Constants.CreateUploadOperation, post.Username, post.IPAddress, Constants.UploadNotValidSystemMessage).ConfigureAwait(false); return(SystemUtilityService.CreateResult(verification.Message, result, false)); } Directory.CreateDirectory(Constants.PhotoFolder); post.Image.Save(imagePath); var uploadRecord = new UploadRecord(post.PostTime, post.Username, storeID, post.Description, post.Rating.ToString(), imagePath, post.Price, post.PriceUnit, post.Name, Constants.NoValueInt, Constants.NoValueInt, Constants.NotInProgressStatus, post.Category); await _uploadService.CreateUploadAsync(uploadRecord).ConfigureAwait(false); result = true; } catch (Exception ex) { // Log exception. await _loggingManager.LogAsync(DateTime.UtcNow.ToString(Constants.LoggingFormatString), Constants.CreateUploadOperation, post.Username, post.IPAddress, ex.ToString()).ConfigureAwait(false); // Recursively retry the operation until the maximum amount of retries is reached. await CreateUploadAsync(post, ++failureCount).ConfigureAwait(false); } // Log the fact that the operation was successful. await _loggingManager.LogAsync(DateTime.UtcNow.ToString(Constants.LoggingFormatString), Constants.CreateUploadOperation, post.Username, post.IPAddress).ConfigureAwait(false); return(SystemUtilityService.CreateResult(Constants.UploadCreationSuccessMessage, result, false)); }
public async Task <Result <bool> > VerifyEmailCodeAsync(string username, string inputCode, string ipAddress, int currentNumExceptions) { try { bool emailVerificationSuccess = false; UserObject user = await _userManagementService.GetUserInfoAsync(username).ConfigureAwait(false); if (user.EmailCodeFailures >= Constants.MaxEmailCodeAttempts) { _ = _loggingManager.LogAsync(DateTime.UtcNow.ToString(Constants.LoggingFormatString), Constants.VerifyEmailOperation, username, ipAddress, Constants.MaxEmailTriesReachedLogMessage).ConfigureAwait(false); return(SystemUtilityService.CreateResult(Constants.MaxEmailTriesReachedUserMessage, emailVerificationSuccess, false)); } long maxValidTimeSeconds = TimeUtilityService.TimespanToSeconds(Constants.EmailCodeMaxValidTime); long currentUnix = TimeUtilityService.CurrentUnixTime(); if (user.EmailCodeTimestamp + maxValidTimeSeconds < currentUnix) { _ = _loggingManager.LogAsync(DateTime.UtcNow.ToString(Constants.LoggingFormatString), Constants.VerifyEmailOperation, username, ipAddress, Constants.EmailCodeExpiredLogMessage).ConfigureAwait(false); return(SystemUtilityService.CreateResult(Constants.EmailCodeExpiredUserMessage, emailVerificationSuccess, false)); } if (user.EmailCode.Equals(inputCode)) { emailVerificationSuccess = true; await _loggingManager.LogAsync(DateTime.UtcNow.ToString(Constants.LoggingFormatString), Constants.VerifyEmailOperation, username, ipAddress).ConfigureAwait(false); return(SystemUtilityService.CreateResult(Constants.VerifyEmailSuccessUserMessage, emailVerificationSuccess, false)); } else { _ = _loggingManager.LogAsync(DateTime.UtcNow.ToString(Constants.LoggingFormatString), Constants.VerifyEmailOperation, username, ipAddress, Constants.WrongEmailCodeMessage).ConfigureAwait(false); await _userManagementService.IncrementEmailCodeFailuresAsync(username).ConfigureAwait(false); return(SystemUtilityService.CreateResult(Constants.WrongEmailCodeMessage, emailVerificationSuccess, false)); } } catch (Exception e) { _ = _loggingManager.LogAsync(DateTime.UtcNow.ToString(Constants.LoggingFormatString), Constants.VerifyEmailOperation, username, ipAddress, e.Message).ConfigureAwait(false); if (currentNumExceptions + 1 >= Constants.MaximumOperationRetries) { await SystemUtilityService.NotifySystemAdminAsync($"{Constants.VerifyEmailOperation} failed a maximum number of times for {username}.", Constants.SystemAdminEmailAddress).ConfigureAwait(false); } return(SystemUtilityService.CreateResult(Constants.SystemErrorUserMessage, false, true)); } }
public static async Task Main(string[] args) { // Make sure only days, source Directory, and targetDirectory are entered into program if (args.Length != 4) { await SystemUtilityService.NotifySystemAdminAsync(Constants.InvalidArgs, Constants.SystemAdminEmailAddress).ConfigureAwait(false); return; } DateTime currentTime = DateTime.Now; int days; string targetDirectory = ""; try { days = Convert.ToInt32(args[1]); } catch { await SystemUtilityService.NotifySystemAdminAsync(Constants.FirstArgumentNotInt, Constants.SystemAdminEmailAddress).ConfigureAwait(false); return; } string sourceDir; if (Directory.Exists(args[2])) { sourceDir = args[2]; } else { await SystemUtilityService.NotifySystemAdminAsync(Constants.SourceDirectoryDNE, Constants.SystemAdminEmailAddress).ConfigureAwait(false); return; } if (Directory.Exists(args[3])) { targetDirectory = args[3]; } targetDirectory += currentTime.ToString(Constants.NamingFormatString); bool result = false; // FetchLogs will return true if files of the proper age are found in the source directory. if (FileFetchingService.FetchLogs(sourceDir, targetDirectory, days)) { if (CompressionService.Compress(Constants.SevenZipPath, sourceDir, targetDirectory)) { result = await FTPService.SendAsync(Constants.FTPUrl, "", targetDirectory, Constants.FTPUsername, Constants.FTPpassword).ConfigureAwait(false); } } // Notify system admin if Archiving fails to run successfully. if (result == false) { await SystemUtilityService.NotifySystemAdminAsync("Archiving failed on" + currentTime, Constants.SystemAdminEmailAddress).ConfigureAwait(false); } }
public async Task <Result <bool> > VerifyPhoneCodeAsync(string username, string inputCode, string ipAddress, string phoneNumber, bool duringRegistration, int currentNumExceptions) { try { bool phoneVerificationSuccess = false; UserObject user = await _userManagementService.GetUserInfoAsync(username).ConfigureAwait(false); if (user.PhoneCodeFailures >= Constants.MaxPhoneCodeAttempts) { _ = _loggingManager.LogAsync(DateTime.UtcNow.ToString(Constants.LoggingFormatString), Constants.VerifyPhoneOperation, username, ipAddress, Constants.MaxPhoneTriesReachedLogMessage).ConfigureAwait(false); return(SystemUtilityService.CreateResult(Constants.MaxPhoneTriesReachedUserMessage, phoneVerificationSuccess, false)); } string verificationStatus = await _verificationService.VerifyPhoneCodeAsync(phoneNumber, inputCode).ConfigureAwait(false); if (verificationStatus.Equals(Constants.TwilioAuthenticationApprovedString)) { phoneVerificationSuccess = true; _ = _loggingManager.LogAsync(DateTime.UtcNow.ToString(Constants.LoggingFormatString), Constants.VerifyPhoneOperation, username, ipAddress).ConfigureAwait(false); if (duringRegistration) { await _userManagementService.MakeTempPermAsync(username).ConfigureAwait(false); } return(SystemUtilityService.CreateResult(Constants.VerifyPhoneSuccessUserMessage, phoneVerificationSuccess, false)); } else if (verificationStatus.Equals(Constants.TwilioAuthenticationPendingString)) { await _userManagementService.IncrementPhoneCodeFailuresAsync(username).ConfigureAwait(false); _ = _loggingManager.LogAsync(DateTime.UtcNow.ToString(Constants.LoggingFormatString), Constants.VerifyPhoneOperation, username, ipAddress, Constants.WrongPhoneCodeMessage).ConfigureAwait(false); return(SystemUtilityService.CreateResult(Constants.WrongPhoneCodeMessage, phoneVerificationSuccess, false)); } else { // Failed await _userManagementService.IncrementPhoneCodeFailuresAsync(username).ConfigureAwait(false); _ = _loggingManager.LogAsync(DateTime.UtcNow.ToString(Constants.LoggingFormatString), Constants.VerifyPhoneOperation, username, ipAddress, Constants.PhoneCodeExpiredLogMessage).ConfigureAwait(false); return(SystemUtilityService.CreateResult(Constants.PhoneCodeExpiredUserMessage, phoneVerificationSuccess, false)); } } catch (Exception e) { _ = _loggingManager.LogAsync(DateTime.UtcNow.ToString(Constants.LoggingFormatString), Constants.VerifyPhoneOperation, username, ipAddress, e.Message).ConfigureAwait(false); if (currentNumExceptions + 1 >= Constants.MaximumOperationRetries) { await SystemUtilityService.NotifySystemAdminAsync($"{Constants.VerifyPhoneOperation} failed a maximum number of times for {username}.", Constants.SystemAdminEmailAddress).ConfigureAwait(false); } return(SystemUtilityService.CreateResult(Constants.SystemErrorUserMessage, false, true)); } }
/// <summary> /// Method to create a snapshot with given year and month. /// </summary> /// <param name="currentNumExceptions"></param> /// <param name="year"></param> /// <param name="month"></param> /// <returns></returns> public async Task <bool> CreateSnapshotAsync(int currentNumExceptions, int year, int month) { bool createSnapshotSuccess = false; try { // Get the amount of days in the specific month. var amountOfDays = _snapshotService.GetDaysInMonth(year, month); // Get all the logs pertaining to the specific month. var logResults = await _snapshotService.GetLogsInMonthAsync(year, month, amountOfDays).ConfigureAwait(false); var snapshot = new List <string>(); // Calling the snapshot service methods to format the data in logresults to dictionaries. var operationsDict = _snapshotService.GetOperationDict(logResults, amountOfDays); var usersDict = await _snapshotService.GetUsersDictAsync().ConfigureAwait(false); var cityDict = await _snapshotService.GetCityDictAsync(logResults).ConfigureAwait(false); var userUploadedDict = _snapshotService.GetUserUploadedDict(logResults); var uploadedIngredientDict = _snapshotService.GetUploadedIngredientDict(logResults); var uploadedStoreDict = _snapshotService.GetUploadedStoreDict(logResults); var searchedIngredientDict = _snapshotService.GetSearchedIngredientDict(logResults); var searchedStoreDict = _snapshotService.GetSearchedStoreDict(logResults); var upvotedUserDict = await _snapshotService.GetUpvotedUserDictAsync(logResults).ConfigureAwait(false); var downvotedUserDict = await _snapshotService.GetDownvotedUserDictAsync(logResults).ConfigureAwait(false); // Finalizing the data and then adding it to the snapshot List. snapshot.Add(_snapshotService.FormatOperationsDict(operationsDict)); snapshot.Add(_snapshotService.FormatStringIntDict(usersDict)); snapshot.Add(_snapshotService.FinalizeStringIntDictForSnap(cityDict)); snapshot.Add(_snapshotService.FinalizeStringIntDictForSnap(userUploadedDict)); snapshot.Add(_snapshotService.FinalizeStringIntDictForSnap(uploadedIngredientDict)); snapshot.Add(_snapshotService.FinalizeStringIntDictForSnap(uploadedStoreDict)); snapshot.Add(_snapshotService.FinalizeStringIntDictForSnap(searchedIngredientDict)); snapshot.Add(_snapshotService.FinalizeStringIntDictForSnap(searchedStoreDict)); snapshot.Add(_snapshotService.FinalizeStringIntDictForSnap(upvotedUserDict)); snapshot.Add(_snapshotService.FinalizeStringIntDictForSnap(downvotedUserDict)); // Call the method to create the snapshot in the snapshot service. createSnapshotSuccess = await _snapshotService.CreateSnapShotAsync(year, month, snapshot).ConfigureAwait(false); await _loggingManager.LogAsync(DateTime.UtcNow.ToString(Constants.LoggingFormatString), Constants.CreateSnapshotOperation, Constants.SystemIdentifier, Constants.LocalHost).ConfigureAwait(false); } catch (Exception e) { await _loggingManager.LogAsync(DateTime.UtcNow.ToString(Constants.LoggingFormatString), Constants.CreateSnapshotOperation, Constants.SystemIdentifier, Constants.LocalHost, e.Message).ConfigureAwait(false); if (currentNumExceptions >= Constants.MaximumOperationRetries) { await SystemUtilityService.NotifySystemAdminAsync($"{Constants.CreateSnapshotOperation} failed a maximum number of times for {Constants.LocalHost}.", Constants.SystemAdminEmailAddress).ConfigureAwait(false); } } return(createSnapshotSuccess); }
// Time out after X seconds will be conducted in Controllers with Task.Wait // Re-trying after exceptions occur will be conducted in Controllers, who will check if an exception occurred and how // many exceptions have currently occured after a manager has returned. // Encrypted password, encrypted AES key, and AES IV are all in hex string format. public async Task <Result <bool> > RegisterAsync(string firstName, string lastName, string email, string username, string phoneNumber, string ipAddress, string hashedPassword, string salt, string proxyPassword, int currentNumExceptions) { try { bool registrationSuccess = false; // If the ip address is not in our system. Insert into datastore if (!await _userManagementService.CheckIPExistenceAsync(ipAddress).ConfigureAwait(false)) { await _userManagementService.CreateIPAsync(ipAddress).ConfigureAwait(false); } // Grab the user ip object. IPAddressObject ip = await _userManagementService.GetIPAddressInfoAsync(ipAddress).ConfigureAwait(false); // Set fields for repeated fails to lock them out. long timeLocked = ip.TimestampLocked; long maxSeconds = TimeUtilityService.TimespanToSeconds(Constants.MaxIPLockTime); long currentUnix = TimeUtilityService.CurrentUnixTime(); // If the time has passed their max time before unlock, unlock them if (timeLocked + maxSeconds < currentUnix && timeLocked != Constants.NoValueLong) { await _userManagementService.UnlockIPAsync(ipAddress).ConfigureAwait(false); } if (await _userManagementService.CheckIfIPLockedAsync(ipAddress).ConfigureAwait(false)) { _ = _loggingManager.LogAsync(DateTime.UtcNow.ToString(Constants.LoggingFormatString), Constants.RegistrationOperation, Constants.AnonymousUserIdentifier, ipAddress, Constants.IPLockedLogMessage).ConfigureAwait(false); return(SystemUtilityService.CreateResult(Constants.IPLockedUserMessage, registrationSuccess, false)); } // Check the length of their first name. if (!StringUtilityService.CheckLength(firstName, Constants.MaximumFirstNameCharacters, Constants.MinimumFirstNameCharacters)) { await _userManagementService.IncrementRegistrationFailuresAsync(ipAddress, Constants.RegistrationTriesResetTime, Constants.MaxRegistrationAttempts).ConfigureAwait(false); _ = _loggingManager.LogAsync(DateTime.UtcNow.ToString(Constants.LoggingFormatString), Constants.RegistrationOperation, Constants.AnonymousUserIdentifier, ipAddress, Constants.InvalidFirstNameLengthLogMessage).ConfigureAwait(false); return(SystemUtilityService.CreateResult(Constants.InvalidFirstNameLengthUserMessage, registrationSuccess, false)); } // Check the character requirements of their first name. if (!StringUtilityService.CheckCharacters(firstName, Constants.CharSetsData[Constants.FirstNameCharacterType])) { await _userManagementService.IncrementRegistrationFailuresAsync(ipAddress, Constants.RegistrationTriesResetTime, Constants.MaxRegistrationAttempts).ConfigureAwait(false); _ = _loggingManager.LogAsync(DateTime.UtcNow.ToString(Constants.LoggingFormatString), Constants.RegistrationOperation, Constants.AnonymousUserIdentifier, ipAddress, Constants.InvalidFirstNameCharactersLogMessage).ConfigureAwait(false); return(SystemUtilityService.CreateResult(Constants.InvalidFirstNameCharactersUserMessage, registrationSuccess, false)); } // Check the length of their last name. if (!StringUtilityService.CheckLength(lastName, Constants.MaximumLastNameCharacters, Constants.MinimumLastNameCharacters)) { await _userManagementService.IncrementRegistrationFailuresAsync(ipAddress, Constants.RegistrationTriesResetTime, Constants.MaxRegistrationAttempts).ConfigureAwait(false); _ = _loggingManager.LogAsync(DateTime.UtcNow.ToString(Constants.LoggingFormatString), Constants.RegistrationOperation, Constants.AnonymousUserIdentifier, ipAddress, Constants.InvalidLastNameLengthLogMessage).ConfigureAwait(false); return(SystemUtilityService.CreateResult(Constants.InvalidLastNameLengthUserMessage, registrationSuccess, false)); } // Check the character requirements of their last name. if (!StringUtilityService.CheckCharacters(lastName, Constants.CharSetsData[Constants.LastNameCharacterType])) { await _userManagementService.IncrementRegistrationFailuresAsync(ipAddress, Constants.RegistrationTriesResetTime, Constants.MaxRegistrationAttempts).ConfigureAwait(false); _ = _loggingManager.LogAsync(DateTime.UtcNow.ToString(Constants.LoggingFormatString), Constants.RegistrationOperation, Constants.AnonymousUserIdentifier, ipAddress, Constants.InvalidLastNameCharactersLogMessage).ConfigureAwait(false); return(SystemUtilityService.CreateResult(Constants.InvalidLastNameCharactersUserMessage, registrationSuccess, false)); } // Check the length of their email. if (!StringUtilityService.CheckLength(email, Constants.MaximumEmailCharacters, Constants.MinimumEmailCharacters)) { await _userManagementService.IncrementRegistrationFailuresAsync(ipAddress, Constants.RegistrationTriesResetTime, Constants.MaxRegistrationAttempts).ConfigureAwait(false); _ = _loggingManager.LogAsync(DateTime.UtcNow.ToString(Constants.LoggingFormatString), Constants.RegistrationOperation, Constants.AnonymousUserIdentifier, ipAddress, Constants.InvalidEmailLengthLogMessage).ConfigureAwait(false); return(SystemUtilityService.CreateResult(Constants.InvalidEmailLengthUserMessage, registrationSuccess, false)); } // Check the character requirements of their email. if (!StringUtilityService.CheckCharacters(email, Constants.CharSetsData[Constants.EmailCharacterType])) { await _userManagementService.IncrementRegistrationFailuresAsync(ipAddress, Constants.RegistrationTriesResetTime, Constants.MaxRegistrationAttempts).ConfigureAwait(false); _ = _loggingManager.LogAsync(DateTime.UtcNow.ToString(Constants.LoggingFormatString), Constants.RegistrationOperation, Constants.AnonymousUserIdentifier, ipAddress, Constants.InvalidEmailCharactersLogMessage).ConfigureAwait(false); return(SystemUtilityService.CreateResult(Constants.InvalidEmailCharactersUserMessage, registrationSuccess, false)); } // Check the format of their email. if (!StringUtilityService.CheckEmailFormatValidity(email)) { await _userManagementService.IncrementRegistrationFailuresAsync(ipAddress, Constants.RegistrationTriesResetTime, Constants.MaxRegistrationAttempts).ConfigureAwait(false); _ = _loggingManager.LogAsync(DateTime.UtcNow.ToString(Constants.LoggingFormatString), Constants.RegistrationOperation, Constants.AnonymousUserIdentifier, ipAddress, Constants.InvalidEmailFormatMessage).ConfigureAwait(false); return(SystemUtilityService.CreateResult(Constants.InvalidEmailFormatMessage, registrationSuccess, false)); } // Email must be unique after canonicalization. string canonicalizedEmail = StringUtilityService.CanonicalizeEmail(email); if (await _userManagementService.CheckEmailExistenceAsync(canonicalizedEmail).ConfigureAwait(false)) { await _userManagementService.IncrementRegistrationFailuresAsync(ipAddress, Constants.RegistrationTriesResetTime, Constants.MaxRegistrationAttempts).ConfigureAwait(false); _ = _loggingManager.LogAsync(DateTime.UtcNow.ToString(Constants.LoggingFormatString), Constants.RegistrationOperation, Constants.AnonymousUserIdentifier, ipAddress, Constants.EmailExistsLogMessage).ConfigureAwait(false); Console.WriteLine("Email"); return(SystemUtilityService.CreateResult(Constants.UniqueIdExistsRegistrationUserMessage, registrationSuccess, false)); } // Check the length of their username. if (!StringUtilityService.CheckLength(username, Constants.MaximumUsernameCharacters, Constants.MinimumUsernameCharacters)) { await _userManagementService.IncrementRegistrationFailuresAsync(ipAddress, Constants.RegistrationTriesResetTime, Constants.MaxRegistrationAttempts).ConfigureAwait(false); _ = _loggingManager.LogAsync(DateTime.UtcNow.ToString(Constants.LoggingFormatString), Constants.RegistrationOperation, Constants.AnonymousUserIdentifier, ipAddress, Constants.InvalidUsernameLengthLogMessage).ConfigureAwait(false); return(SystemUtilityService.CreateResult(Constants.InvalidUsernameLengthUserMessage, registrationSuccess, false)); } // Check the character requirements of their username. if (!StringUtilityService.CheckCharacters(email, Constants.CharSetsData[Constants.UsernameCharacterType])) { await _userManagementService.IncrementRegistrationFailuresAsync(ipAddress, Constants.RegistrationTriesResetTime, Constants.MaxRegistrationAttempts).ConfigureAwait(false); _ = _loggingManager.LogAsync(DateTime.UtcNow.ToString(Constants.LoggingFormatString), Constants.RegistrationOperation, Constants.AnonymousUserIdentifier, ipAddress, Constants.InvalidUsernameCharactersLogMessage).ConfigureAwait(false); return(SystemUtilityService.CreateResult(Constants.InvalidUsernameCharactersUserMessage, registrationSuccess, false)); } // Check username uniqueness. if (await _userManagementService.CheckUserExistenceAsync(username).ConfigureAwait(false)) { await _userManagementService.IncrementRegistrationFailuresAsync(ipAddress, Constants.RegistrationTriesResetTime, Constants.MaxRegistrationAttempts).ConfigureAwait(false); _ = _loggingManager.LogAsync(DateTime.UtcNow.ToString(Constants.LoggingFormatString), Constants.RegistrationOperation, Constants.AnonymousUserIdentifier, ipAddress, Constants.UsernameExistsLogMessage).ConfigureAwait(false); Console.WriteLine("username"); return(SystemUtilityService.CreateResult(Constants.UniqueIdExistsRegistrationUserMessage, registrationSuccess, false)); } // Check the length of their phone number. if (!StringUtilityService.CheckLength(phoneNumber, Constants.PhoneNumberCharacterLength)) { await _userManagementService.IncrementRegistrationFailuresAsync(ipAddress, Constants.RegistrationTriesResetTime, Constants.MaxRegistrationAttempts).ConfigureAwait(false); _ = _loggingManager.LogAsync(DateTime.UtcNow.ToString(Constants.LoggingFormatString), Constants.RegistrationOperation, Constants.AnonymousUserIdentifier, ipAddress, Constants.InvalidPhoneNumberLengthLogMessage).ConfigureAwait(false); return(SystemUtilityService.CreateResult(Constants.InvalidPhoneNumberLengthUserMessage, registrationSuccess, false)); } // Check the character requirements of their phone number. if (!StringUtilityService.CheckCharacters(phoneNumber, Constants.CharSetsData[Constants.PhoneNumberCharacterType])) { await _userManagementService.IncrementRegistrationFailuresAsync(ipAddress, Constants.RegistrationTriesResetTime, Constants.MaxRegistrationAttempts).ConfigureAwait(false); _ = _loggingManager.LogAsync(DateTime.UtcNow.ToString(Constants.LoggingFormatString), Constants.RegistrationOperation, Constants.AnonymousUserIdentifier, ipAddress, Constants.InvalidPhoneNumberCharactersLogMessage).ConfigureAwait(false); return(SystemUtilityService.CreateResult(Constants.InvalidPhoneNumberCharactersUserMessage, registrationSuccess, false)); } // Check phone number uniqueness. if (await _userManagementService.CheckPhoneNumberExistenceAsync(phoneNumber).ConfigureAwait(false)) { await _userManagementService.IncrementRegistrationFailuresAsync(ipAddress, Constants.RegistrationTriesResetTime, Constants.MaxRegistrationAttempts).ConfigureAwait(false); _ = _loggingManager.LogAsync(DateTime.UtcNow.ToString(Constants.LoggingFormatString), Constants.RegistrationOperation, Constants.AnonymousUserIdentifier, ipAddress, Constants.PhoneNumberExistsLogMessage).ConfigureAwait(false); Console.WriteLine("phone"); return(SystemUtilityService.CreateResult(Constants.UniqueIdExistsRegistrationUserMessage, registrationSuccess, false)); } // Check the length of their password. if (!StringUtilityService.CheckLength(proxyPassword, Constants.MaximumPasswordCharacters, Constants.MinimumPasswordCharacters)) { await _userManagementService.IncrementRegistrationFailuresAsync(ipAddress, Constants.RegistrationTriesResetTime, Constants.MaxRegistrationAttempts).ConfigureAwait(false); _ = _loggingManager.LogAsync(DateTime.UtcNow.ToString(Constants.LoggingFormatString), Constants.RegistrationOperation, Constants.AnonymousUserIdentifier, ipAddress, Constants.InvalidPasswordLengthLogMessage).ConfigureAwait(false); return(SystemUtilityService.CreateResult(Constants.InvalidPasswordLengthUserMessage, registrationSuccess, false)); } // Successful registration! registrationSuccess = true; // Create user record object to represent a user. // Email code, email code timestamp, login failures, last login failure timestamp, email code failures, and phone code failures initialized to have no value. UserRecord user = new UserRecord(username, firstName + " " + lastName, canonicalizedEmail, phoneNumber, hashedPassword, Constants.EnabledStatus, Constants.CustomerUserType, salt, Constants.NoValueLong, Constants.NoValueString, Constants.NoValueLong, Constants.NoValueInt, Constants.NoValueLong, Constants.NoValueInt, Constants.NoValueInt); // Create that user. await _userManagementService.CreateUserAsync(true, user).ConfigureAwait(false); _ = _loggingManager.LogAsync(DateTime.UtcNow.ToString(Constants.LoggingFormatString), Constants.RegistrationOperation, Constants.AnonymousUserIdentifier, ipAddress).ConfigureAwait(false); return(SystemUtilityService.CreateResult(Constants.RegistrationSuccessUserMessage, registrationSuccess, false)); } catch (Exception e) { Console.WriteLine(e.Message); Console.WriteLine(e.StackTrace); _ = _loggingManager.LogAsync(DateTime.UtcNow.ToString(Constants.LoggingFormatString), Constants.RegistrationOperation, Constants.AnonymousUserIdentifier, ipAddress, e.Message).ConfigureAwait(false); if (currentNumExceptions + 1 >= Constants.MaximumOperationRetries) { await SystemUtilityService.NotifySystemAdminAsync($"{Constants.RegistrationOperation} failed a maximum number of times for {ipAddress}.", Constants.SystemAdminEmailAddress).ConfigureAwait(false); } return(SystemUtilityService.CreateResult(Constants.SystemErrorUserMessage, false, true)); } }
// Encrypted password, encrypted AES key, and aesIV are all in hex string format. public async Task <Result <AuthenticationResult> > LogInAsync(string username, string ipAddress, string password, int currentNumExceptions) { bool authenticationSuccessful = false; bool userExist = false; try { // If the username doesn't exist. if (!await _userManagementService.CheckUserExistenceAsync(username).ConfigureAwait(false)) { // Log the action. _ = _loggingManager.LogAsync(DateTime.UtcNow.ToString(Constants.LoggingFormatString), Constants.LogInOperation, Constants.AnonymousUserIdentifier, ipAddress, Constants.UsernameDNELogMessage).ConfigureAwait(false); // Return the result of the login failure. AuthenticationResult authenResult = new AuthenticationResult(authenticationSuccessful, userExist); return(SystemUtilityService.CreateResult(Constants.InvalidLogInUserMessage, authenResult, false)); } userExist = true; // Get the information of the usernmae. UserObject user = await _userManagementService.GetUserInfoAsync(username).ConfigureAwait(false); // If the username is disabled. if (user.Disabled == 1) { // Log the action. _ = _loggingManager.LogAsync(DateTime.UtcNow.ToString(Constants.LoggingFormatString), Constants.LogInOperation, Constants.AnonymousUserIdentifier, ipAddress, Constants.UserDisableLogMessage).ConfigureAwait(false); // Return the result of the disabled username's login try. AuthenticationResult authenResult = new AuthenticationResult(authenticationSuccessful, userExist); return(SystemUtilityService.CreateResult(Constants.UserDisableUserMessage, authenResult, false)); } AuthenticationDTO existing = new AuthenticationDTO(username, user.Password); AuthenticationDTO credentials = new AuthenticationDTO(username, password); // If the username's stored password matches the hashed password. if (_authenticationService.Authenticate(existing, credentials)) { authenticationSuccessful = true; // Create a token for the username. string token = await _sessionService.CreateTokenAsync(username).ConfigureAwait(false); // Get user type. string userType = await _userManagementService.GetUserTypeAsync(username).ConfigureAwait(false); Console.WriteLine(userType); // Get the path to store the token. string path = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); path = path + $"{path.Substring(0, 1)}" + Constants.TokenFile; // Save the token the the path. using (StreamWriter sw = File.CreateText(path)) { sw.WriteLine(token); } // Log the action. _ = _loggingManager.LogAsync(DateTime.UtcNow.ToString(Constants.LoggingFormatString), Constants.LogInOperation, username, ipAddress).ConfigureAwait(false); // Return the result of the successful login. AuthenticationResult authenResult = new AuthenticationResult(authenticationSuccessful, userExist, token, userType); return(SystemUtilityService.CreateResult(Constants.LogInSuccessUserMessage, authenResult, false)); } // If the password doesn't match. else { // Increment the number of login failure. await _userManagementService.IncrementLoginFailuresAsync(username, Constants.LogInTriesResetTime, Constants.MaxLogInAttempts).ConfigureAwait(false); // Log the action. _ = _loggingManager.LogAsync(DateTime.UtcNow.ToString(Constants.LoggingFormatString), Constants.LogInOperation, Constants.AnonymousUserIdentifier, ipAddress, Constants.InvalidPasswordLogMessage).ConfigureAwait(false); // Return the result of the unsuccessful login. AuthenticationResult authenResult = new AuthenticationResult(authenticationSuccessful, userExist); return(SystemUtilityService.CreateResult(Constants.InvalidLogInUserMessage, authenResult, false)); } } // Catch exceptions. catch (Exception e) { // Log the exception. _ = _loggingManager.LogAsync(DateTime.UtcNow.ToString(Constants.LoggingFormatString), Constants.LogInOperation, Constants.AnonymousUserIdentifier, ipAddress, e.Message).ConfigureAwait(false); // If the current number of consecutive exceptions has reached the maximum number of retries. if (currentNumExceptions + 1 >= Constants.MaximumOperationRetries) { // Notify the system admin. await SystemUtilityService.NotifySystemAdminAsync($"{Constants.LogInOperation} failed a maximum number of times for {username}.", Constants.SystemAdminEmailAddress).ConfigureAwait(false); } // Return the result of the exception occured. AuthenticationResult authenResult = new AuthenticationResult(authenticationSuccessful, userExist); return(SystemUtilityService.CreateResult(Constants.SystemErrorUserMessage, authenResult, true)); } }