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

            ///////////////////////////////////////////////////////////////////
            // "I'm not a robot" check ...
            ///////////////////////////////////////////////////////////////////
            if (!_reCaptchaService.ReCaptchaPassed
                (
                    Request.Form["g-recaptcha-response"],
                    _configuration[MiscConstants.GOOGLE_RECAPTCHA_SECRET]
                )
                )
            {
                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());
        }
Esempio n. 2
0
        public async Task <IActionResult> OnPostAsync()
        {
            Console.WriteLine("[ForgotPassword.OnPostAsync]: BEGIN");

            ///////////////////////////////////////////////////////////////////
            // "I'm not a robot" check ...
            ///////////////////////////////////////////////////////////////////
            if (!_reCaptchaService.ReCaptchaPassed
                (
                    Request.Form["g-recaptcha-response"],
                    _configuration[MiscConstants.GOOGLE_RECAPTCHA_SECRET]
                )
                )
            {
                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());
        }
Esempio n. 3
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 ...
            ///////////////////////////////////////////////////////////////////

            // Console.WriteLine("\n[Login][OnPost][g-recaptcha-response]=>\n");
            // Console.WriteLine(Request.Form["g-recaptcha-response"]);
            // Console.WriteLine("\n<=[Login][OnPost][g-recaptcha-response]");

            // _logger.LogInformation("\n[Login][OnPost][g-recaptcha-response]=>\n");
            // _logger.LogInformation(Request.Form["g-recaptcha-response"]);
            // _logger.LogInformation("\n<=[Login][OnPost][g-recaptcha-response]");

            // Console.WriteLine("\n[Login][OnPost][GOOGLE_RECAPTCHA_SECRET]=>\n");
            // Console.WriteLine(_configuration[MiscConstants.GOOGLE_RECAPTCHA_SECRET]);
            // Console.WriteLine("\n<=[Login][OnPost][GOOGLE_RECAPTCHA_SECRET]");

            // _logger.LogInformation("\n[Login][OnPost][GOOGLE_RECAPTCHA_SECRET]=>\n");
            // _logger.LogInformation(_configuration[MiscConstants.GOOGLE_RECAPTCHA_SECRET]);
            // _logger.LogInformation("\n<=[Login][OnPost][GOOGLE_RECAPTCHA_SECRET]");


            if (!_reCaptchaService.ReCaptchaPassed
                (
                    Request.Form["g-recaptcha-response"],
                    _configuration[MiscConstants.GOOGLE_RECAPTCHA_SECRET]
                )
                )
            {
                //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());
        }
Esempio n. 4
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());
        }