protected override async Task <HttpResponseMessage> SendAsync(
            HttpRequestMessage request,
            CancellationToken cancellationToken)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            var accessToken = _accessTokenAccessor.AccessToken;

            if (accessToken == null)
            {
                throw new InvalidOperationException("Missing access token.");
            }

            if (accessToken.IsExpired)
            {
                if (_accessTokenRefresher == null)
                {
                    throw new InvalidOperationException(
                              $"Access token is expired and there is no [{nameof(IAccessTokenRefresher)}].");
                }

                accessToken = await _accessTokenRefresher.RefreshAccessToken(
                    accessToken.RefreshToken,
                    cancellationToken);

                await _accessTokenStore.StoreTokenAsync(accessToken, cancellationToken);
            }

            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken.Value);

            return(await base.SendAsync(request, cancellationToken));
        }
Esempio n. 2
0
        public async Task <Unit> Handle(LoginCommand request, CancellationToken cancellationToken)
        {
            Console.WriteLine(_stringLocalizer["Welcome!"]);
            Console.WriteLine(_stringLocalizer["To login and create an access token:"]);
            Console.WriteLine(
                _stringLocalizer["1. Open a browser and go to "] +
                "https://moneybird.com/oauth/authorize?" +
                $"client_id={_apiConfiguration.ClientId}" +
                "&redirect_uri=urn:ietf:wg:oauth:2.0:oob" +
                "&response_type=code" +
                "&scope=sales_invoices%20documents%20estimates%20bank%20settings");
            Console.WriteLine(_stringLocalizer["2. Copy and paste code."]);

            Console.Write(TerminalReadLinePrefix);

            var authenticationCode = Console.ReadLine();

            Console.WriteLine("\n" + _stringLocalizer["Retrieving access token..."]);

            AccessToken accessToken;

            try
            {
                accessToken = await _accessTokenAcquirer.AcquireAccessTokenAsync(
                    authenticationCode,
                    cancellationToken);
            }
            catch (HttpRequestException)
            {
                Console.WriteLine(_stringLocalizer["Retrieving access token failed."]);
                return(Unit.Value);
            }

            await _accessTokenStore.StoreTokenAsync(accessToken, cancellationToken);

            Console.WriteLine(_stringLocalizer["Login successful!"]);

            return(Unit.Value);
        }