예제 #1
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl ??= Url.Content("~/");

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

            if (ModelState.IsValid)
            {
                // This doesn't count login failures towards account lockout
                // To enable password failures to trigger account lockout, set lockoutOnFailure: true

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

                if (user != null && await _userManager.CheckPasswordAsync(user, Input.Password))
                {
                    GenericResult <string> resultJwt = await _jwtService.GetJwt(Input.Email, Input.Password);

                    if (resultJwt.Success)
                    {
                        // Si el usuario tiene el claim de JWT lo elimino y agrego uno nuevo
                        var claimJwt = _context.UserClaims.
                                       Where(x => x.ClaimType == "JWT" && x.UserId == user.Id).FirstOrDefault();

                        if (claimJwt != null)
                        {
                            _context.UserClaims.Remove(claimJwt);
                            await _context.SaveChangesAsync();
                        }
                        await _userManager.AddClaimAsync(user, new Claim("JWT", resultJwt.value));
                    }
                }


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

                if (result.Succeeded)
                {
                    _logger.Information("{User} logged in.", user.Email);
                    return(LocalRedirect(returnUrl));
                }
                if (result.RequiresTwoFactor)
                {
                    return(RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = Input.RememberMe }));
                }
                if (result.IsLockedOut)
                {
                    _logger.Warning("{User} account locked out.", user.Email);
                    return(RedirectToPage("./Lockout"));
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "Usuario o contraseña incorrectos.");
                    return(Page());
                }
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl ??= Url.Content("~/");
            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {
                    UserName = Input.Email, Email = Input.Email, Name = Input.Name, Surname = Input.Surname
                };
                var result = await _userManager.CreateAsync(user, Input.Password);

                if (result.Succeeded)
                {
                    if (_userManager.Options.SignIn.RequireConfirmedAccount)
                    {
                        var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                        code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                        var callbackUrl = Url.Page(
                            "/Account/ConfirmEmail",
                            pageHandler: null,
                            values: new { area = "Identity", userId = user.Id, code = code, returnUrl = returnUrl },
                            protocol: Request.Scheme);

                        await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                                                          $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                        return(RedirectToPage("RegisterConfirmation", new { email = Input.Email, returnUrl = returnUrl }));
                    }
                    else
                    {
                        var RoleResult = await _roleManager.FindByNameAsync(ApplicationUserService.ROLE_ADMIN);

                        if (RoleResult == null)
                        {
                            // Create ROLE_ADMIN Role
                            await _roleManager.CreateAsync(new IdentityRole(ApplicationUserService.ROLE_ADMIN));
                        }
                        RoleResult = await _roleManager.FindByNameAsync(ApplicationUserService.ROLE_USER);

                        if (RoleResult == null)
                        {
                            // Create ROLE_USER Role
                            await _roleManager.CreateAsync(new IdentityRole(ApplicationUserService.ROLE_USER));
                        }

                        if (_userManager.Users.Count() == 1)
                        {
                            //si es el primer usuario registrado le asigno el rol admin
                            await _userManager.AddToRoleAsync(user, ApplicationUserService.ROLE_ADMIN);

                            _logger.Information("User: {User} created a new account with {Role} role.", user, ApplicationUserService.ROLE_ADMIN);
                        }
                        else
                        {
                            await _userManager.AddToRoleAsync(user, ApplicationUserService.ROLE_USER);

                            _logger.Information("User: {User} created a new account with {Role} role.", user, ApplicationUserService.ROLE_USER);
                        }



                        GenericResult <string> resultJwt = await _jwtService.GetJwt(Input.Email, Input.Password);

                        if (resultJwt.Success)
                        {
                            await _userManager.AddClaimAsync(user, new Claim("JWT", resultJwt.value));
                        }
                        await _signInManager.SignInAsync(user, isPersistent : false);

                        return(LocalRedirect(returnUrl));
                    }
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }