locked
Accessing ApplicationUser Property in the Login.cshtml.cs page RRS feed

  • Question

  • User1554758465 posted

    I'm developing web application using ASP.Net MVC Core. I used "Individual user authentication" so the identity table, Register and Login pages is generated by default.

    I extended the identity table with enum column called "AccountStatus" that has Four values as following:

    public class ApplicationUser : IdentityUser
    {
    
        public int StatusId { get; set; }
        public string StatusName { get; set; }
        public AccountStatusId AccountStatusId { get; set; }
        public AccountStatus AccountStatus { get; set; }
    
    }
        public enum AccountStatusId : int
        {
            Active = 0,
            InActive = 1,
            Expired = 2,
            Pending = 3
        }
        public class AccountStatus
        {
            public AccountStatusId AccountStatusId { get; set; }
            public string Status { get; set; }
    
            public List<ApplicationUser> Statuses { get; set; }
        }

    I did the migration for the above code and I created 2 roles (Center and Admin).

     public class SD
    {
        public const string AdminUser = "Admin";
        public const string CenterUser = "Center";
    
    }

    so , I want in the Login.cshtml.cs below to check if the "AccountStatusId = AccountStatusId.Pending" then prevent the user from successful login and display a message "Waits for Approval".

    But I'm not sure how can i access the field "AccountStatusId" which is in "ApplicationUser" model and check this field if "Pending" in Login.cshtml.cs page. Any help is appreciated.

    Login.cshtml.cs

    namespace RegisterTest.Areas.Identity.Pages.Account
    {
        [AllowAnonymous]
        public class LoginModel : PageModel
        {
            private readonly UserManager<IdentityUser> _userManager;
            private readonly SignInManager<IdentityUser> _signInManager;
            private readonly ILogger<LoginModel> _logger;
    
            public LoginModel(SignInManager<IdentityUser> signInManager, 
                ILogger<LoginModel> logger,
                UserManager<IdentityUser> userManager)
            {
                _userManager = userManager;
                _signInManager = signInManager;
                _logger = logger;
            }
    
            [BindProperty]
            public InputModel Input { get; set; }
            public IList<AuthenticationScheme> ExternalLogins { get; set; }
            public string ReturnUrl { get; set; }
            [TempData]
            public string ErrorMessage { get; set; }
            public class InputModel
            {
                [Required]
                [EmailAddress]
                public string Email { get; set; }
    
                [Required]
                [DataType(DataType.Password)]
                public string Password { get; set; }
    
                [Display(Name = "Remember me?")]
                public bool RememberMe { get; set; }
            }
            public async Task OnGetAsync(string returnUrl = null)
            {
                    if (!string.IsNullOrEmpty(ErrorMessage))
                    {
                        ModelState.AddModelError(string.Empty, ErrorMessage);
                    }
                    returnUrl = returnUrl ?? Url.Content("~/");
                    // Clear the existing external cookie to ensure a clean login process
                    await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);
                    ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
                    ReturnUrl = returnUrl;
                }
                public async Task<IActionResult> OnPostAsync(string returnUrl = null)
                {
                    returnUrl = returnUrl ?? Url.Content("~/");
                    if (ModelState.IsValid)
                    {
                        // 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(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: false);
    
                        if (result.Succeeded)
                        {
                            _logger.LogInformation("User logged in.");
                            return LocalRedirect(returnUrl);
                        }
                        if (result.RequiresTwoFactor)
                        {
                            return RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = Input.RememberMe });
                        }
                        if (result.IsLockedOut)
                        {
                            _logger.LogWarning("User account locked out.");
                            return RedirectToPage("./Lockout");
                        }
                        else
                        {
                            ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                            return Page();
                        }
                    }
                    // If we got this far, something failed, redisplay form
                    return Page();
                }
            }
        }
    Monday, June 8, 2020 10:42 AM

Answers

  • User711641945 posted

    Hi ShahadAlshuhail,

    Check like below:

    public async Task<IActionResult> OnPostAsync(string returnUrl = null)
    {
        returnUrl = returnUrl ?? Url.Content("~/");
    
        if (ModelState.IsValid)
        {
            var user = _userManager.FindByEmailAsync(Input.Email).Result;
            if(user.AccountStatusId == AccountStatusId.Pending)
            {
                ModelState.AddModelError(string.Empty, "Waits for Approval");
                return Page();
            }
            if(user.AccountStatusId == AccountStatusId.Active)
            {
                var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: true);
                if (result.Succeeded)
                {
                    _logger.LogInformation("User logged in.");
                    return LocalRedirect(returnUrl);
                }
                if (result.RequiresTwoFactor)
                {
                    return RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = Input.RememberMe });
                }
                if (result.IsLockedOut)
                {
                    _logger.LogWarning("User account locked out.");
                    return RedirectToPage("./Lockout");
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                    return Page();
                }
            }
            // This doesn't count login failures towards account lockout
            // To enable password failures to trigger account lockout, set lockoutOnFailure: true
                    
        }
    
        // If we got this far, something failed, redisplay form
        return Page();
    }

    Best Regards,

    Rena

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, June 9, 2020 9:29 AM