/// <summary> /// This method is used to login to the Site /// </summary> /// <returns></returns> public static Task <LoginResponse> Login(string emailAddress, string password, bool passwordIsHashed = false) { // initial value LoginResponse loginResponse = new LoginResponse(); // local Artist artist = null; // If the emailAddress string exists if (TextHelper.Exists(emailAddress)) { // Create a new instance of a 'Gateway' object, and set the connectionName Gateway gateway = new Gateway(Connection.Name); // load the sites artist = gateway.FindArtistByEmailAddress(emailAddress); // if the artist exists if (NullHelper.Exists(artist)) { // get the key string key = EnvironmentVariableHelper.GetEnvironmentVariableValue("BlazorImageGallery"); // if the key was found if (TextHelper.Exists(key)) { // can this artist be verified bool isVerified = CryptographyHelper.VerifyHash(password, key, artist.PasswordHash, passwordIsHashed); // if the password hashes match if (isVerified) { // The user did login loginResponse.Success = true; // Set the artist loginResponse.Artist = artist; } else { // Set the message loginResponse.Message = "The passwords do not match."; } } else { // Set the message loginResponse.Message = "The Environment BlazorImageGallery Key was not found."; } } } // return the list return(Task.FromResult(loginResponse)); }
/// <summary> /// This method reads the app.config file to /// load the current configuration. /// </summary> /// <returns></returns> public void ConnectToDatabase(DataManager dataManager) { // locals string methodName = "ConnectToDatabase"; string objectName = "AuthenticationManager"; // Create variable for a possible CustomException CustomException exception = null; try { // If connection is not set if (String.IsNullOrEmpty(dataManager.DataConnector.ConnectionString)) { // if the connectionName is set if (TextHelper.Exists(dataManager.ConnectionName)) { // Set the ConnectionString (requires DataJuggler.Core.UltimateHelper version 1.3.5 or greater) dataManager.DataConnector.ConnectionString = EnvironmentVariableHelper.GetEnvironmentVariableValue(dataManager.ConnectionName); } } // check if database is already connected if (dataManager.DataConnector.State == System.Data.ConnectionState.Open) { // close connection and reopen (there should not be any open connections here) // I have been thinking of a bulk insert feature in the future, but that is not for this method // To Do: Log Error 'Database Connection Was Already Open' dataManager.DataConnector.Close(); } // Open Connection dataManager.DataConnector.Open(); } catch (Exception error) { // If ErrorProcessor exists if (this.ErrorProcessor != null) { // Log this error this.ErrorProcessor.LogError(methodName, objectName, error); } } }
/// <summary> /// This method Process New User Sign Up /// </summary> public async void ProcessNewUserSignUp(object userObject) { // get the user User user = userObject as User; // if the user exists if (NullHelper.Exists(user)) { // Get the KeyCode string keyCode = EnvironmentVariableHelper.GetEnvironmentVariableValue(Connection.Name); // If the keyCode string exists if (TextHelper.Exists(keyCode)) { // Set the PasswordHash, this takes the longest time user.PasswordHash = CryptographyHelper.GeneratePasswordHash(Password, keyCode, 3); // if the password hash was created if (TextHelper.Exists(user.PasswordHash)) { // save the user bool saved = await UserService.SaveUser(ref user); // if saved if ((saved) && (HasParentIndexPage)) { // Force the user to login, see if they entered real data ParentIndexPage.SetupScreen(ScreenTypeEnum.Login); } else { // Show a messagge ValidationMessage = "Oops, something went wrong. Please try again with a different password."; } } else { // Show a messagge ValidationMessage = "Oops, something went wrong. Please try again with a different password."; } } } }
/// <summary> /// This method is used to verify a user /// </summary> /// <param name="firstRender"></param> /// <returns></returns> protected async override Task OnAfterRenderAsync(bool firstRender) { // if there is not a logged in user if (!HasLoggedInUser) { // locals string emailAddress = ""; string storedPasswordHash = ""; try { // get the values from local storage if present bool rememberLogin = await ProtectedLocalStore.GetAsync <bool>("RememberLogin"); // if rememberLogin is true if (rememberLogin) { emailAddress = await ProtectedLocalStore.GetAsync <string>("EmailAddress"); storedPasswordHash = await ProtectedLocalStore.GetAsync <string>("PasswordHash"); // If the emailAddress string exists if (TextHelper.Exists(emailAddress)) { // Attempt to find this user User user = await UserService.FindUserByEmailAddress(emailAddress); // If the user object exists if (NullHelper.Exists(user)) { // get the key string key = EnvironmentVariableHelper.GetEnvironmentVariableValue("BlazorChat"); // if the key was found if (TextHelper.Exists(key)) { // can this artist be verified bool isVerified = CryptographyHelper.VerifyHash(storedPasswordHash, key, user.PasswordHash, true); // if the value for isVerified is true if (isVerified) { // Set the LoggedInuser LoggedInUser = user; } } } } } } catch (Exception error) { // for debugging only DebugHelper.WriteDebugError("OnAfterRenderAsync", "Login.cs", error); } } // call the base await base.OnAfterRenderAsync(firstRender); // if the value for HasLoggedInUser is true if ((HasLoggedInUser) && (firstRender)) { // Refresh the UI Refresh(); } }
/// <summary> /// This method reads the app.config file to /// load the current configuration. /// </summary> /// <returns></returns> public void ConnectToDatabase(DataManager dataManager) { // locals string methodName = "ConnectToDatabase"; string objectName = "AuthenticationManager"; // Create variable for a possible CustomException CustomException exception = null; try { // If connection is not set if (String.IsNullOrEmpty(dataManager.DataConnector.ConnectionString)) { // if the connectionName is set if (TextHelper.Exists(dataManager.ConnectionName)) { // Set the ConnectionString (requires DataJuggler.Core.UltimateHelper version 1.3.5 or greater) dataManager.DataConnector.ConnectionString = EnvironmentVariableHelper.GetEnvironmentVariableValue(dataManager.ConnectionName); } else { // this is for environments using a web.config or app.config. // For Dot Net Core / Blazor or any new projects, Environment Variables are now the // recommended way to store connection strings. // Read Configuration File this.Configuration.Read(); // If the configuration is valid if (this.Configuration.IsValid) { // if the ConnectionString exists if (this.Configuration.HasConnectionString) { // Set the connection string using Integrated Secrity (Windows Authentication) dataManager.DataConnector.ConnectionString = this.Configuration.ConnectionString; } else { // set the server string serverName = this.Configuration.DatabaseServer; // set the databaseName string databaseName = this.Configuration.DatabaseName; // If integrated security is set to true if (this.Configuration.IntegratedSecurity) { // Set the connection string using Integrated Secrity (Windows Authentication) dataManager.DataConnector.ConnectionString = dataManager.DataConnector.BuildConnectionString(serverName, databaseName); } else { // set the userName string userName = this.Configuration.DatabaseUserName; // set the password string password = this.Configuration.DatabasePassword; // build the connectionstring for Sql Server Authentication dataManager.DataConnector.ConnectionString = dataManager.DataConnector.BuildConnectionString(serverName, databaseName, userName, password); } } } } } // check if database is already connected if (dataManager.DataConnector.State == System.Data.ConnectionState.Open) { // close connection and reopen (there should not be any open connections here) // I have been thinking of a bulk insert feature in the future, but that is not for this method // To Do: Log Error 'Database Connection Was Already Open' dataManager.DataConnector.Close(); } // Open Connection dataManager.DataConnector.Open(); } catch (Exception error) { // If ErrorProcessor exists if (this.ErrorProcessor != null) { // Only create a new configuration error if it does not already exist. if (error as CustomException == null) { // If the configuration is not valid if (!this.Configuration.IsValid) { // Create Instance of configurationError exception = new InvalidConfigurationException(methodName, objectName, error); } else { // Create Instance of dataConnectionError exception = new DataConnectionFailedException(methodName, objectName, error); } } // Log this error this.ErrorProcessor.LogError(methodName, objectName, exception); } } }
/// <summary> /// This method Process New User Sign Up /// </summary> public async void ProcessVerifyPassword(object userObject) { try { // cast the object as a signUpModel object User user = userObject as User; // If the user object exists if (NullHelper.Exists(user)) { // Get the KeyCode string keyCode = EnvironmentVariableHelper.GetEnvironmentVariableValue(Connection.Name); // verify the user is logged in bool verified = CryptographyHelper.VerifyHash(password, keyCode, user.PasswordHash); // if not verified if (!verified) { // Set the message ValidationMessage = "The credentials entered were either not found or invalid."; // hide the progress ShowProgress = false; } else { // Set the LoggedInUser on this page LoggedInUser = user; // Set the LoggedInUser ParentIndexPage.LoggedInUser = user; // if the value for RememberLogin is true if (RememberLogin) { // Save the login details in local protected storage await HandleRememberPassword(); } // Update the login information for this user user.LastLoginDate = DateTime.Now; // add to their total logins user.TotalLogins++; // Save the user bool saved = await UserService.SaveUser(ref user); // Set the Logged In User ParentIndexPage.LoggedInUser = user; // Return to the Main Screen, and now you can enter chat ParentIndexPage.SetupScreen(ScreenTypeEnum.Main); } } else { // Set the message ValidationMessage = "The credentials entered were either not found or invalid."; // hide the progress ShowProgress = false; } } catch (Exception error) { // for debugging only for now DebugHelper.WriteDebugError("ProcessVerifyPassword", "Login.razor.cs", error); } }
/// <summary> /// This method Process New User Sign Up /// </summary> public async void ProcessNewUserSignUp(object signUpObject) { // cast the object as a signUpModel object this.SignUpModel = signUpObject as SignUpModel; // if the value for HasSignUpModel is true if (HasSignUpModel) { // locals string passwordHash = ""; bool abort = false; message = ""; // create a new Artist this.Artist = new Artist(); // get the key string key = EnvironmentVariableHelper.GetEnvironmentVariableValue("BlazorImageGallery"); // if the key was found if (TextHelper.Exists(key, password)) { // get the encryptedPassword passwordHash = CryptographyHelper.GeneratePasswordHash(password, key, 3); } // set the artistPath string artistPath = Path.Combine("wwwroot/Images/Gallery", displayName.Replace(" ", "")); // saves going to the database to lookup if the artist exists if (Directory.Exists(artistPath)) { // abort due to artist already exists abort = true; // Set the message Message = "This artist already exists. Sign in if this is you."; // if the value for HasProgressBar is true if (HasProgressBar) { // Stop and hide ProgressBar.Stop(); } } else { // create the artistFolder Directory.CreateDirectory(artistPath); } // if we should continue if (!abort) { // set the bound properties artist.EmailAddress = signUpModel.EmailAddress; artist.PasswordHash = passwordHash; artist.CreatedDate = DateTime.Now; artist.Active = true; artist.Name = signUpModel.DisplayName; artist.CreatedDate = DateTime.Now; artist.LastUpdated = DateTime.Now; artist.FolderPath = artistPath; artist.ProfilePicture = signUpModel.ProfilePictureUrl; artist.Active = true; // Validate this artist bool isValid = ValidateArtist(); // if isValid if (isValid) { // perform the save bool saved = await ArtistService.SaveArtist(ref artist); // if saved if (saved) { // Get the loginResponse this.LoginResponse = await ArtistService.Login(artist.EmailAddress, artist.PasswordHash, true); // The SignUp is complete SignUpComplete = true; } } } } }