Skip to content
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

Added tests for Auth without ApiKey #140

Merged
merged 3 commits into from
Nov 9, 2024
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
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
<PackageLicenseExpression>Apache-2.0</PackageLicenseExpression>
<PackageReadmeFile>README.md</PackageReadmeFile>
<Title>MoonrakerSharpWebApi.SQLite</Title>
<UserSecretsId>2fcb2e15-a623-46ce-91ea-5913ca527be9</UserSecretsId>
</PropertyGroup>

<ItemGroup>
Expand Down
78 changes: 78 additions & 0 deletions src/MoonrakerSharpWebApi.Test/MoonrakerSharpWebApi.Test.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ public class Tests
private readonly string _host = SecretAppSettingReader.ReadSection<SecretAppSetting>("TestSetup").Ip ?? "";
private readonly int _port = 80;
private readonly string _api = SecretAppSettingReader.ReadSection<SecretAppSetting>("TestSetup").ApiKey ?? "";
private readonly string _user = SecretAppSettingReader.ReadSection<SecretAppSetting>("TestSetup").Username ?? "";
private readonly string _pwd = SecretAppSettingReader.ReadSection<SecretAppSetting>("TestSetup").Password ?? "";
private readonly bool _ssl = false;

private readonly bool _skipOnlineTests = true;
Expand Down Expand Up @@ -48,6 +50,82 @@ public void TearDown()
client?.Dispose();
}

[Test]
public async Task BuildWitOneShotTokenAsync()
{
try
{
var client = new MoonrakerClient.MoonrakerConnectionBuilder()
.WithName("Test")
.WithServerAddress(_host, _port, _ssl)
.Build();
KlipperAccessTokenResult? token = await client.GetOneshotTokenAsync();

client.OneShotToken = token?.Result ?? string.Empty;
Assert.That(!string.IsNullOrEmpty(client.OneShotToken));

KlipperMachineInfo? info = await client.GetMachineSystemInfoAsync();
Assert.That(info is not null);
}
catch (Exception ex)
{
Assert.Fail(ex.Message);
}
}

[Test]
public async Task BuildWitUserTokenAsync()
{
try
{
Assert.That(!string.IsNullOrEmpty(_user) && !string.IsNullOrEmpty(_pwd), "Provide a user and password in your secrets.json file first!");
var client = new MoonrakerClient.MoonrakerConnectionBuilder()
.WithName("Test")
.WithServerAddress(_host, _port, _ssl)
.Build();
string? apiKey = await client.LoginUserForApiKeyAsync(_user, _pwd);

/*
* Set by the LoginUserAsync() method
* UserToken = queryResult?.Result?.Token ?? string.Empty;
* RefreshToken = queryResult?.Result?.RefreshToken ?? string.Empty;
*/
Assert.That(!string.IsNullOrEmpty(client.UserToken));
Assert.That(!string.IsNullOrEmpty(client.RefreshToken));

// This should be enough to authenticate.
KlipperMachineInfo? info = await client.GetMachineSystemInfoAsync();
Assert.That(info is not null);
info = null;

// Remove the api key to test if the UserToken works as well
var lastHeader = client.AuthHeaders.Last();
client.AuthHeaders.Remove(lastHeader.Key);

info = await client.GetMachineSystemInfoAsync();
Assert.That(info is not null);

client.AuthHeaders.Clear();
client.ApiKey = "";

// Also try with the api key to verify
client.ApiKey = apiKey ?? string.Empty;
Assert.That(!string.IsNullOrEmpty(client.ApiKey));

info = await client.GetMachineSystemInfoAsync();
Assert.That(info is not null);

await client.LogoutCurrentUserAsync();

info = await client.GetMachineSystemInfoAsync();
Assert.That(info is not null);
}
catch (Exception ex)
{
Assert.Fail(ex.Message);
}
}

[Test]
public void SerializeJsonTest()
{
Expand Down
2 changes: 2 additions & 0 deletions src/MoonrakerSharpWebApi.Test/SecretAppSetting.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,7 @@ public class SecretAppSetting
{
public string? ApiKey { get; set; }
public string? Ip { get; set; }
public string? Username { get; set; }
public string? Password { get; set; }
}
}
7 changes: 7 additions & 0 deletions src/MoonrakerSharpWebApi/MoonrakerClient.Auth.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,13 @@ namespace AndreasReitberger.API.Moonraker
public partial class MoonrakerClient
{
#region Auth
/*
[ObservableProperty]
[property: JsonIgnore, System.Text.Json.Serialization.JsonIgnore, XmlIgnore]
new string apiKey = string.Empty;
partial void OnApiKeyChanged(string value) => AddOrUpdateAuthHeader("usertoken", value);
*/


[ObservableProperty]
[property: JsonIgnore, System.Text.Json.Serialization.JsonIgnore, XmlIgnore]
Expand Down
2 changes: 1 addition & 1 deletion src/MoonrakerSharpWebApi/MoonrakerClient.Files.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ partial void OnFilesChanged(ObservableCollection<KlipperFile> value)

[ObservableProperty]
[property: JsonIgnore, System.Text.Json.Serialization.JsonIgnore, XmlIgnore]
ObservableCollection<KlipperDirectory> availableDirectories = new();
ObservableCollection<KlipperDirectory> availableDirectories = [];
partial void OnAvailableDirectoriesChanged(ObservableCollection<KlipperDirectory> value)
{
/*
Expand Down
6 changes: 0 additions & 6 deletions src/MoonrakerSharpWebApi/MoonrakerClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,12 @@
using AndreasReitberger.API.Print3dServer.Core.Interfaces;
using AndreasReitberger.Core.Utilities;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net.Http;
using System.Security;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
Expand Down Expand Up @@ -961,15 +958,13 @@ public bool CheckIfConfigurationHasChanged(object temp)
KlipperAccessTokenResult? resultObject = null;
try
{
//object cmd = new { name = ScriptName };
string targetUri = $"{MoonrakerCommands.Access}";
result = await SendRestApiRequestAsync(
requestTargetUri: targetUri,
method: Method.Get,
command: "oneshot_token",
jsonObject: null,
authHeaders: AuthHeaders,
//urlSegments: urlSegements,
cts: default
)
.ConfigureAwait(false);
Expand Down Expand Up @@ -1827,7 +1822,6 @@ await SendRestApiRequestAsync(MoonrakerCommandBase.machine, Method.Post, "servic
command: "login",
jsonObject: cmd,
authHeaders: AuthHeaders,
//urlSegments: urlSegments,
cts: default
)
.ConfigureAwait(false);
Expand Down
25 changes: 24 additions & 1 deletion src/MoonrakerSharpWebApi/MoonrakerConnectionBuilder.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
using System;
using AndreasReitberger.API.Moonraker.Models;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace AndreasReitberger.API.Moonraker
{
Expand Down Expand Up @@ -35,6 +37,27 @@ public MoonrakerConnectionBuilder WithApiKey(string apiKey)
return this;
}

/*
public async Task<MoonrakerConnectionBuilder> WithUserTokenAsync(string? userToken = null)
{
if (userToken is null)
{
KlipperAccessTokenResult? tokenResult = await _client.GetOneshotTokenAsync();
userToken = tokenResult?.Result;
}
_client.OneShotToken = userToken ?? string.Empty;
return this;
}

public async Task<MoonrakerConnectionBuilder> WitLoginAsync(string username, string password)
{
string apiToken = await _client.LoginUserForApiKeyAsync(username, password);
_client.ApiKey = apiToken;
await _client.LogoutCurrentUserAsync();
return this;
}
*/

public MoonrakerConnectionBuilder WithName(string name)
{
_client.ServerName = name;
Expand Down