diff --git a/ADefHelpDeskWebApp/Pages/Authentication/ExternalLogin.razor b/ADefHelpDeskWebApp/Pages/Authentication/ExternalLogin.razor deleted file mode 100644 index 3900372..0000000 --- a/ADefHelpDeskWebApp/Pages/Authentication/ExternalLogin.razor +++ /dev/null @@ -1,388 +0,0 @@ -@page "/Account/ExternalLogin" -@inherits OwningComponentBase -@using System.ComponentModel.DataAnnotations -@using System.Security.Claims -@using System.Text -@using System.Text.Encodings.Web -@using ADefHelpDeskWebApp.Classes -@using ADefHelpDeskWebApp.Components.Account -@using ADefHelpDeskWebApp.Controllers -@using AdefHelpDeskBase.Controllers -@using AdefHelpDeskBase.Models -@using Microsoft.AspNetCore.Identity -@using Microsoft.AspNetCore.WebUtilities -@using ADefHelpDeskWebApp.Data -@inject ApplicationSettingsController _ApplicationSettingsController -@inject RegisterController _RegisterController -@inject IConfiguration _configuration -@inject IWebHostEnvironment _HostEnvironment -@inject UserManager _UserManager -@inject SignInManager _SignInManager -@inject RoleManager _RoleManager -@inject SignInManager SignInManager -@inject UserManager UserManager -@inject IUserStore UserStore -@inject IEmailSender EmailSender -@inject NavigationManager NavigationManager -@inject IdentityRedirectManager RedirectManager -@inject ILogger Logger - -External Login -@if (message != null) -{ - -} - -@if (!ShowSuccess) -{ -

Associate your @ProviderDisplayName account to @strEmail

-
- -
- You've successfully authenticated with @ProviderDisplayName. - Please enter the password for the existing @strEmail account - and click the Associate button to finish logging in. -
- -
-
- - - -
- -
- -
-
-
- -
- @if (Showlogout) - { -
-
-
- @if (externalLoginInfo.LoginProvider == "Google") - { - - Or [Log out of your oogle account] - - } - else if (externalLoginInfo.LoginProvider == "Microsoft") - { - - Or [Log out of Microsoft account] - - } -
-
-
- } -} -else -{ -
- You've successfully associated @ProviderDisplayName with the existing account. -
-
-
-
- -
- -
-
-
-} -@code { - public const string LoginCallbackAction = "LoginCallback"; - - private string message; - private ExternalLoginInfo externalLoginInfo = default!; - - [CascadingParameter] - private HttpContext HttpContext { get; set; } = default!; - - [SupplyParameterFromForm] - private InputModel Input { get; set; } = new(); - - [SupplyParameterFromQuery] - private string RemoteError { get; set; } - - [SupplyParameterFromQuery] - private string ReturnUrl { get; set; } - - [SupplyParameterFromQuery] - private string Action { get; set; } - - private string ProviderDisplayName => externalLoginInfo.ProviderDisplayName; - - private bool AllowRegistration = false; - private bool Showlogout = false; - private bool ShowSuccess = false; - - string strEmail = ""; - string strFirstName = ""; - string strLastName = ""; - - // RegisterStatus to return - RegisterStatus objRegisterStatus = new RegisterStatus(); - - protected override async Task OnInitializedAsync() - { - _RegisterController = (RegisterController)ScopedServices.GetService(typeof(RegisterController)); - _ApplicationSettingsController = (ApplicationSettingsController)ScopedServices.GetService(typeof(ApplicationSettingsController)); - - var DTOSettings = _ApplicationSettingsController.GetSettings("", NavigationManager.BaseUri); - AllowRegistration = DTOSettings.allowRegistration; - - if (RemoteError is not null) - { - RedirectManager.RedirectToWithStatus("Account/Login", $"Error from external provider: {RemoteError}", HttpContext); - } - - var info = await SignInManager.GetExternalLoginInfoAsync(); - - if (info is null) - { - RedirectManager.RedirectToWithStatus("Account/Login", "Error loading external login information.", HttpContext); - } - - externalLoginInfo = info; - - if (HttpMethods.IsGet(HttpContext.Request.Method)) - { - if (Action == LoginCallbackAction) - { - await OnLoginCallbackAsync(); - return; - } - - // We should only reach this page via the login callback, so redirect back to - // the login page if we get here some other way. - RedirectManager.RedirectTo("Account/Login"); - } - } - - private async Task OnLoginCallbackAsync() - { - // Sign in the user with this external login provider if the user already has a login. - var result = await SignInManager.ExternalLoginSignInAsync( - externalLoginInfo.LoginProvider, - externalLoginInfo.ProviderKey, - isPersistent: false, - bypassTwoFactor: true); - - if (result.Succeeded) - { - try - { - Log.InsertSystemLog(GetConnectionString(), "LoginExternal", externalLoginInfo.Principal.Identity?.Name, $"{externalLoginInfo.Principal.Identity?.Name} logged in with {externalLoginInfo.LoginProvider} provider."); - } - catch - { - // Do nothing - } - - RedirectManager.RedirectTo(ReturnUrl); - } - else if (result.IsLockedOut) - { - RedirectManager.RedirectTo("Account/Lockout"); - } - - if (AllowRegistration) - { - await CreateAccountAsync(); - } - else - { - RedirectManager.RedirectTo("Account/Login"); - } - } - - private async Task OnValidSubmitAsync() - { - if (Input.Password != null) - { - try - { - // Get email of the ExternalLoginUser - string ExternalLoginUserEmail = ""; - if (externalLoginInfo.Principal.HasClaim(c => c.Type == ClaimTypes.Email)) - { - ExternalLoginUserEmail = - externalLoginInfo.Principal.FindFirstValue(ClaimTypes.Email); - } - - // Check password against user in database - var user = await UserManager.FindByEmailAsync(ExternalLoginUserEmail); - - if (user != null) - { - var CheckPasswordResult = - await UserManager.CheckPasswordAsync(user, Input.Password); - - if (CheckPasswordResult) - { - // user found and password is correct - // add external login to user and sign in - var AddLoginResult = - await UserManager.AddLoginAsync(user, externalLoginInfo); - - if (AddLoginResult.Succeeded) - { - await SignInManager.SignInAsync(user, isPersistent: false, externalLoginInfo.LoginProvider); - ShowSuccess = true; - - try - { - Log.InsertSystemLog(GetConnectionString(), "LoginExternal", user.Email, $"{user.Email ?? "[missing email]"} added {externalLoginInfo.LoginProvider} provider."); - } - catch - { - // Do nothing - } - - HttpContext.RedirectTo("Index"); - } - else - { - foreach (var error in AddLoginResult.Errors) - { - message = error.Description; - } - } - } - else // password is incorrect - { - message = "Password is incorrect"; - } - } - } - catch (Exception ex) - { - message = ex.Message; - } - } - } - - private async Task CreateAccountAsync() - { - // If the user does not have an account create an account. - - if (externalLoginInfo.Principal.HasClaim(c => c.Type == ClaimTypes.Email)) - { - strEmail = externalLoginInfo.Principal.FindFirstValue(ClaimTypes.Email) ?? ""; - } - - if (externalLoginInfo.Principal.HasClaim(c => c.Type == ClaimTypes.GivenName)) - { - strFirstName = externalLoginInfo.Principal.FindFirstValue(ClaimTypes.GivenName) ?? ""; - } - - if (externalLoginInfo.Principal.HasClaim(c => c.Type == ClaimTypes.Surname)) - { - strLastName = externalLoginInfo.Principal.FindFirstValue(ClaimTypes.Surname) ?? ""; - } - - // Create the User - RegisterDTO objRegister = new RegisterDTO(); - objRegister.email = strEmail; - objRegister.userName = strEmail; - objRegister.firstName = strFirstName; - objRegister.lastName = strLastName; - objRegister.password = ""; - - string strDefaultConnection = _configuration["ConnectionStrings:DefaultConnection"]; - - objRegisterStatus = await _RegisterController.RegisterUser( - objRegister, strDefaultConnection, _HostEnvironment, _UserManager, - _SignInManager, true, NavigationManager.BaseUri); - - if (!objRegisterStatus.isSuccessful) - { - Showlogout = true; - return; - } - - var user = await UserManager.FindByNameAsync(strEmail); - - if (user != null) - { - var result = await UserManager.AddLoginAsync(user, externalLoginInfo); - - if (result.Succeeded) - { - await SignInManager.SignInAsync(user, isPersistent: false, externalLoginInfo.LoginProvider); - - try - { - Log.InsertSystemLog(GetConnectionString(), "LoginExternal", user.Email ?? "[missing email]", $"{user.Email ?? "[missing email]"} created an account using {externalLoginInfo.LoginProvider} provider."); - } - catch - { - // Do nothing - } - - RedirectManager.RedirectTo(ReturnUrl); - } - } - - message = $"Error: User could not be created"; - } - - private ApplicationUser CreateUser() - { - try - { - return Activator.CreateInstance(); - } - catch - { - throw new InvalidOperationException($"Can't create an instance of '{nameof(ApplicationUser)}'. " + - $"Ensure that '{nameof(ApplicationUser)}' is not an abstract class and has a parameterless constructor"); - } - } - - private sealed class InputModel - { - [Required] - public string Password { get; set; } = ""; - } - - private string GetConnectionString() - { - try - { - return _configuration.GetConnectionString("DefaultConnection"); - } - catch - { - return "ERROR:UNSET-CONNECTION-STRING"; - } - } - - #region CreateVerificationKey - private static string CreateVerificationKey(int KeyLength) - { - const string valid = "12389ABC*DEFGHIJKL@MN4567OPQRSTUVWXYZ#%"; - StringBuilder res = new StringBuilder(); - Random rnd = new Random(); - while (0 < KeyLength--) - { - res.Append(valid[rnd.Next(valid.Length)]); - } - return res.ToString() + "_u9#"; - } - #endregion -} \ No newline at end of file diff --git a/ADefHelpDeskWebApp/Pages/Authentication/ExternalLoginPicker.razor b/ADefHelpDeskWebApp/Pages/Authentication/ExternalLoginPicker.razor deleted file mode 100644 index 4a2ba3c..0000000 --- a/ADefHelpDeskWebApp/Pages/Authentication/ExternalLoginPicker.razor +++ /dev/null @@ -1,101 +0,0 @@ -@using ADefHelpDeskWebApp.Classes -@using ADefHelpDeskWebApp.Controllers -@using AdefHelpDeskBase.Models -@using Microsoft.AspNetCore.Authentication -@using Microsoft.AspNetCore.Identity -@using ADefHelpDeskWebApp.Data -@inject ApplicationSettingsController _ApplicationSettingsController -@inject SignInManager SignInManager -@inject IConfiguration _configuration - -@if (externalLogins.Length > 0) -{ - -
-
- - -

- @foreach (var provider in externalLogins) - { - if (provider.Name == "Google") - { -

- -
-    - } - else if (provider.Name == "Microsoft") - { -
- -
-    - } - else - { -
- -
- } - } -

-
-
-} -@code { - [SupplyParameterFromQuery] - private string ReturnUrl { get; set; } - - private AuthenticationScheme[] externalLogins = []; - - protected override async Task OnInitializedAsync() - { - externalLogins = (await SignInManager.GetExternalAuthenticationSchemesAsync()).ToArray(); - - // Suppress any external logins that are not configured - string strDefaultConnection = _configuration["ConnectionStrings:DefaultConnection"]; - - GeneralSettings objGeneralSettings = new GeneralSettings(strDefaultConnection); - - if (objGeneralSettings.GoogleClientID == "" || objGeneralSettings.GoogleClientSecret == "") - { - externalLogins = externalLogins.Where(x => x.Name != "Google").ToArray(); - } - - if (objGeneralSettings.MicrosoftClientID == "" || objGeneralSettings.MicrosoftClientSecret == "") - { - externalLogins = externalLogins.Where(x => x.Name != "Microsoft").ToArray(); - } - } -} \ No newline at end of file diff --git a/ADefHelpDeskWebApp/Pages/Authentication/Login.cshtml b/ADefHelpDeskWebApp/Pages/Authentication/Login.cshtml deleted file mode 100644 index 25af260..0000000 --- a/ADefHelpDeskWebApp/Pages/Authentication/Login.cshtml +++ /dev/null @@ -1,19 +0,0 @@ -@page -@model BlazorGoogleAuth.Pages.Identity.Login - -@{ - Layout = null; -} - - - - - - - - -
- -
- - \ No newline at end of file diff --git a/ADefHelpDeskWebApp/Pages/Authentication/Login.cshtml.cs b/ADefHelpDeskWebApp/Pages/Authentication/Login.cshtml.cs deleted file mode 100644 index 08f4417..0000000 --- a/ADefHelpDeskWebApp/Pages/Authentication/Login.cshtml.cs +++ /dev/null @@ -1,41 +0,0 @@ -#nullable enable -using Microsoft.AspNetCore.Authentication; -using Microsoft.AspNetCore.Authentication.Cookies; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Mvc.RazorPages; - -namespace BlazorGoogleAuth.Pages.Identity; - -[AllowAnonymous] -public class Login : PageModel -{ - public IActionResult OnGetAsync(string? returnUrl = null) - { - return new ChallengeResult("Google", new() - { - RedirectUri = Url.Page("./Login", - "Callback", - new {returnUrl}) - }); - } - - public async Task OnGetCallbackAsync(string? returnUrl = null, string? remoteError = null) - { - // Get the information about the user from the external login provider - var user = User.Identities.FirstOrDefault(); - if (!(user?.IsAuthenticated ?? false)) - return LocalRedirect("/"); - - await HttpContext.SignInAsync( - CookieAuthenticationDefaults.AuthenticationScheme, - new(user), - new() - { - IsPersistent = true, - RedirectUri = Request.Host.Value - }); - - return LocalRedirect("/"); - } -} \ No newline at end of file diff --git a/ADefHelpDeskWebApp/Pages/Authentication/LoginControl.razor b/ADefHelpDeskWebApp/Pages/Authentication/LoginControl.razor deleted file mode 100644 index c269203..0000000 --- a/ADefHelpDeskWebApp/Pages/Authentication/LoginControl.razor +++ /dev/null @@ -1,278 +0,0 @@ -@page "/Authentication/logincontrol" -@using ADefHelpDeskWebApp.Components.Account -@using Microsoft.AspNetCore.Authentication -@using Microsoft.AspNetCore.Identity -@using Microsoft.AspNetCore.Hosting -@using Microsoft.EntityFrameworkCore -@using Microsoft.Extensions.Configuration -@using Microsoft.AspNetCore.Http -@using ADefHelpDeskWebApp.Classes -@using AdefHelpDeskBase.Models -@using AdefHelpDeskBase.Models.DataContext -@using System.ComponentModel.DataAnnotations -@inject UserManager _userManager -@inject SignInManager _signInManager -@inject IWebHostEnvironment _hostEnvironment -@inject IConfiguration _config -@inject IHttpContextAccessor _httpContextAccessor -@inject NavigationManager NavigationManager -@inject IdentityRedirectManager RedirectManager - -
-
-
-

@errorMessage

- - -

Use a local account to log in.

-
- -
- - - -
-
- - - -
- @if (requiresVerification) - { -
- - -
- } -
-      - -
-
- -
-
-
-
- @if (externalLogins.Length > 0) - { -
-
-

Login in with your social account

-
- -
-
- } -
-@code { - [CascadingParameter] - private HttpContext HttpContext { get; set; } = default!; - - [SupplyParameterFromForm] - private InputModel Input { get; set; } = new(); - - [SupplyParameterFromQuery] - private string ReturnUrl { get; set; } - - string errorMessage = ""; - bool requiresVerification = false; - - private AuthenticationScheme[] externalLogins = []; - - public IList ExternalLogins { get; set; } - - protected override async Task OnInitializedAsync() - { - if (HttpContext is not null) - { - if (HttpMethods.IsGet(HttpContext.Request.Method)) - { - // Clear the existing external cookie to ensure a clean login process - await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme); - } - } - - // Suppress any external logins that are not configured - - externalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToArray(); - - GeneralSettings objGeneralSettings = new GeneralSettings(GetConnectionString()); - - if (objGeneralSettings.GoogleClientID == "" || objGeneralSettings.GoogleClientSecret == "") - { - externalLogins = externalLogins.Where(x => x.Name != "Google").ToArray(); - } - - if (objGeneralSettings.MicrosoftClientID == "" || objGeneralSettings.MicrosoftClientSecret == "") - { - externalLogins = externalLogins.Where(x => x.Name != "Microsoft").ToArray(); - } - } - - private async Task LoginUser() - { - try - { - DTOAuthentication objDTOAuthentication = new DTOAuthentication - { - userName = Input.Email, - password = Input.Password, - rememberMe = Input.RememberMe, - verificationCode = Input.VerificationCode - }; - - var objLoginStatus = await GetLoginStatus(objDTOAuthentication); - - if (objLoginStatus.isLoggedIn) - { - var objUser = await _signInManager.UserManager.FindByNameAsync(Input.Email); - - if (objUser != null) - { - await _signInManager.SignInAsync(objUser, false); - - try - { - Log.InsertSystemLog(GetConnectionString(), "Login", objUser.Email, $"{objUser.Email} logged in "); - } - catch - { - // Do nothing - } - - HttpContext.RedirectTo("Index"); - } - } - else if (objLoginStatus.status == "Verify") - { - errorMessage = "Your account needs to be verified. Please check your email for the verification link."; - } - else if (objLoginStatus.status == "IsLockedOut") - { - errorMessage = "Your account is locked out."; - } - else if (objLoginStatus.status == "Authentication Failure") - { - errorMessage = "Authentication Failure."; - } - else - { - errorMessage = "Error: Invalid login attempt."; - } - } - catch (Exception ex) - { - // Log the exception (using a logging framework or a simple log statement) - errorMessage = $"An error occurred during login: {ex.Message}"; - } - } - - public async Task GetLoginStatus(DTOAuthentication Authentication) - { - // LoginStatus to return - var objLoginStatus = new LoginStatus { isLoggedIn = false }; - - // Get values passed - var paramUserName = Authentication.userName; - var paramPassword = Authentication.password; - var paramRememberMe = Authentication.rememberMe; - var paramVerificationCode = Authentication.verificationCode; - - if (paramUserName != null && paramPassword != null) - { - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseSqlServer(GetConnectionString()); - - // Check to see if the user needs to Verify their account - using (var context = new ADefHelpDeskContext(optionsBuilder.Options)) - { - var objAdefHelpDeskUser = context.AdefHelpDeskUsers - .FirstOrDefault(u => u.Username == paramUserName); - - if (objAdefHelpDeskUser?.VerificationCode != null) - { - requiresVerification = true; - - if (paramVerificationCode == null) - { - objLoginStatus.status = "Verify"; - return objLoginStatus; - } - else - { - if (paramVerificationCode.Trim().ToLower() != objAdefHelpDeskUser.VerificationCode.Trim().ToLower()) - { - objLoginStatus.status = "Verify"; - return objLoginStatus; - } - else - { - // Clear the verification code - objAdefHelpDeskUser.VerificationCode = null; - context.SaveChanges(); - } - } - } - } - - // This doesn't count login failures towards account lockout - // To enable password failures to trigger account lockout, set lockoutOnFailure: true - var result = await _signInManager.PasswordSignInAsync(paramUserName, paramPassword, paramRememberMe, lockoutOnFailure: false); - - if (result.Succeeded) - { - objLoginStatus.status = "Success"; - objLoginStatus.isLoggedIn = true; - return objLoginStatus; - } - if (result.RequiresTwoFactor) - { - objLoginStatus.status = "RequiresVerification"; - return objLoginStatus; - } - if (result.IsLockedOut) - { - objLoginStatus.status = "IsLockedOut"; - return objLoginStatus; - } - } - - objLoginStatus.status = "Authentication Failure"; - return objLoginStatus; - } - - private string GetConnectionString() - { - try - { - return _config.GetConnectionString("DefaultConnection"); - } - catch - { - return "ERROR:UNSET-CONNECTION-STRING"; - } - } - - private sealed class InputModel - { - [Required] - public string Email { get; set; } = ""; - - [Required] - [DataType(DataType.Password)] - public string Password { get; set; } = ""; - - [Display(Name = "Remember me?")] - public bool RememberMe { get; set; } - - [Display(Name = "Verification Code")] - public string VerificationCode { get; set; } = ""; - } -} \ No newline at end of file