Пример #1
0
        public async Task <IActionResult> Login([FromBody] LoginAccountDto model)
        {
            var result = await _accountService.LoginAccountAsync(model);

            if (!result.Success)
            {
                return(BadRequest(result.Message));
            }

            return(Ok(result.Token));
        }
Пример #2
0
        public async Task <IActionResult> Login(LoginAccountDto model)
        {
            var user = await _userManager.FindByNameAsync(model.UserName);

            if (user == null)
            {
                throw new AppException("Wrong user or password!");
            }

            var emailConfirmation = await _userManager.IsEmailConfirmedAsync(user);

            if (emailConfirmation == false)
            {
                throw new AppException("Precisas de confirmar o teu registo para continuar. Por favor confirma o teu email!");
            }


            var result = await _signInManager.PasswordSignInAsync(model.UserName, model.Password, isPersistent : false, lockoutOnFailure : true);

            //if (!result.Succeeded)
            //  throw new AppException("Wrong user or password!");

            await UserIsLockoutAsync(user, result);

            await _userManager.ResetAccessFailedCountAsync(user);


            var token = await GetJwtSecurityToken(user);

            if (token == null)
            {
                throw new AppException("Error generating Token!");
            }

            var refreshToken = new RefreshTokens
            {
                Username = user.UserName,
                Token    = GenerateRefreshToken(user).Token,
                Revoked  = false,
                IpAdress = _httpContext.HttpContext.Connection.RemoteIpAddress.ToString(),
            };

            _context.RefreshTokens.Add(refreshToken);
            _context.SaveChanges();

            return(Ok(new
            {
                message = "Login Successful!",
                access_token = new JwtSecurityTokenHandler().WriteToken(token),
                expiration = token.ValidTo,
                refresh_token = refreshToken.Token,
            }));
        }
Пример #3
0
        public async Task <IActionResult> Login(LoginAccountDto loginDtoViewModel)
        {
            if (!ModelState.IsValid)
            {
                return(View(loginDtoViewModel));
            }
            var checkUser = await _userManager.FindByEmailAsync(loginDtoViewModel.UserName);

            if (checkUser == null)
            {
                checkUser = await _userManager.FindByNameAsync(loginDtoViewModel.UserName);

                if (checkUser == null)
                {
                    ViewBag.LoginError = "Sai tên đăng nhập hoặc mật khẩu";
                    return(View(loginDtoViewModel));
                }
            }
            var checkPassword = await _userManager.CheckPasswordAsync(checkUser, loginDtoViewModel.Password);

            if (!checkPassword)
            {
                ViewBag.LoginError = "Sai tên đăng nhập hoặc mật khẩu";
                return(View(loginDtoViewModel));
            }

            if (!checkUser.EmailConfirmed)
            {
                ViewBag.LoginError = "Tài khoản chưa xác nhận mail";
                return(View(loginDtoViewModel));
            }
            await _signInManager.SignOutAsync();

            var signinResult = await _signInManager.PasswordSignInAsync(checkUser, loginDtoViewModel.Password,
                                                                        loginDtoViewModel.RememberLogin, true);

            if (signinResult.IsLockedOut)
            {
                ViewBag.LoginError = "Tài khoản bị khóa, hãy liên hệ với quản trị viên để được hỗ trợ";
                return(View(loginDtoViewModel));
            }

            if (signinResult.RequiresTwoFactor)
            {
                return(RedirectToAction(nameof(LoginTwoStep),
                                        new
                {
                    Email = checkUser.EmailConfirmed, loginDtoViewModel.RememberLogin, loginDtoViewModel.ReturnUrl
                }));
            }
            return(Redirect(loginDtoViewModel.ReturnUrl));
        }
Пример #4
0
        public async Task <IActionResult> Login([FromBody] LoginAccountDto model)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(BadRequest(ModelState.Values.SelectMany(v => v.Errors).Select(modelError => modelError.ErrorMessage).ToList()));
                }

                return(await _authService.Login(model));
            }
            catch (AppException ex)
            {
                return(BadRequest(new { message = ex.Message }));
            }
        }
Пример #5
0
        public LogOnDto Login([FromBody] LoginAccountDto model)
        {
            var result = _signInManager.PasswordSignInAsync(model.Email, model.Password, false, false).Result;

            if (!result.Succeeded)
            {
                throw new ApplicationException(ExceptionMessages.LoginFailed);
            }

            var    appUser = _userManager.Users.SingleOrDefault(user => user.Email == model.Email);
            string token   = GenerateJwtToken(model.Email, appUser);
            int    userId  = appUser.Id;
            string logo    = string.Empty;

            using (var dbContext = new ApplicationDbContext())
            {
                if (!_userManager.IsInRoleAsync(appUser, Roles.Client).Result)
                {
                    // Es una clinica o un empleado de la clinica
                    if (_userManager.IsInRoleAsync(appUser, Roles.Employee).Result)
                    {
                        var employee = dbContext.Clinic_Employees.FirstOrDefault(e => e.UserId == appUser.Id);
                        userId = employee.OwnerUserId;
                    }

                    var clinic = dbContext.Clinics.FirstOrDefault(c => c.UserId == userId);
                    logo = clinic.Logo;
                }
                if (_userManager.IsInRoleAsync(appUser, Roles.Client).Result)
                {
                    var client = dbContext.Clinic_Clients.FirstOrDefault(c => c.UserId == userId);
                    logo = client.Logo;
                }
            }

            ValidTokens.Add($"{JwtBearerDefaults.AuthenticationScheme} {token}", userId);

            return(new LogOnDto
            {
                Token = token,
                Logo = logo
            });
        }
Пример #6
0
        public async Task <AccountResponse> LoginAccountAsync(LoginAccountDto model)
        {
            Dictionary <string, string[]> errors = new Dictionary <string, string[]>();

            var result = await _signInManager.PasswordSignInAsync(model.UserName, model.Password, false, false);

            if (!result.Succeeded)
            {
                errors.Add("Konto", new[] { "Nie udalo sie zalogowac" });
                return(new AccountResponse(errors));
            }

            UserAccount appUser  = _userManager.Users.SingleOrDefault(r => r.UserName == model.UserName);
            JwtTokenDto response = new JwtTokenDto
            {
                Token = GenerateJwtToken(model.UserName, appUser)
            };

            return(new AccountResponse(response));
        }
Пример #7
0
        public async Task <TokenDto> LoginAsync(LoginAccountDto accountDto, CancellationToken ct = default)
        {
            Logger.LogInformation("Login to account {@Account}", accountDto);

            AccountBase accountBase = await UnitOfWork.AccountRepository.GetUserAsync(accountDto.Email, ct);

            if (accountBase == null)
            {
                Logger.LogInformation("Account with email {Email} doesn't exist", accountDto.Email);
                throw new AccountNotFoundException();
            }

            if (!accountBase.IsPasswordEqual(accountDto.Password))
            {
                Logger.LogInformation("Password for email {Email} is wrong", accountDto.Email);
                throw new WrongPasswordException();
            }

            string token = TokenGeneratorHelper.GenerateToken(_configuration, GenerateClaims(accountBase));

            return(new TokenDto(token, _configuration.ExpiresInDay));
        }
Пример #8
0
        public async Task <ApiResult <WebToken> > AppUserSingIn(LoginAccountDto dto)
        {
            var result = await passportService.SingInAppUserAsync(dto.UserName, dto.Password);

            return(new ApiResult <WebToken>(result));
        }
Пример #9
0
        private async Task <LoginAccountDto> BuildLoginViewModelAsync(string returnUrl)
        {
            var context = await _identityServerInteractionService.GetAuthorizationContextAsync(returnUrl);

            if (context?.IdP != null && await _schemeProvider.GetSchemeAsync(context.IdP) != null)
            {
                var local = context.IdP == IdentityServer4.IdentityServerConstants.LocalIdentityProvider;

                // this is meant to short circuit the UI and only trigger the one external IdP
                var vm = new LoginAccountDto()
                {
                    EnableLocalLogin = local,
                    ReturnUrl        = returnUrl,
                    UserName         = context?.LoginHint,
                };

                if (!local)
                {
                    vm.ExternalProviders = new[] { new ExternalProvider {
                                                       AuthenticationScheme = context.IdP
                                                   } };
                }

                return(vm);
            }
            var schemes = await _schemeProvider.GetAllSchemesAsync();

            var providers = schemes
                            .Where(x => x.DisplayName != null)
                            .Select(x => new ExternalProvider
            {
                DisplayName          = x.DisplayName ?? x.Name,
                AuthenticationScheme = x.Name
            }).ToList();

            var allowLocal = true;

            if (context?.ClientId != null)
            {
                var client = await _clientStore.FindEnabledClientByIdAsync(context.ClientId);

                if (client != null)
                {
                    allowLocal = client.EnableLocalLogin;

                    if (client.IdentityProviderRestrictions != null && client.IdentityProviderRestrictions.Any())
                    {
                        providers = providers.Where(provider => client.IdentityProviderRestrictions.Contains(provider.AuthenticationScheme)).ToList();
                    }
                }
            }

            return(new LoginAccountDto()
            {
                RememberLogin = true,
                EnableLocalLogin = allowLocal && true,
                ReturnUrl = returnUrl,
                UserName = context?.LoginHint,
                ExternalProviders = providers.ToArray()
            });
        }
        protected override async Task <TokenDto> ExecuteAsync(LoginToAccountCommand request, CancellationToken ct)
        {
            LoginAccountDto loginAccountDto = _mapper.Map <LoginAccountDto>(request);

            return(await _accountService.LoginAsync(loginAccountDto, ct));
        }