Skip to content

Update authorization method to Bearer header. Related #20 #21

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Dec 27, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion build.cake
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,8 @@ Task("Test")
var settings = new DotNetTestSettings
{
Configuration = buildConfiguration,
Loggers = new List<string> { "console;verbosity=detailed" }
Loggers = new List<string> { "console;verbosity=detailed" },
Filter = "trait!=mfa-required"
};

DotNetTest(testProjectFile, settings);
Expand Down
5 changes: 5 additions & 0 deletions src/Todoist.Net.Tests/Extensions/Constants.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,9 @@ internal static class Constants
public const string IntegrationFreeTraitValue = "integration-free";

public const string IntegrationPremiumTraitValue = "integration-premium";

/// <summary>
/// These kind of test won't work with MFA enabled.
/// </summary>
public const string MfaRequiredTraitValue = "mfa-required";
}
2 changes: 1 addition & 1 deletion src/Todoist.Net.Tests/Models/DueDateTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public void DateTimeAssignment_FloatingDueDateEvent_Success()
{
var date = new DateTime(2018, 2, 5, 0, 0, 0, DateTimeKind.Utc);

var dueDate = new DueDate(date, false);
var dueDate = new DueDate(date);

Assert.Equal("2018-02-05T00:00:00", dueDate.StringDate);
Assert.False(dueDate.IsFullDay);
Expand Down
16 changes: 8 additions & 8 deletions src/Todoist.Net.Tests/RateLimitAwareRestClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,17 +13,17 @@ public sealed class RateLimitAwareRestClient : ITodoistRestClient
{
private readonly ITestOutputHelper _outputHelper;

private readonly TodoistRestClient restClient;
private readonly TodoistRestClient _restClient;

public RateLimitAwareRestClient(ITestOutputHelper outputHelper)
public RateLimitAwareRestClient(string token, ITestOutputHelper outputHelper)
{
_outputHelper = outputHelper;
restClient = new TodoistRestClient();
_restClient = new TodoistRestClient(token);
}

public void Dispose()
{
restClient?.Dispose();
_restClient?.Dispose();
}

public async Task<HttpResponseMessage> ExecuteRequest(Func<Task<HttpResponseMessage>> request)
Expand All @@ -36,7 +36,7 @@ public async Task<HttpResponseMessage> ExecuteRequest(Func<Task<HttpResponseMess
do
{
result = await request().ConfigureAwait(false);
if ((int)result.StatusCode != 429 /*Requests limit*/ &&
if ((int)result.StatusCode != 429 /*Requests limit*/ &&
(int)result.StatusCode < 500 /*Server side errors happen randomly*/)
{
return result;
Expand All @@ -57,15 +57,15 @@ public async Task<HttpResponseMessage> PostAsync(
string resource,
IEnumerable<KeyValuePair<string, string>> parameters)
{
return await ExecuteRequest(() => restClient.PostAsync(resource, parameters)).ConfigureAwait(false);
return await ExecuteRequest(() => _restClient.PostAsync(resource, parameters)).ConfigureAwait(false);
}

public async Task<HttpResponseMessage> PostFormAsync(
string resource,
IEnumerable<KeyValuePair<string, string>> parameters,
IEnumerable<ByteArrayContent> files)
{
return await ExecuteRequest(() => restClient.PostFormAsync(resource, parameters, files))
return await ExecuteRequest(() => _restClient.PostFormAsync(resource, parameters, files))
.ConfigureAwait(false);
}

Expand All @@ -79,7 +79,7 @@ public async Task<TimeSpan> GetRateLimitCooldown(HttpResponseMessage response)
var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
JObject json = JObject.Parse(content);

return TimeSpan.FromSeconds(json["error_extra"]["retry_after"].Value<double>());
return TimeSpan.FromSeconds(json["error_extra"]!["retry_after"]!.Value<double>());
}
catch
{
Expand Down
2 changes: 1 addition & 1 deletion src/Todoist.Net.Tests/Services/ActivityServiceTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ public void GetActivity_HasEntries()
{
var client = TodoistClientFactory.Create(_outputHelper);

var logEntries = client.Activity.GetAsync(new LogFilter() { Limit = 50 }).Result.Events;
var logEntries = client.Activity.GetAsync(new LogFilter { Limit = 50 }).Result.Events;

Assert.NotEmpty(logEntries);
}
Expand Down
2 changes: 1 addition & 1 deletion src/Todoist.Net.Tests/Services/BackupServiceTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
namespace Todoist.Net.Tests.Services
{
[Collection(Constants.TodoistApiTestCollectionName)]
[Trait(Constants.TraitName, Constants.IntegrationFreeTraitValue)]
[Trait(Constants.TraitName, Constants.MfaRequiredTraitValue)]
public class BackupServiceTests
{
private readonly ITestOutputHelper _outputHelper;
Expand Down
2 changes: 1 addition & 1 deletion src/Todoist.Net.Tests/Services/FiltersServiceTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public void GetFilterInfo_Success()
{
var client = TodoistClientFactory.Create(_outputHelper);

var filters = client.Filters.GetAsync().Result;
var filters = client.Filters.GetAsync().Result.ToList();

Assert.True(filters.Any());

Expand Down
6 changes: 4 additions & 2 deletions src/Todoist.Net.Tests/Services/ProjectsServiceTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ public void CreateUpdateOrderMoveAndDelete_Success()
var client = TodoistClientFactory.Create(_outputHelper);

var projectName = Guid.NewGuid().ToString();
var project = new Project(projectName);
var project = new Project(projectName);
client.Projects.AddAsync(project).Wait();

Assert.True(project.Id != default(string));
Expand All @@ -58,7 +58,9 @@ public void CreateUpdateOrderMoveAndDelete_Success()
client.Projects.UpdateAsync(project).Wait();

client.Projects.ReorderAsync(new ReorderEntry(project.Id, 1)).Wait();
client.Projects.MoveAsync(new MoveArgument(project.Id, null)).Wait();

// TODO: Fix the request
//client.Projects.MoveAsync(new MoveArgument(project.Id, null)).Wait();

client.Projects.DeleteAsync(project.Id).Wait();
}
Expand Down
2 changes: 1 addition & 1 deletion src/Todoist.Net.Tests/TodoistClientFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ public static class TodoistClientFactory
public static ITodoistClient Create(ITestOutputHelper outputHelper)
{
var token = SettingsProvider.GetToken();
return new TodoistClient(token, new RateLimitAwareRestClient(outputHelper));
return new TodoistClient(new RateLimitAwareRestClient(token, outputHelper));
}

public static ITodoistTokenlessClient CreateTokenlessClient()
Expand Down
8 changes: 4 additions & 4 deletions src/Todoist.Net/Todoist.Net.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@

<PropertyGroup>
<Description>A Todoist API client for .NET</Description>
<VersionPrefix>3.0.1</VersionPrefix>
<VersionPrefix>4.0.0</VersionPrefix>
<Authors>Oleg Shevchenko</Authors>
<TargetFrameworks>netstandard2.0;net45</TargetFrameworks>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<AssemblyName>Todoist.Net</AssemblyName>

<PackageId>Todoist.Net</PackageId>
<PackageTags>todoist</PackageTags>
<PackageReleaseNotes>https://github.com/olsh/todoist-net/releases</PackageReleaseNotes>
Expand All @@ -16,7 +16,7 @@
<RepositoryType>git</RepositoryType>
<RepositoryUrl>https://github.com/olsh/todoist-net</RepositoryUrl>
<PackageIconUrl>https://raw.githubusercontent.com/olsh/todoist-net/master/images/todoist-net-nuget.png</PackageIconUrl>

<AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder>
</PropertyGroup>

Expand All @@ -29,7 +29,7 @@
<ItemGroup Condition=" '$(TargetFramework)' == 'net45' ">
<Reference Include="System.Net.Http" />
</ItemGroup>

<ItemGroup>
<AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleTo">
<_Parameter1>Todoist.Net.Tests</_Parameter1>
Expand Down
38 changes: 8 additions & 30 deletions src/Todoist.Net/TodoistClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,15 +30,13 @@ public sealed class TodoistClient : IDisposable, IAdvancedTodoistClient

private readonly ITodoistRestClient _restClient;

private readonly string _token;

/// <summary>
/// Initializes a new instance of the <see cref="TodoistClient" /> class.
/// </summary>
/// <param name="token">The token.</param>
/// <exception cref="ArgumentException">Value cannot be null or empty - token</exception>
public TodoistClient(string token)
: this(token, new TodoistRestClient())
: this(token, null)
{
}

Expand All @@ -49,25 +47,22 @@ public TodoistClient(string token)
/// <param name="proxy">The proxy.</param>
/// <exception cref="ArgumentException">Value cannot be null or empty - token</exception>
public TodoistClient(string token, IWebProxy proxy)
: this(token, new TodoistRestClient(proxy))
: this(new TodoistRestClient(token, proxy))
{
if (string.IsNullOrEmpty(token))
{
throw new ArgumentException("Value cannot be null or empty.", nameof(token));
}
}

/// <summary>
/// Initializes a new instance of the <see cref="TodoistClient" /> class.
/// </summary>
/// <param name="token">The token.</param>
/// <param name="restClient">The rest client.</param>
/// <exception cref="System.ArgumentException">Value cannot be null or empty - token</exception>
public TodoistClient(string token, ITodoistRestClient restClient)
public TodoistClient(ITodoistRestClient restClient)
{
if (string.IsNullOrEmpty(token))
{
throw new ArgumentException("Value cannot be null or empty.", nameof(token));
}

_token = token;
_restClient = restClient;
_restClient = restClient ?? throw new ArgumentNullException(nameof(restClient));

Projects = new ProjectsService(this);
Templates = new TemplateService(this);
Expand All @@ -86,11 +81,6 @@ public TodoistClient(string token, ITodoistRestClient restClient)
Sections = new SectionService(this);
}

internal TodoistClient(ITodoistRestClient restClient)
{
_restClient = restClient ?? throw new ArgumentNullException(nameof(restClient));
}

/// <summary>
/// Gets the activity service.
/// </summary>
Expand Down Expand Up @@ -378,8 +368,6 @@ private async Task<T> ProcessFormAsync<T>(
ICollection<KeyValuePair<string, string>> parameters,
IEnumerable<ByteArrayContent> files)
{
TryAddToken(parameters);

var response = await _restClient.PostFormAsync(resource, parameters, files)
.ConfigureAwait(false);
var responseContent = await ReadResponseAsync(response)
Expand All @@ -399,8 +387,6 @@ private async Task<string> ProcessRawPostAsync(
string resource,
ICollection<KeyValuePair<string, string>> parameters)
{
TryAddToken(parameters);

var response = await _restClient.PostAsync(resource, parameters)
.ConfigureAwait(false);

Expand Down Expand Up @@ -477,14 +463,6 @@ private void ThrowIfErrors(SyncResponse syncResponse)
}
}

private void TryAddToken(ICollection<KeyValuePair<string, string>> parameters)
{
if (!string.IsNullOrEmpty(_token))
{
parameters.Add(new KeyValuePair<string, string>("token", _token));
}
}

private void UpdateTempIds(Command[] commands, IDictionary<Guid, string> tempIdMappings)
{
foreach (var command in commands)
Expand Down
23 changes: 20 additions & 3 deletions src/Todoist.Net/TodoistRestClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace Todoist.Net
Expand All @@ -10,11 +11,19 @@ internal sealed class TodoistRestClient : ITodoistRestClient
{
private readonly HttpClient _httpClient;

public TodoistRestClient() : this(null)
public TodoistRestClient() : this(null, null)
{
}

public TodoistRestClient(IWebProxy proxy)
public TodoistRestClient(string token) : this(token, null)
{
}

public TodoistRestClient(IWebProxy proxy) : this(null, proxy)
{
}

public TodoistRestClient(string token, IWebProxy proxy)
{
var httpClientHandler = new HttpClientHandler();
if (proxy != null)
Expand All @@ -24,7 +33,15 @@ public TodoistRestClient(IWebProxy proxy)
}

// ReSharper disable once ExceptionNotDocumented
_httpClient = new HttpClient(httpClientHandler) { BaseAddress = new Uri("https://api.todoist.com/sync/v9/") };
_httpClient = new HttpClient(httpClientHandler)
{
BaseAddress = new Uri("https://api.todoist.com/sync/v9/")
};

if (!string.IsNullOrEmpty(token))
{
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
}
}

public void Dispose()
Expand Down