/// <summary>
    /// Login for incoming user. Returns a token if login informations are valid or the user is not lockedout. Otherwise returns the error list.
    /// </summary>
    /// <param name="loginDTO"></param>
    /// <param name="userValidation"></param>
    /// <param name="tokenExpiredDate"></param>
    /// <returns></returns>
    public virtual async Task <TLoginResultDTO> LoginAsync(ILoginDTO loginDTO,
                                                           IIdentityOperations <TUserManager, TDbContext, TLocalizer, TUser, TRole, TKey, TLoginResultDTO> .UserValidation userValidation,
                                                           DateTime tokenExpiredDate)
    {
        TUser user = new();

        var(tUser, loginResult) = await userValidation.Invoke(loginDTO, user).ConfigureAwait(false);

        user = tUser;

        if (loginResult.ErrorMessages.Count > 0)
        {
            return(loginResult);
        }

        SignInResult signInResult = await _signInManager.PasswordSignInAsync(user, loginDTO.Password, loginDTO.Persistent, lockoutOnFailure : true).ConfigureAwait(false);

        //Kimlik doğrulama başarılı ise
        if (signInResult.Succeeded)
        {
            //Token username,IsPersonnel ve rollere göre üretilir
            loginResult.Token = await GenerateTokenWithRoleAsync(user : user, tokenExpiredDate).ConfigureAwait(false) as MilvaToken;

            if (_useWhiteList)
            {
                //Bu kullanici daha once token almissa o token silinip yerine yeni alinmis token yazilir.
                if (SignedInUsers.SignedInUserTokens.ContainsKey(user.UserName))
                {
                    SignedInUsers.SignedInUserTokens.Remove(user.UserName);
                }

                SignedInUsers.SignedInUserTokens.Add(user.UserName, loginResult.Token.AccessToken);
            }

            return(loginResult);
        }

        #region Error Handling

        //Eğer ki başarısız bir account girişi söz konusu ise AccessFailedCount kolonundaki değer +1 arttırılacaktır.
        await _userManager.AccessFailedAsync(user).ConfigureAwait(false);

        if (signInResult.RequiresTwoFactor)
        {
            loginResult.ErrorMessages.Add(new IdentityError {
                Code = LocalizerKeys.RequiresTwoFactor, Description = _localizer[LocalizerKeys.RequiresTwoFactor]
            });
        }

        if (signInResult.IsNotAllowed)
        {
            loginResult.ErrorMessages.Add(new IdentityError {
                Code = LocalizerKeys.NotAllowed, Description = _localizer[LocalizerKeys.NotAllowed]
            });
        }

        #endregion

        return(loginResult);
    }
        public async Task <Response <ILoginResponseDTO> > Token(ILoginDTO loginObj)
        {
            var response = new Response <ILoginResponseDTO>();

            var user = await GetIdentity(loginObj.Login, loginObj.Password);

            if (user == null)
            {
                response.Error = new Error(404, "The user was not found or you entered incorrect data.");
                return(response);
            }

            User userDB = await _db.Users.Where(u => u.Email == loginObj.Login).FirstOrDefaultAsync();

            var roleObj = await _db.UserRoles.Where(r => r.UserId == userDB.Id).FirstOrDefaultAsync();

            var objWithRoleName = await _db.Roles.Where(r => r.Id == roleObj.RoleId).FirstOrDefaultAsync();

            var now = DateTime.UtcNow;

            var expires = now.Add(TimeSpan.FromMinutes(AuthOptions.LIFETIME));

            var jwt = new JwtSecurityToken(
                issuer: AuthOptions.ISSUER,
                audience: AuthOptions.AUDIENCE,
                notBefore: now,
                claims: user.Claims,
                expires: expires,
                signingCredentials: new SigningCredentials(AuthOptions.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256));
            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

            var loginResponse = new LoginResponseDTO(encodedJwt, expires.ToString(), objWithRoleName.Name);

            response.Data = loginResponse;

            return(response);
        }
Beispiel #3
0
        public async Task <object> LoginAsync(ILoginDTO dto)
        {
            var user = await _userManager.FindByNameAsync(dto.UserName);

            if (user == null)
            {
                throw new UserNotFoundException();
            }

            var result = await _signInManager.CheckPasswordSignInAsync(user, dto.Password, false);

            if (!result.Succeeded)
            {
                throw new IncorrectPasswordException();
            }

            var token = _tokenService.GenerateTokenAsync(dto.UserName);

            return(new
            {
                dto.UserName,
                AccessToken = await token
            });
        }
Beispiel #4
0
 private async Task <(AppUser educationUser, LoginResultDTO loginResult)> ValidateUserAsync(ILoginDTO loginDTO, AppUser user, bool isUserType) => await base.ValidateUserAsync(loginDTO, user).ConfigureAwait(false);
    /// <summary>
    /// Validating user to login.
    /// </summary>
    /// <param name="loginDTO"></param>
    /// <param name="user"></param>
    /// <returns></returns>
    public virtual async Task <(TUser tUser, TLoginResultDTO loginResult)> ValidateUserAsync(ILoginDTO loginDTO, TUser user)
    {
        IdentityError GetLockedError(DateTime lockoutEnd)
        {
            var remainingLockoutEnd = lockoutEnd - DateTime.UtcNow;

            var reminingLockoutEndString = remainingLockoutEnd.Hours > 0
                                            ? _localizer[LocalizerKeys.Hours, remainingLockoutEnd.Hours]
                                            : remainingLockoutEnd.Minutes > 0
                                                 ? _localizer[LocalizerKeys.Minutes, remainingLockoutEnd.Minutes]
                                                 : _localizer[LocalizerKeys.Seconds, remainingLockoutEnd.Seconds];

            return(new IdentityError {
                Code = LocalizerKeys.Locked, Description = _localizer[LocalizerKeys.Locked, reminingLockoutEndString]
            });
        }

        int accessFailedCountLimit = 5;

        user = new TUser();

        var loginResult = new TLoginResultDTO {
            ErrorMessages = new List <IdentityError>()
        };

        if (loginDTO.UserName == null && loginDTO.Email == null)
        {
            throw new MilvaUserFriendlyException(LocalizerKeys.PleaseEnterEmailOrUsername);
        }

        //Kullanici adi veya email ile kullanici dogrulama
        #region User Validation

        var userNotFound = true;

        if (loginDTO.UserName != null)
        {
            user = _userManager.FindByNameAsync(userName: loginDTO.UserName).Result;

            userNotFound = user == null;

            if (userNotFound)
            {
                loginResult.ErrorMessages.Add(new IdentityError {
                    Code = LocalizerKeys.InvalidUserName, Description = _localizer[LocalizerKeys.InvalidUserName]
                });
                return(user, loginResult);
            }
        }

        if (loginDTO.Email != null && userNotFound)
        {
            user = _userManager.FindByEmailAsync(email: loginDTO.Email).Result;

            userNotFound = user == null;

            if (userNotFound)
            {
                loginResult.ErrorMessages.Add(new IdentityError {
                    Code = LocalizerKeys.InvalidEmail, Description = _localizer[LocalizerKeys.InvalidEmail]
                });
                return(user, loginResult);
            }
        }

        if (userNotFound)
        {
            loginResult.ErrorMessages.Add(new IdentityError {
                Code = LocalizerKeys.InvalidLogin, Description = _localizer[LocalizerKeys.InvalidLogin]
            });

            return(user, loginResult);
        }

        var userLocked = _userManager.IsLockedOutAsync(user).Result;

        if (userLocked && DateTime.UtcNow > user.LockoutEnd.Value.DateTime)
        {
            _contextRepository.InitializeUpdating <TUser, TKey>(user);

            //Locklanmış kullanıcının süresini sıfırlıyoruz
            await _userManager.SetLockoutEndDateAsync(user, null).ConfigureAwait(false);

            await _userManager.ResetAccessFailedCountAsync(user).ConfigureAwait(false);

            userLocked = false;
        }

        if (userLocked)
        {
            loginResult.ErrorMessages.Add(GetLockedError(user.LockoutEnd.Value.DateTime));
            return(user, loginResult);
        }

        var passIsTrue = _userManager.CheckPasswordAsync(user, loginDTO.Password).Result;
        //personnel olarak giris yapmaya calisan gercekten personel mi? degilse basarili giris yapmissa da kabul etme ve hassas mesaj vermesini engellemek icin personel degil diye ayarla

        if (!passIsTrue)
        {
            await _userManager.AccessFailedAsync(user).ConfigureAwait(false);

            if (_userManager.IsLockedOutAsync(user).Result)
            {
                loginResult.ErrorMessages.Add(GetLockedError(user.LockoutEnd.Value.DateTime));
                return(user, loginResult);
            }

            var lockWarningMessage = _localizer[LocalizerKeys.LockWarning, accessFailedCountLimit - user.AccessFailedCount];

            loginResult.ErrorMessages.Add(new IdentityError {
                Code = LocalizerKeys.InvalidLogin, Description = lockWarningMessage
            });

            return(user, loginResult);
        }

        return(user, loginResult);

        #endregion
    }