Пример #1
0
        public async Task <Result <TokenDto> > Handle(Command.LoginCommand.LoginCommand request, CancellationToken cancellationToken)
        {
            var user = await _userRepository.GetAsync(x => x.Mobile == request.Mobile && x.IsDelete == false, cancellationToken);

            if (user is null)
            {
                return(Result <TokenDto> .Failed(new BadRequestObjectResult(new ApiMessage(ResponseMessage.InvalidUserNameOrPassword))));
            }

            if (PasswordManagement.CheckPassword(request.Password, user.Password) == false)
            {
                return(Result <TokenDto> .Failed(new BadRequestObjectResult(new ApiMessage(ResponseMessage.InvalidUserNameOrPassword))));
            }

            if (user.IsMobileConfirm == false)
            {
                return(Result <TokenDto> .Failed(new BadRequestObjectResult(new ApiMessage(ResponseMessage.AccountDeactivate))));
            }


            var userToken = await _userTokenRepository.GetAsync(x =>
                                                                x.IsExpired == false && x.ExpiredDate >= DateTime.Now && x.UserId == user.Id, cancellationToken);

            //if user already have valid token in database
            if (userToken != null)
            {
                return(Result <TokenDto> .SuccessFul(new TokenDto
                {
                    AccessToken = userToken.Token,
                    RoleName = user.Roles.FirstOrDefault()?.Name
                }));
            }

            var result = await _tokenGenerator.Generate(user, cancellationToken);

            return(Result <TokenDto> .SuccessFul(new TokenDto
            {
                AccessToken = result.Data.AccessToken,
                RoleName = result.Data.RoleName
            }));
        }