Esempio n. 1
0
        public async Task <LoginSuccessModel> Handle(LoginRequest request, CancellationToken cancellationToken)
        {
            var accounts = await _context.Users.AsNoTracking()
                           .FirstOrDefaultAsync(x => x.Email == request.Email && x.RoleId == 1);

            bool checkPassword = false;

            if (accounts != null)
            {
                LoginSuccessModel resultReturn = new LoginSuccessModel();
                if (accounts.IsActive == false)
                {
                    resultReturn.IdError = 1;
                    return(resultReturn);
                }
                checkPassword = BCrypt.Net.BCrypt.Verify(request.Password, accounts.Password);
                if (checkPassword)
                {
                    string role     = _context.Roles.AsNoTracking().FirstOrDefault(r => r.Id == accounts.RoleId).Role;
                    string fullname = accounts.FirstName + " " + accounts.LastName;
                    resultReturn.Id       = accounts.Id;
                    resultReturn.FullName = fullname;
                    resultReturn.Role     = role;
                    resultReturn.Token    = _helper.GenerateJwtToken(request.Email, accounts, role);
                    return(resultReturn);
                }
            }
            return(null);
        }
Esempio n. 2
0
        public async Task <IActionResult> Login([FromHeader(Name = "User-Agent")] string userAgent,
                                                [FromHeader(Name = "Authorization")] string authorization,
                                                [FromServices] IJwtSigningEncodingKey signingEncodingKey,
                                                [FromServices] IJwtEncryptingEncodingKey encryptingEncodingKey)
        {
            if (string.IsNullOrEmpty(userAgent) ||
                string.IsNullOrWhiteSpace(userAgent))
            {
                return(Json("Incorrect user-agent info"));
            }
            if (string.IsNullOrEmpty(authorization) ||
                string.IsNullOrWhiteSpace(authorization))
            {
                return(Json("Incorrect user data"));
            }

            // Decoding from Base64 Authorization Basic <username:password>
            var clearAuth           = authorization.Replace("Basic ", string.Empty);
            var base64EncodedBytes  = Convert.FromBase64String(clearAuth);
            var base64EncodedString = Encoding.UTF8.GetString(base64EncodedBytes);
            var credentials         = base64EncodedString.Split(":");

            if (credentials is null ||
                credentials?.Length != 2)
            {
                return(Json("Incorrect data format for authorization"));
            }

            // User verification
            var existUser = await _userRepository.Query()
                            .Where(s => s.Login == credentials[0])
                            .SingleOrDefaultAsync();

            if (existUser is null)
            {
                return(Json("Authorization error"));
            }
            if (!credentials[1].Equals(existUser?.Password))
            {
                return(Json("Incorrect password"));
            }

            // Generate Jwe token
            var jwtToken     = _accountHelper.GenerateJwtToken(existUser, signingEncodingKey, encryptingEncodingKey);
            var refreshToken = _accountHelper.GenerateRefreshToken();

            if (refreshToken is null)
            {
                return(Json("Refresh token isn't formed"));
            }

            var dtUtcNow  = DateTime.UtcNow;
            var userLogin = new UserLoginModel
            {
                RefreshToken  = refreshToken,
                CreateDateUTC = dtUtcNow,
                ExpireDateUTC = dtUtcNow.AddDays(2),
                UserAgent     = userAgent
            };
            var existUserLogin = await _userLoginRepository.Query()
                                 .Where(s => s.UserId == existUser.Id &&
                                        s.UserAgent == userLogin.UserAgent)
                                 .SingleOrDefaultAsync();

            // Delete existing login
            if (existUserLogin != null)
            {
                await _userLoginRepository.DeleteAsync(existUserLogin);
            }

            existUser.UsersLogins.Add(userLogin);
            await _userRepository.UpdateAsync(existUser);

            var response = new { jwtToken, refreshToken };

            return(Json(response));
        }