Ejemplo n.º 1
0
        public async Task <IActionResult> OnPostAsync()
        {
            Console.WriteLine("[ResetPassword.OnPostAsync]: BEGIN");

            ///////////////////////////////////////////////////////////////////
            // "I'm not a robot" check ...
            ///////////////////////////////////////////////////////////////////
            if (!PageModelUtil.ReCaptchaPassed
                (
                    Request.Form["g-recaptcha-response"],
                    _configuration[MiscConstants.GOOGLE_RECAPTCHA_SECRET],
                    _logger
                )
                )
            {
                Console.WriteLine("[ResetPassword.OnPostAsync] reCAPTCHA FAILED");
                ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                // RECAPTCHA FAILED - redisplay form
                ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                ModelState.AddModelError(string.Empty, "You failed the CAPTCHA. Are you a robot?");
                ViewData["ReCaptchaKey"] = _configuration[MiscConstants.GOOGLE_RECAPTCHA_KEY];
                return(Page());
            }
            Console.WriteLine("[Login.OnPostAsync] reCAPTCHA PASSED");


            if (!ModelState.IsValid)
            {
                return(Page());
            }

            var user = await _userManager.FindByEmailAsync(Input.Email);

            if (user == null)
            {
                // Don't reveal that the user does not exist
                return(RedirectToPage("./ResetPasswordConfirmation"));
            }

            var result = await _userManager.ResetPasswordAsync(user, Input.Code, Input.Password);

            if (result.Succeeded)
            {
                return(RedirectToPage("./ResetPasswordConfirmation"));
            }

            foreach (var error in result.Errors)
            {
                ModelState.AddModelError(string.Empty, error.Description);
            }
            return(Page());
        }
Ejemplo n.º 2
0
        public void OnGet(string returnUrl = null)
        {
            AgencySelectList    = new SelectList(_dbContext.Agencies.OrderBy(a => a.DisplayOrder), "AgencyID", "AgencyName");
            SubAgencySelectList = new SelectList(_dbContext.SubAgencies.OrderBy(sa => sa.DisplayOrder), "SubAgencyID", "SubAgencyName");

            var recaptchaKey = _configuration[MiscConstants.GOOGLE_RECAPTCHA_KEY];
            //Console.WriteLine("recaptchaKey: " + recaptchaKey);

            var recaptchaSecret = _configuration[MiscConstants.GOOGLE_RECAPTCHA_SECRET];

            //Console.WriteLine("recaptchaSecret: " + recaptchaSecret);

            ViewData["ReCaptchaKey"] = _configuration[MiscConstants.GOOGLE_RECAPTCHA_KEY];

            ReturnUrl = PageModelUtil.EnsureLocalUrl(this, returnUrl);
        }
Ejemplo n.º 3
0
        public async Task <IActionResult> OnPostAsync()
        {
            Console.WriteLine("[ForgotPassword.OnPostAsync]: BEGIN");

            ///////////////////////////////////////////////////////////////////
            // "I'm not a robot" check ...
            ///////////////////////////////////////////////////////////////////
            if (!PageModelUtil.ReCaptchaPassed
                (
                    Request.Form["g-recaptcha-response"],
                    _configuration[MiscConstants.GOOGLE_RECAPTCHA_SECRET],
                    _logger
                )
                )
            {
                Console.WriteLine("[Login.OnPostAsync] reCAPTCHA FAILED");
                ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                // RECAPTCHA FAILED - redisplay form
                ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                ModelState.AddModelError(string.Empty, "You failed the CAPTCHA. Are you a robot?");
                ViewData["ReCaptchaKey"] = _configuration[MiscConstants.GOOGLE_RECAPTCHA_KEY];
                return(Page());
            }
            Console.WriteLine("[Login.OnPostAsync] reCAPTCHA PASSED");

            if (ModelState.IsValid)
            {
                var user = await _userManager.FindByEmailAsync(Input.Email);

                if (user == null || !(await _userManager.IsEmailConfirmedAsync(user)))
                {
                    // Don't reveal that the user does not exist or is not confirmed
                    return(RedirectToPage("./ForgotPasswordConfirmation"));
                }

                // For more information on how to enable account confirmation and password reset please
                // visit https://go.microsoft.com/fwlink/?LinkID=532713
                var code = await _userManager.GeneratePasswordResetTokenAsync(user);

                var callbackUrl = Url.ResetPasswordCallbackLink(user.Id, code, Request.Scheme);
                await _emailSender.SendResetPasswordAsync(Input.Email, callbackUrl);

                return(RedirectToPage("./ForgotPasswordConfirmation"));
            }

            return(Page());
        }
Ejemplo n.º 4
0
        public async Task OnGetAsync(string returnUrl = null)
        {
            if (!string.IsNullOrEmpty(ErrorMessage))
            {
                ModelState.AddModelError(string.Empty, ErrorMessage);
            }

            // Clear the existing external cookie to ensure a clean login process
            await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);

            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();

            // Make sure that passed-in 'returnUrl' is of a local origin
            this.ReturnUrl = PageModelUtil.EnsureLocalUrl(this, returnUrl);

            // I'm not a robot
            ViewData["ReCaptchaKey"] = _configuration[MiscConstants.GOOGLE_RECAPTCHA_KEY];
        }
Ejemplo n.º 5
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            if (!ModelState.IsValid)
            {
                Console.WriteLine("Modelstate is INVALID - returning Page()");
                return(Page());
            }

            ReturnUrl = PageModelUtil.EnsureLocalUrl(this, returnUrl);

            ///////////////////////////////////////////////////////////////////
            // "I'm not a robot" check ...
            ///////////////////////////////////////////////////////////////////
            if (!PageModelUtil.ReCaptchaPassed
                (
                    Request.Form["g-recaptcha-response"],     // that's how you get it from the Request object
                    _configuration[MiscConstants.GOOGLE_RECAPTCHA_SECRET],
                    _logger
                )
                )
            {
                Console.WriteLine("reCAPTCHA FAILED");
                ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                // RECAPTCHA FAILED - redisplay form
                ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                ModelState.AddModelError(string.Empty, "You failed the CAPTCHA. Are you a robot?");
                AgencySelectList         = new SelectList(_dbContext.Agencies.OrderBy(a => a.DisplayOrder), "AgencyID", "AgencyName");
                SubAgencySelectList      = new SelectList(_dbContext.SubAgencies.OrderBy(sa => sa.DisplayOrder), "SubAgencyID", "SubAgencyName");
                ViewData["ReCaptchaKey"] = _configuration[MiscConstants.GOOGLE_RECAPTCHA_KEY];
                return(Page());
            }

            Console.WriteLine("reCAPTCHA PASSED");

            if (ModelState.IsValid)
            {
                Console.WriteLine("Modelstate is VALID - processing will continue");

                var user = new ApplicationUser
                {
                    UserName                = Input.Email,
                    Email                   = Input.Email,
                    FirstName               = Input.FirstName,
                    MiddleName              = Input.MiddleName,
                    LastName                = Input.LastName,
                    JobTitle                = Input.JobTitle,
                    AgencyID                = Input.AgencyID,
                    SubAgencyID             = Input.SubAgencyID,
                    DateRegistered          = DateTime.Now,
                    DateAccountExpires      = DateTime.Now.AddDays(AccountConstants.DAYS_ACCOUNT_EXPIRES),
                    DatePasswordExpires     = DateTime.Now.AddDays(AccountConstants.DAYS_PASSWORD_EXPIRES),
                    RulesOfBehaviorAgreedTo = Input.RulesOfBehaviorAgreedTo
                };

                ///////////////////////////////////////////////////////////////////
                // Create User
                ///////////////////////////////////////////////////////////////////
                var result = await _userManager.CreateAsync(user, Input.Password);

                ///////////////////////////////////////////////////////////////////
                // Create User Role
                ///////////////////////////////////////////////////////////////////
                if (result.Succeeded)
                {
                    result = await _userManager.AddToRoleAsync(user, RoleConstants.STUDENT);
                }

                if (result.Succeeded)
                {
                    _logger.LogInformation("User created a new account with password.");

                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                    var callbackUrl = Url.EmailConfirmationLink(user.Id, code, Request.Scheme);
                    await _emailSender.SendEmailConfirmationAsync(Input.Email, callbackUrl);

                    //await _signInManager.SignInAsync(user, isPersistent: false);
                    //return LocalRedirect(Url.GetLocalUrl(returnUrl));

                    ///////////////////////////////////////////////////////////////////
                    // Log the 'USER_REGISTERED' event
                    ///////////////////////////////////////////////////////////////////
                    _eventLogService.LogEvent(EventTypeCodeConstants.USER_REGISTERED, user);

                    /////////////////////////////////////////////////////////////////////
                    // Redirect user to 'RegisterConfirmation' page
                    /////////////////////////////////////////////////////////////////////
                    return(RedirectToPage("./RegisterConfirmation"));
                }

                _logger.LogDebug("[logger] # of errors: " + result.Errors.Count());
                Console.WriteLine("[console] # of errors: " + result.Errors.Count());

                foreach (var error in result.Errors)
                {
                    _logger.LogDebug(error.Description);
                    Console.WriteLine(error.Description);

                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            // If we got this far, something failed, redisplay form
            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            AgencySelectList         = new SelectList(_dbContext.Agencies.OrderBy(a => a.DisplayOrder), "AgencyID", "AgencyName");
            SubAgencySelectList      = new SelectList(_dbContext.SubAgencies.OrderBy(sa => sa.DisplayOrder), "SubAgencyID", "SubAgencyName");
            ViewData["ReCaptchaKey"] = _configuration[MiscConstants.GOOGLE_RECAPTCHA_KEY];
            return(Page());
        }
Ejemplo n.º 6
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            //Console.WriteLine("[Login][OnPostAsync] - BEGIN");

            // Make sure that passed-in 'returnUrl' is of a local origin
            //this.ReturnUrl = PageModelUtil.EnsureLocalUrl(this, returnUrl);
            this.ReturnUrl = returnUrl;
            //Console.WriteLine("[Login][OnPostAsync] - returnUrl: " + returnUrl);

            ///////////////////////////////////////////////////////////////////
            // "I'm not a robot" check ...
            ///////////////////////////////////////////////////////////////////
            if (!PageModelUtil.ReCaptchaPassed
                (
                    Request.Form["g-recaptcha-response"],
                    _configuration[MiscConstants.GOOGLE_RECAPTCHA_SECRET],
                    _logger
                )
                )
            {
                //Console.WriteLine("[Login.OnPostAsync] reCAPTCHA FAILED");
                ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                // RECAPTCHA FAILED - redisplay form
                ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                ModelState.AddModelError(string.Empty, "You failed the CAPTCHA. Are you a robot?");
                ViewData["ReCaptchaKey"] = _configuration[MiscConstants.GOOGLE_RECAPTCHA_KEY];
                return(Page());
            }

            //Console.WriteLine("[Login.OnPostAsync] reCAPTCHA PASSED");
            //Console.WriteLine("[Login][OnPostAsync] - ModelState.IsValid: " + ModelState.IsValid);

            if (ModelState.IsValid)
            {
                // This doesn't count login failures towards account lockout
                // To enable password failures to trigger account lockout, set lockoutOnFailure: true
                // Console.WriteLine("Input.Email: " + Input.Email);
                // Console.WriteLine("Input.Password: "******"Input.RememberMe: " + Input.RememberMe);

                Input.RememberMe = false;
                var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure : true);

                //Console.WriteLine("[Login][OnPostAsync] - SignInResult.Succeeded........: " + result.Succeeded);
                //Console.WriteLine("[Login][OnPostAsync] - SignInResult.RequiresTwoFactor: " + result.RequiresTwoFactor);
                //Console.WriteLine("[Login][OnPostAsync] - SignInResult.IsLockedOut......: " + result.IsLockedOut);

                if (result.Succeeded)
                {
                    _logger.LogInformation("[Login][OnPostAsync] - SignInResult succeeded");

                    ApplicationUser user = await _signInManager.UserManager.FindByNameAsync(Input.Email);

                    ///////////////////////////////////////////////////////////////////
                    // Log the 'LOGIN' event
                    ///////////////////////////////////////////////////////////////////
                    _eventLogService.LogEvent(EventTypeCodeConstants.LOGIN, user);

                    //Console.WriteLine("[Login][OnPostAsync] - Password Expired: " + (user.DatePasswordExpires <= DateTime.Now) );
                    if (user.DatePasswordExpires <= DateTime.Now)
                    {
                        //Console.WriteLine("[Login][OnPostAsync] - Password expired, redirecting to './Manage/ChangePassword' page");
                        return(RedirectToPage("./Manage/ChangePassword"));
                    }

                    //Console.WriteLine("[Login][OnPostAsync] - ApplicationUser.TwoFactorEnabled: " + user.TwoFactorEnabled);
                    if (user.TwoFactorEnabled == false)
                    {
                        //Console.WriteLine("[Login][OnPostAsync] - Two-factor auth NOT enabled, redirecting to './Manage/EnableAuthenticator' page");
                        return(RedirectToPage("./Manage/EnableAuthenticator"));
                    }
                    //Console.WriteLine("[Login][OnPostAsync] - Two-factor auth IS enabled");

                    return(LocalRedirect(Url.GetLocalUrl(returnUrl)));
                }
                if (result.RequiresTwoFactor)
                {
                    //Console.WriteLine("[Login][OnPostAsync] - redirecting to './LoginWith2fa' page");
                    Input.RememberMe = false;
                    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.");
                    ViewData["ReCaptchaKey"] = _configuration[MiscConstants.GOOGLE_RECAPTCHA_KEY];
                    return(Page());
                }
            }

            ///////////////////////////////////////////////////////////////////////////////
            // If we got this far, something failed, redisplay form
            ///////////////////////////////////////////////////////////////////////////////
            ViewData["ReCaptchaKey"] = _configuration[MiscConstants.GOOGLE_RECAPTCHA_KEY];
            return(Page());
        }
Ejemplo n.º 7
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            if (!ModelState.IsValid)
            {
                Console.WriteLine("[" + DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss") + "][Register][OnPost] => Modelstate is INVALID - returning Page()");
                return(Page());
            }

            Console.WriteLine("[" + DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss") + "][Register][OnPost][" + Input.Email + "] => Modelstate is VALID - continuing ...");

            ReturnUrl = PageModelUtil.EnsureLocalUrl(this, returnUrl);

            ///////////////////////////////////////////////////////////////////
            // "I'm not a robot" check ...
            ///////////////////////////////////////////////////////////////////
            if (!_reCaptchaService.ReCaptchaPassed
                (
                    Request.Form["g-recaptcha-response"],     // that's how you get it from the Request object
                    _configuration[MiscConstants.GOOGLE_RECAPTCHA_SECRET]
                )
                )
            {
                Console.WriteLine("[" + DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss") + "][Register][OnPost][" + Input.Email + "] => reCAPTCHA FAILED - returning Page()");
                ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                // RECAPTCHA FAILED - redisplay form
                ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                ModelState.AddModelError(string.Empty, "You failed the CAPTCHA. Are you a robot?");
                AgencySelectList         = new SelectList(_dbContext.Agencies.OrderBy(a => a.DisplayOrder), "AgencyID", "AgencyName");
                SubAgencySelectList      = new SelectList(_dbContext.SubAgencies.OrderBy(sa => sa.DisplayOrder), "SubAgencyID", "SubAgencyName");
                ViewData["ReCaptchaKey"] = _configuration[MiscConstants.GOOGLE_RECAPTCHA_KEY];
                return(Page());
            }

            Console.WriteLine("[" + DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss") + "][Register][OnPost][" + Input.Email + "] => reCAPTCHA PASSED - continuing ...");

            if (ModelState.IsValid)
            {
                Console.WriteLine("[" + DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss") + "][Register][OnPost][" + Input.Email + "] => Creating ApplicationUser ...");

                var user = new ApplicationUser
                {
                    UserName                = Input.Email,
                    Email                   = Input.Email,
                    FirstName               = Input.FirstName,
                    MiddleName              = Input.MiddleName,
                    LastName                = Input.LastName,
                    JobTitle                = Input.JobTitle,
                    AgencyID                = Input.AgencyID,
                    SubAgencyID             = Input.SubAgencyID,
                    DateRegistered          = DateTime.Now,
                    DateAccountExpires      = DateTime.Now.AddDays(AccountConstants.DAYS_ACCOUNT_EXPIRES),
                    DatePasswordExpires     = DateTime.Now.AddDays(AccountConstants.DAYS_PASSWORD_EXPIRES),
                    RulesOfBehaviorAgreedTo = Input.RulesOfBehaviorAgreedTo
                };

                ///////////////////////////////////////////////////////////////////
                // Create User
                ///////////////////////////////////////////////////////////////////
                Console.WriteLine("[" + DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss") + "][Register][OnPost][" + user.Email + "] => Calling _userManager.CreateAsync() ...");
                var result = await _userManager.CreateAsync(user, Input.Password);

                ///////////////////////////////////////////////////////////////////
                // Create User Role
                ///////////////////////////////////////////////////////////////////
                if (result.Succeeded)
                {
                    Console.WriteLine("[" + DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss") + "][Register][OnPost][" + user.Email + "] => Calling _userManager.AddToRoleAsync() ...");
                    result = await _userManager.AddToRoleAsync(user, RoleConstants.STUDENT);
                }

                if (result.Succeeded)
                {
                    Console.WriteLine("[" + DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss") + "][Register][OnPost][" + user.Email + "] => User created with role of STUDENT ...");

                    ////////////////////////////////////////////////////////////////////////
                    // OLD WAY OF GENERATING EMAIL VERIFICATION TOKENS
                    ////////////////////////////////////////////////////////////////////////
                    // var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
                    ////////////////////////////////////////////////////////////////////////

                    ////////////////////////////////////////////////////////////////////////
                    // NEW WAY OF GENERATING EMAIL VERIFICATION TOKENS
                    ////////////////////////////////////////////////////////////////////////
                    string emailToken = Guid.NewGuid().ToString();
                    _emailTokenRepo.Create(user.Id, emailToken);
                    ////////////////////////////////////////////////////////////////////////

                    Console.WriteLine("[" + DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss") + "][Register][OnPost][" + user.Email + "] => BEGIN: Email Confirmation Token:");
                    Console.WriteLine("'" + emailToken + "'");
                    Console.WriteLine("[" + DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss") + "][Register][OnPost][" + user.Email + "] => END: Email Confirmation Token");

                    Console.WriteLine("[" + DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss") + "][Register][OnPost][" + user.Email + "] => HttpRequest.Scheme: '" + Request.Scheme + "'");

                    //var callbackUrl = Url.EmailConfirmationLink(user.Id, code, Request.Scheme);
                    var callbackUrl = Url.EmailConfirmationLink(user.Id, emailToken, "https");

                    Console.WriteLine("[" + DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss") + "][Register][OnPost][" + user.Email + "] => BEGIN: EmailConfirmationLink:");
                    Console.WriteLine(callbackUrl);
                    Console.WriteLine("[" + DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss") + "][Register][OnPost][" + user.Email + "] => END: EmailConfirmationLink");

                    Console.WriteLine("[" + DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss") + "][Register][OnPost][" + user.Email + "] => Sedning email confirmation with link ...");
                    await _emailSender.SendEmailConfirmationAsync(Input.Email, callbackUrl);

                    //await _signInManager.SignInAsync(user, isPersistent: false);
                    //return LocalRedirect(Url.GetLocalUrl(returnUrl));

                    ///////////////////////////////////////////////////////////////////
                    // Log the 'USER_REGISTERED' event
                    ///////////////////////////////////////////////////////////////////
                    _eventLogService.LogEvent(EventTypeCodeConstants.USER_REGISTERED, user);

                    /////////////////////////////////////////////////////////////////////
                    // Redirect user to 'RegisterConfirmation' page
                    /////////////////////////////////////////////////////////////////////
                    return(RedirectToPage("./RegisterConfirmation"));
                }

                _logger.LogDebug("[logger] # of errors: " + result.Errors.Count());
                Console.WriteLine("[console] # of errors: " + result.Errors.Count());

                foreach (var error in result.Errors)
                {
                    _logger.LogDebug(error.Description);
                    Console.WriteLine(error.Description);

                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            // If we got this far, something failed, redisplay form
            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            AgencySelectList         = new SelectList(_dbContext.Agencies.OrderBy(a => a.DisplayOrder), "AgencyID", "AgencyName");
            SubAgencySelectList      = new SelectList(_dbContext.SubAgencies.OrderBy(sa => sa.DisplayOrder), "SubAgencyID", "SubAgencyName");
            ViewData["ReCaptchaKey"] = _configuration[MiscConstants.GOOGLE_RECAPTCHA_KEY];
            return(Page());
        }