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

CLI Project w/ Authentication #25

Merged
merged 4 commits into from
Apr 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
4 changes: 3 additions & 1 deletion src/dotnet/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -485,4 +485,6 @@ $RECYCLE.BIN/

appsettings.*.json
sharedsettings.*.json
app.db
app.db

HQ.CLI/data/
9 changes: 9 additions & 0 deletions src/dotnet/HQ.Abstractions/HQ.Abstractions.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
namespace HQ.Server;
namespace HQ.Abstractions;

public class WeatherForecast
{
Expand Down
34 changes: 34 additions & 0 deletions src/dotnet/HQ.CLI/Commands/ConfigureCommand.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
using Microsoft.Extensions.Logging;
using Spectre.Console;
using Spectre.Console.Cli;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HQ.CLI.Commands;

internal class ConfigureCommand : AsyncCommand<HQCommandSettings>
{
private readonly HQConfig _config;

public ConfigureCommand(HQConfig config)
{
_config = config;
}

public override async Task<int> ExecuteAsync(CommandContext context, HQCommandSettings settings)

Check warning on line 21 in src/dotnet/HQ.CLI/Commands/ConfigureCommand.cs

View workflow job for this annotation

GitHub Actions / build-dotnet

This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.

Check warning on line 21 in src/dotnet/HQ.CLI/Commands/ConfigureCommand.cs

View workflow job for this annotation

GitHub Actions / build-dotnet

This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
{
_config.ApiUrl = AnsiConsole.Prompt(
new TextPrompt<Uri>("Enter API URL:")
.ValidationErrorMessage("[red]That's not a valid API URL[/]")
.Validate(uri => uri.IsAbsoluteUri));

_config.AuthUrl = AnsiConsole.Prompt(new TextPrompt<Uri>("Enter Auth URL:")
.ValidationErrorMessage("[red]That's not a valid Auth URL[/]")
.Validate(uri => uri.IsAbsoluteUri));

return 0;
}
}
109 changes: 109 additions & 0 deletions src/dotnet/HQ.CLI/Commands/LoginCommand.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
using IdentityModel.Client;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.Extensions.Logging;
using Spectre.Console;
using Spectre.Console.Cli;
using System.Diagnostics;
using static IdentityModel.OidcConstants;

namespace HQ.CLI.Commands;

internal class LoginCommand : AsyncCommand<HQCommandSettings>
{
private readonly ILogger<LoginCommand> _logger;
private readonly HQConfig _config;
private readonly IDataProtectionProvider _dataProtectionProvider;
private readonly HttpClient _httpClient;

public LoginCommand(ILogger<LoginCommand> logger, HQConfig config, IDataProtectionProvider dataProtectionProvider, HttpClient httpClient)
{
_logger = logger;
_config = config;
_dataProtectionProvider = dataProtectionProvider;
_httpClient = httpClient;
}

public override async Task<int> ExecuteAsync(CommandContext context, HQCommandSettings settings)
{
if(String.IsNullOrEmpty(_config.AuthUrl?.AbsoluteUri))
{
AnsiConsole.MarkupLine("[red]Invalid Auth URL[/]");
return 1;
}

var disco = await _httpClient.GetDiscoveryDocumentAsync(_config.AuthUrl.AbsoluteUri);
if (disco.IsError) throw new Exception(disco.Error);

var authorizeResponse = await _httpClient.RequestDeviceAuthorizationAsync(new DeviceAuthorizationRequest
{
Address = disco.DeviceAuthorizationEndpoint,
ClientId = "hq",
Scope = "openid profile email offline_access"
});
if (authorizeResponse.IsError) throw new Exception(authorizeResponse.Error);

AnsiConsole.MarkupLineInterpolated($@"Attempting to automatically open the login page in your default browser.
If the browser does not open or you wish to use a different device to authorize this request, open the following URL:

[link]{authorizeResponse.VerificationUri}[/]

Then enter the code:

{authorizeResponse.UserCode}");

try
{
Process launchBrowserProcess = new Process();
launchBrowserProcess.StartInfo.UseShellExecute = true;
launchBrowserProcess.StartInfo.FileName = authorizeResponse.VerificationUriComplete;
launchBrowserProcess.Start();
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Unable to launch browser.");
}

var interval = TimeSpan.FromSeconds(authorizeResponse.Interval);
var expiresIn = authorizeResponse.ExpiresIn;
DateTime? expiresAt = null;
if (expiresIn.HasValue)
{
expiresAt = DateTime.UtcNow.AddSeconds(expiresIn.Value);
}

IdentityModel.Client.TokenResponse? response = null;
do
{
response = await _httpClient.RequestDeviceTokenAsync(new DeviceTokenRequest
{
Address = disco.TokenEndpoint,

ClientId = "hq",
DeviceCode = authorizeResponse.DeviceCode

Check warning on line 82 in src/dotnet/HQ.CLI/Commands/LoginCommand.cs

View workflow job for this annotation

GitHub Actions / build-dotnet

Possible null reference assignment.

Check warning on line 82 in src/dotnet/HQ.CLI/Commands/LoginCommand.cs

View workflow job for this annotation

GitHub Actions / build-dotnet

Possible null reference assignment.
});

// Console.WriteLine(response.Raw);

if (response.Error == "slow_down")
{
// Console.WriteLine("Got a slow down!");
interval += TimeSpan.FromSeconds(5);
}

// Console.WriteLine("Waiting for response...");
await Task.Delay(interval);
}
while (response.Error == "authorization_pending" || response.Error == "slow_down");
if (response.IsError) throw new Exception(response.Error);

var protector = _dataProtectionProvider.CreateProtector("HQ.CLI");

_config.RefreshToken = !String.IsNullOrEmpty(response.RefreshToken) ? protector.Protect(response.RefreshToken) : null;
_config.AccessToken = !String.IsNullOrEmpty(response.AccessToken) ? protector.Protect(response.AccessToken) : null; ;
_config.AccessTokenExpiresAt = DateTime.UtcNow.AddSeconds(response.ExpiresIn);

AnsiConsole.MarkupLine("[green]Authentication successful![/] ");

return 0;
}
}
28 changes: 28 additions & 0 deletions src/dotnet/HQ.CLI/Commands/TestApiCommand.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
using HQ.SDK;
using Spectre.Console.Cli;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HQ.CLI.Commands
{
internal class TestApiCommand : AsyncCommand<HQCommandSettings>
{
private readonly TestApiService _testApiService;

public TestApiCommand(TestApiService testApiService)
{
_testApiService = testApiService;
}

public override async Task<int> ExecuteAsync(CommandContext context, HQCommandSettings settings)
{
var response = await _testApiService.GetWeatherForecastAsync();
Console.WriteLine(response);

return 0;
}
}
}
38 changes: 38 additions & 0 deletions src/dotnet/HQ.CLI/HQ.CLI.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<PublishSingleFile>true</PublishSingleFile>
<SelfContained>true</SelfContained>
<AssemblyName>hq</AssemblyName>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="IdentityModel" Version="6.2.0" />
<PackageReference Include="Microsoft.AspNetCore.DataProtection.Extensions" Version="8.0.3" />
<PackageReference Include="Microsoft.Extensions.Http" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="8.0.0" />
<PackageReference Include="Spectre.Console.Cli" Version="0.48.1-preview.0.38" />
</ItemGroup>

<ItemGroup>
<None Update="Properties\launchSettings.json">
<ExcludeFromSingleFile>true</ExcludeFromSingleFile>
<CopyToPublishDirectory>Never</CopyToPublishDirectory>
</None>
</ItemGroup>

<ItemGroup>
<Folder Include="data\keys\" />
<Folder Include="Settings\" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\HQ.SDK\HQ.SDK.csproj" />
</ItemGroup>

</Project>
76 changes: 76 additions & 0 deletions src/dotnet/HQ.CLI/HQApiMessageHandler.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using Microsoft.AspNetCore.DataProtection;
using IdentityModel.Client;
using static IdentityModel.OidcConstants;

namespace HQ.CLI
{
internal class HQApiMessageHandler : DelegatingHandler
{
private readonly HQConfig _config;
private readonly HttpClient _httpClient;
private readonly IDataProtector _dataProtector;

public HQApiMessageHandler(HQConfig config, HttpClient httpClient, IDataProtectionProvider dataProtectionProvider)
{
_config = config;
_httpClient = httpClient;
_dataProtector = dataProtectionProvider.CreateProtector("HQ.CLI");
}

private async Task<string> GetTokenAsync(CancellationToken cancellationToken, bool forceRefresh = false)
{
var accessToken = _dataProtector.Unprotect(_config.AccessToken);

Check warning on line 30 in src/dotnet/HQ.CLI/HQApiMessageHandler.cs

View workflow job for this annotation

GitHub Actions / build-dotnet

Possible null reference argument for parameter 'protectedData' in 'string DataProtectionCommonExtensions.Unprotect(IDataProtector protector, string protectedData)'.

Check warning on line 30 in src/dotnet/HQ.CLI/HQApiMessageHandler.cs

View workflow job for this annotation

GitHub Actions / build-dotnet

Possible null reference argument for parameter 'protectedData' in 'string DataProtectionCommonExtensions.Unprotect(IDataProtector protector, string protectedData)'.
var refreshToken = _dataProtector.Unprotect(_config.RefreshToken);

Check warning on line 31 in src/dotnet/HQ.CLI/HQApiMessageHandler.cs

View workflow job for this annotation

GitHub Actions / build-dotnet

Possible null reference argument for parameter 'protectedData' in 'string DataProtectionCommonExtensions.Unprotect(IDataProtector protector, string protectedData)'.

Check warning on line 31 in src/dotnet/HQ.CLI/HQApiMessageHandler.cs

View workflow job for this annotation

GitHub Actions / build-dotnet

Possible null reference argument for parameter 'protectedData' in 'string DataProtectionCommonExtensions.Unprotect(IDataProtector protector, string protectedData)'.

if ((_config.AccessTokenExpiresAt.HasValue && _config.AccessTokenExpiresAt.Value <= DateTime.UtcNow) || forceRefresh)
{
var disco = await _httpClient.GetDiscoveryDocumentAsync(_config.AuthUrl.AbsoluteUri);

Check warning on line 35 in src/dotnet/HQ.CLI/HQApiMessageHandler.cs

View workflow job for this annotation

GitHub Actions / build-dotnet

Dereference of a possibly null reference.

Check warning on line 35 in src/dotnet/HQ.CLI/HQApiMessageHandler.cs

View workflow job for this annotation

GitHub Actions / build-dotnet

Dereference of a possibly null reference.
if (disco.IsError) throw new Exception(disco.Error);

var response = await _httpClient.RequestRefreshTokenAsync(new RefreshTokenRequest
{
Address = disco.TokenEndpoint,

ClientId = "hq",
RefreshToken = refreshToken
});

if (response.IsError) throw new Exception(response.Error);

accessToken = response.AccessToken;

_config.RefreshToken = !String.IsNullOrEmpty(response.RefreshToken) ? _dataProtector.Protect(response.RefreshToken) : null;
_config.AccessToken = !String.IsNullOrEmpty(response.AccessToken) ? _dataProtector.Protect(response.AccessToken) : null; ;
_config.AccessTokenExpiresAt = DateTime.UtcNow.AddSeconds(response.ExpiresIn);
}

return accessToken;

Check warning on line 55 in src/dotnet/HQ.CLI/HQApiMessageHandler.cs

View workflow job for this annotation

GitHub Actions / build-dotnet

Possible null reference return.

Check warning on line 55 in src/dotnet/HQ.CLI/HQApiMessageHandler.cs

View workflow job for this annotation

GitHub Actions / build-dotnet

Possible null reference return.
}

protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var token = await GetTokenAsync(cancellationToken);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);

var response = await base.SendAsync(request, cancellationToken);
if (response.StatusCode == HttpStatusCode.Unauthorized)
{
token = await GetTokenAsync(cancellationToken, true);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
response.Dispose();

response = await base.SendAsync(request, cancellationToken);
}

return response;
}
}
}
18 changes: 18 additions & 0 deletions src/dotnet/HQ.CLI/HQCommandInterceptor.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
using Spectre.Console.Cli;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HQ.CLI;

internal class HQCommandInterceptor : ICommandInterceptor
{
public void Intercept(CommandContext context, CommandSettings settings)
{
if (settings is HQCommandSettings hqSettings)
{
}
}
}
13 changes: 13 additions & 0 deletions src/dotnet/HQ.CLI/HQCommandSettings.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
using Spectre.Console.Cli;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HQ.CLI
{
public class HQCommandSettings : CommandSettings
{
}
}
18 changes: 18 additions & 0 deletions src/dotnet/HQ.CLI/HQConfig.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace HQ.CLI
{
internal class HQConfig
{
public Uri? ApiUrl { get; set; }
public Uri? AuthUrl { get; set; }
public string? RefreshToken { get; set; }
public string? AccessToken { get; set; }
public DateTime? AccessTokenExpiresAt { get; set; }
}
}
Loading
Loading