Ejemplo n.º 1
0
        private async Task <T> SendAsync <T>(string url, HttpMethod method, object value, CancellationToken cancellationToken) where T : class
        {
            var content = value == null
                ? null
                : new StringContent(JsonFormatter.Format(value), Encoding.UTF8, MediaTypes.ManicTimeJson);
            ServerHttpResponse <T> serverResponse = await SendHttpAsync <T>(url, method, content, cancellationToken).ConfigureAwait(false);

            return(serverResponse?.Resource);
        }
Ejemplo n.º 2
0
        public async Task <string> AuthenticateOauthAsync(string username, string password, CancellationToken cancellationToken)
        {
            ServerHttpResponse <HomeResource> challengeResponse =
                await SendHttpAsync <HomeResource>(_serverUrl, HttpMethod.Get, null, cancellationToken).ConfigureAwait(false);

            string authenticationType = GetAuthenticationType(challengeResponse.Headers);

            if (authenticationType != AuthenticationTypes.Bearer)
            {
                throw new InvalidOperationException("Server is not configured for ManicTime authentication.");
            }
            string tokenUrl = challengeResponse.Resource?.Links.Url(Relations.Token);

            if (tokenUrl == null)
            {
                throw new InvalidOperationException("Token url not found.");
            }

            HttpContent tokenContent = new StringContent(
                $"grant_type=password&username={Uri.EscapeDataString(username ?? "")}&password={Uri.EscapeDataString(password ?? "")}",
                null, MediaTypes.FormUrlEncoded);
            ServerHttpResponse <AccessTokenResource> tokenResponse =
                await SendHttpAsync <AccessTokenResource>(tokenUrl, HttpMethod.Post, tokenContent, cancellationToken).ConfigureAwait(false);


            if (tokenResponse.StatusCode != HttpStatusCode.OK && tokenResponse.StatusCode != HttpStatusCode.BadRequest)
            {
                throw new InvalidOperationException($"Invalid status code received: {tokenResponse.StatusCode}");
            }
            if (tokenResponse.StatusCode == HttpStatusCode.BadRequest)
            {
                if (tokenResponse.Resource?.Error.Equals("invalid_grant", StringComparison.OrdinalIgnoreCase) == false)
                {
                    throw new InvalidOperationException($"Unknown error: {tokenResponse.Resource?.Error}");
                }
                return(null);
            }
            if (tokenResponse.Resource?.Token == null)
            {
                throw new InvalidOperationException("Token not received");
            }
            return(tokenResponse.Resource.Token);
        }