Beispiel #1
0
        public async Task <UserCreatedResponse> Handle(CreateUserCommand request, CancellationToken cancellationToken)
        {
            var isUsernameTaken = (await _boringBankDbContext.Users
                                   .AsNoTracking()
                                   .FirstOrDefaultAsync(x => x.Username.ToLower() == request.Username.ToLower())) != null;

            if (isUsernameTaken)
            {
                throw new Exception($"User already exists with username {request.Username}");
            }

            var user = new User
            {
                Username    = request.Username,
                BankAccount = new BankAccount()
            };

            _boringBankUserService.SetUserPassword(user, request.Password);

            _boringBankDbContext.Users.Add(user);

            await _boringBankDbContext.SaveChangesAsync(cancellationToken);

            var token = _boringBankTokenService.CreateTokenFromUser(user);

            return(new UserCreatedResponse
            {
                AccessToken = token,
                UserId = user.UserId,
                BankAccountId = user.BankAccount.BankAccountId
            });
        }
        public Task <UserAuthenticationResponse> Handle(AuthenticateUserCommand request, CancellationToken cancellationToken)
        {
            var hasValidCredentials = _boringBankUserService.ValidateUsernameAndPassword(request.Username, request.Password);

            if (!hasValidCredentials)
            {
                throw new Exception("Invalid username or password");
            }

            var user  = _boringBankUserService.FindUserByUsername(request.Username);
            var token = _boringBankTokenService.CreateTokenFromUser(user);

            return(Task.FromResult(new UserAuthenticationResponse
            {
                AccessToken = token
            }));
        }