Exemplo n.º 1
0
        public async Task <SignInAccountModel> SignInAsync(SignInAccountAuthorizationViewModel model)
        {
            ApplicationUser identityUser = _userManager.Users
                                           .SingleOrDefault(x => x.NormalizedEmail == model.Email.ToUpper() && !x.IsDeleted);

            Require.Objects.NotNull <NotFoundException>(identityUser, $"User not found");

            var isConfirm = await _userManager.IsEmailConfirmedAsync(identityUser);

            Require.Booleans.IsTrue <BadRequestException>(isConfirm, "Email is not confirmed.");

            var accessFailedCount = identityUser.AccessFailedCount;
            var signInResult      = await _signInManager.PasswordSignInAsync(identityUser, model.Password, false, true);

            if (signInResult == SignInResult.Failed)
            {
                throw new BadRequestException("Invalid login attempt.");
            }
            if (signInResult == SignInResult.LockedOut)
            {
                if (accessFailedCount > 0)
                {
                    var token = await CreateSecurityTokenForUnlockUser(identityUser.Id);
                    await SendNotificationAboutLockAccount(identityUser, token);
                }

                throw new BadRequestException(@"Invalid login attempt.
                                Your account has been blocked for 10 minutes.");
            }
            var(accessToken, refreshToken, refreshTokenExpires) = await _jwtFactory.GenerateAuthorizationToken(identityUser.Id, model.RememberMe);

            //TODO: CreateRefreshTokenIfNotExist - save refresh token in database

            var userData = _mapper.Map <UserAccountModelItem>(identityUser);

            userData.UserRoles.AddRange(await _userManager.GetRolesAsync(identityUser));

            var authData = new SignInAccountModel
            {
                Token = accessToken,
                //RefreshToken = refreshToken,
                ExpireDate = refreshTokenExpires,
                User       = userData
            };

            return(authData);
        }