Skip to content

Commit

Permalink
Merge pull request #7 from EpicOfficer/FEATURE/Wordle
Browse files Browse the repository at this point in the history
Rework discord activity token handling in API and frontend (actually works now)
  • Loading branch information
EpicOfficer authored Apr 3, 2024
2 parents 67f8fd9 + 21d63a0 commit d0583fd
Show file tree
Hide file tree
Showing 19 changed files with 120 additions and 258 deletions.
4 changes: 0 additions & 4 deletions Blink3.API/Blink3.API.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,4 @@
<ProjectReference Include="..\Blink3.DataAccess\Blink3.DataAccess.csproj"/>
</ItemGroup>

<ItemGroup>
<Folder Include="Interfaces\"/>
</ItemGroup>

</Project>
59 changes: 12 additions & 47 deletions Blink3.API/Controllers/AuthController.cs
Original file line number Diff line number Diff line change
@@ -1,14 +1,11 @@
using System.Net.Http.Headers;
using System.Text.Json;
using AspNet.Security.OAuth.Discord;
using Blink3.API.Interfaces;
using Blink3.API.Models;
using Blink3.Core.Configuration;
using Blink3.Core.DiscordAuth;
using Blink3.Core.DiscordAuth.Extensions;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Swashbuckle.AspNetCore.Annotations;

namespace Blink3.API.Controllers;
Expand All @@ -17,14 +14,8 @@ namespace Blink3.API.Controllers;
[ApiController]
[SwaggerTag("Authentication related actions")]
public class AuthController(IAuthenticationService authenticationService,
IHttpClientFactory httpClientFactory,
IOptions<BlinkConfiguration> config) : ControllerBase
IDiscordTokenService discordTokenService) : ControllerBase
{
/// <summary>
/// Represents the configuration settings for the application.
/// </summary>
private BlinkConfiguration Config => config.Value;

[HttpGet("login")]
[SwaggerOperation(
Summary = "Initiates login via Discord",
Expand Down Expand Up @@ -74,42 +65,16 @@ public IActionResult Status()
}

[HttpPost("token")]
public async Task<IActionResult> Token([FromBody] DiscordTokenRequest tokenRequest)
[SwaggerOperation(
Summary = "Exchange an oauth code for an access token",
Description = "Returns the oauth2 access token",
OperationId = "Auth.Token",
Tags = ["Auth"]
)]
[SwaggerResponse(StatusCodes.Status200OK, "Returned access token", typeof(DiscordTokenResponse))]
[SwaggerResponse(StatusCodes.Status400BadRequest, "Failed to get an access token", typeof(ProblemDetails))]
public async Task<IActionResult> Token([FromBody] string code)
{
string clientId = Config.Discord.ClientId;
string clientSecret = Config.Discord.ClientSecret;

using HttpClient httpClient = httpClientFactory.CreateClient();
FormUrlEncodedContent requestBody = new(new[]
{
new KeyValuePair<string, string>("client_id", clientId),
new KeyValuePair<string, string>("client_secret", clientSecret),
new KeyValuePair<string, string>("grant_type", "authorization_code"),
new KeyValuePair<string, string>("code", tokenRequest.Code)
});

httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

HttpResponseMessage response;

try
{
response = await httpClient.PostAsync(DiscordAuthenticationDefaults.TokenEndpoint, requestBody);
}
catch (Exception ex)
{
return BadRequest("Request failed - " + ex.Message);
}

if (!response.IsSuccessStatusCode) return BadRequest();

string jsonResponse = await response.Content.ReadAsStringAsync();
Dictionary<string, string>? token = JsonSerializer.Deserialize<Dictionary<string, string>>(jsonResponse);
if (token is null || !token.TryGetValue("access_token", out string? value))
{
return BadRequest("Could not obtain access token");
}

return Ok(new { access_token = value });
return Ok(await discordTokenService.GetTokenAsync(code));
}
}
19 changes: 19 additions & 0 deletions Blink3.API/Interfaces/IDiscordTokenService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
using Blink3.API.Models;

namespace Blink3.API.Interfaces;

/// <summary>
/// Represents the interface for handling Discord token operations.
/// </summary>
public interface IDiscordTokenService
{
/// <summary>
/// Retrieves a Discord access token asynchronously.
/// </summary>
/// <param name="code">The authorization code received from Discord.</param>
/// <returns>
/// A task that represents the asynchronous operation. The task result contains a
/// <see cref="DiscordTokenResponse" /> object representing the Discord access token information.
/// </returns>
Task<DiscordTokenResponse> GetTokenAsync(string code);
}
8 changes: 0 additions & 8 deletions Blink3.API/Models/DiscordTokenRequest.cs

This file was deleted.

21 changes: 21 additions & 0 deletions Blink3.API/Models/DiscordTokenResponse.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
using System.Text.Json.Serialization;

namespace Blink3.API.Models;

public class DiscordTokenResponse
{
[JsonPropertyName("token_type")]
public string? TokenType { get; set; }

[JsonPropertyName("access_token")]
public string? AccessToken { get; set; }

[JsonPropertyName("expires_in")]
public int ExpiresIn { get; set; }

[JsonPropertyName("refresh_token")]
public string? RefreshToken { get; set; }

[JsonPropertyName("scope")]
public string? Scope { get; set; }
}
3 changes: 3 additions & 0 deletions Blink3.API/Program.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Blink3.API.Extensions;
using Blink3.API.Interfaces;
using Blink3.API.Services;
using Blink3.Core.Caching.Extensions;
using Blink3.Core.Configuration;
Expand Down Expand Up @@ -66,7 +67,9 @@
builder.Services.AddSingleton<DiscordRestClient>();
builder.Services.AddHostedService<DiscordStartupService>();

// For getting discord tokens
builder.Services.AddHttpClient();
builder.Services.AddSingleton<IDiscordTokenService, DiscordTokenService>();

// Configure Authentication and Discord OAuth
builder.Services.AddDiscordAuth(appConfig);
Expand Down
36 changes: 36 additions & 0 deletions Blink3.API/Services/DiscordTokenService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using System.Net.Http.Headers;
using AspNet.Security.OAuth.Discord;
using Blink3.API.Interfaces;
using Blink3.API.Models;
using Blink3.Core.Configuration;
using Microsoft.Extensions.Options;

namespace Blink3.API.Services;

public class DiscordTokenService(
IHttpClientFactory httpClientFactory,
IOptions<BlinkConfiguration> config) : IDiscordTokenService
{
private BlinkConfiguration Config => config.Value;

public async Task<DiscordTokenResponse> GetTokenAsync(string code)
{
using HttpClient httpClient = httpClientFactory.CreateClient();
FormUrlEncodedContent requestBody = new(new[]
{
new KeyValuePair<string, string>("client_id", Config.Discord.ClientId),
new KeyValuePair<string, string>("client_secret", Config.Discord.ClientSecret),
new KeyValuePair<string, string>("grant_type", "authorization_code"),
new KeyValuePair<string, string>("code", code)
});

httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

HttpResponseMessage response =
await httpClient.PostAsync(DiscordAuthenticationDefaults.TokenEndpoint, requestBody);
if (!response.IsSuccessStatusCode)
throw new ApplicationException("Error retrieving access token from Discord.");

return await response.Content.ReadFromJsonAsync<DiscordTokenResponse>() ?? new DiscordTokenResponse();
}
}
30 changes: 0 additions & 30 deletions Blink3.Activity/README.md

This file was deleted.

1 change: 0 additions & 1 deletion Blink3.Activity/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + React + TS</title>
</head>
Expand Down
2 changes: 1 addition & 1 deletion Blink3.Activity/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 4 additions & 4 deletions Blink3.Activity/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@
"preview": "vite preview"
},
"dependencies": {
"@discord/embedded-app-sdk": "^1.1.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"@discord/embedded-app-sdk": "1.1.0"
"react-dom": "^18.2.0"
},
"devDependencies": {
"@types/react": "^18.2.66",
Expand All @@ -23,8 +23,8 @@
"eslint": "^8.57.0",
"eslint-plugin-react-hooks": "^4.6.0",
"eslint-plugin-react-refresh": "^0.4.6",
"type-fest": "^2.16.0",
"typescript": "^5.2.2",
"vite": "^5.2.0",
"type-fest": "^2.16.0"
"vite": "^5.2.0"
}
}
1 change: 0 additions & 1 deletion Blink3.Activity/public/vite.svg

This file was deleted.

42 changes: 0 additions & 42 deletions Blink3.Activity/src/App.css

This file was deleted.

Loading

0 comments on commit d0583fd

Please sign in to comment.