2024-12-09 21:11:46 +01:00
|
|
|
// Copyright (C) 2023-present sam/u1f320 (vulpine.solutions)
|
|
|
|
//
|
|
|
|
// This program is free software: you can redistribute it and/or modify
|
|
|
|
// it under the terms of the GNU Affero General Public License as published
|
|
|
|
// by the Free Software Foundation, either version 3 of the License, or
|
|
|
|
// (at your option) any later version.
|
|
|
|
//
|
|
|
|
// This program is distributed in the hope that it will be useful,
|
|
|
|
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
// GNU Affero General Public License for more details.
|
|
|
|
//
|
|
|
|
// You should have received a copy of the GNU Affero General Public License
|
|
|
|
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
2024-11-03 13:53:16 +01:00
|
|
|
using System.Net;
|
|
|
|
using System.Web;
|
|
|
|
using EntityFramework.Exceptions.Common;
|
2024-06-10 16:25:49 +02:00
|
|
|
using Foxnouns.Backend.Database;
|
2024-06-12 16:19:49 +02:00
|
|
|
using Foxnouns.Backend.Database.Models;
|
2024-12-08 20:17:30 +01:00
|
|
|
using Foxnouns.Backend.Dto;
|
2024-06-13 02:23:55 +02:00
|
|
|
using Foxnouns.Backend.Extensions;
|
2024-11-03 13:53:16 +01:00
|
|
|
using Foxnouns.Backend.Middleware;
|
2024-06-12 16:19:49 +02:00
|
|
|
using Foxnouns.Backend.Services;
|
2024-11-03 02:07:07 +01:00
|
|
|
using Foxnouns.Backend.Services.Auth;
|
2024-06-13 02:23:55 +02:00
|
|
|
using Foxnouns.Backend.Utils;
|
2024-09-14 16:37:52 +02:00
|
|
|
using JetBrains.Annotations;
|
2024-06-10 16:25:49 +02:00
|
|
|
using Microsoft.AspNetCore.Mvc;
|
2024-06-13 02:23:55 +02:00
|
|
|
using Microsoft.EntityFrameworkCore;
|
2024-06-12 16:19:49 +02:00
|
|
|
using NodaTime;
|
2024-06-10 16:25:49 +02:00
|
|
|
|
|
|
|
namespace Foxnouns.Backend.Controllers.Authentication;
|
|
|
|
|
2024-10-02 00:15:14 +02:00
|
|
|
[Route("/api/internal/auth/discord")]
|
2024-12-10 15:28:44 +01:00
|
|
|
[ApiExplorerSettings(IgnoreApi = true)]
|
2024-06-12 16:19:49 +02:00
|
|
|
public class DiscordAuthController(
|
2024-09-14 16:37:52 +02:00
|
|
|
[UsedImplicitly] Config config,
|
2024-06-12 16:19:49 +02:00
|
|
|
ILogger logger,
|
|
|
|
DatabaseContext db,
|
2024-09-09 14:50:00 +02:00
|
|
|
KeyCacheService keyCacheService,
|
|
|
|
AuthService authService,
|
2024-11-03 02:07:07 +01:00
|
|
|
RemoteAuthService remoteAuthService
|
2024-10-02 00:28:07 +02:00
|
|
|
) : ApiControllerBase
|
2024-06-10 16:25:49 +02:00
|
|
|
{
|
2024-09-04 14:25:44 +02:00
|
|
|
private readonly ILogger _logger = logger.ForContext<DiscordAuthController>();
|
|
|
|
|
2024-06-12 16:19:49 +02:00
|
|
|
[HttpPost("callback")]
|
2024-11-03 02:07:07 +01:00
|
|
|
[ProducesResponseType<CallbackResponse>(StatusCodes.Status200OK)]
|
2024-12-08 20:17:30 +01:00
|
|
|
public async Task<IActionResult> CallbackAsync([FromBody] CallbackRequest req)
|
2024-06-12 16:19:49 +02:00
|
|
|
{
|
|
|
|
CheckRequirements();
|
2024-11-02 21:23:49 +01:00
|
|
|
await keyCacheService.ValidateAuthStateAsync(req.State);
|
2024-06-12 16:19:49 +02:00
|
|
|
|
2024-12-08 15:07:25 +01:00
|
|
|
RemoteAuthService.RemoteUser remoteUser = await remoteAuthService.RequestDiscordTokenAsync(
|
|
|
|
req.Code
|
|
|
|
);
|
|
|
|
User? user = await authService.AuthenticateUserAsync(AuthType.Discord, remoteUser.Id);
|
2024-10-02 00:28:07 +02:00
|
|
|
if (user != null)
|
2024-11-03 02:07:07 +01:00
|
|
|
return Ok(await authService.GenerateUserTokenAsync(user));
|
2024-06-12 16:19:49 +02:00
|
|
|
|
2024-10-02 00:28:07 +02:00
|
|
|
_logger.Debug(
|
|
|
|
"Discord user {Username} ({Id}) authenticated with no local account",
|
|
|
|
remoteUser.Username,
|
|
|
|
remoteUser.Id
|
|
|
|
);
|
2024-06-12 16:19:49 +02:00
|
|
|
|
2024-12-08 15:07:25 +01:00
|
|
|
string ticket = AuthUtils.RandomToken();
|
2024-10-02 00:28:07 +02:00
|
|
|
await keyCacheService.SetKeyAsync(
|
|
|
|
$"discord:{ticket}",
|
|
|
|
remoteUser,
|
2024-11-02 21:23:49 +01:00
|
|
|
Duration.FromMinutes(20)
|
2024-10-02 00:28:07 +02:00
|
|
|
);
|
|
|
|
|
2024-12-08 15:07:25 +01:00
|
|
|
return Ok(new CallbackResponse(false, ticket, remoteUser.Username, null, null, null));
|
2024-06-13 02:23:55 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
[HttpPost("register")]
|
2024-12-08 20:17:30 +01:00
|
|
|
[ProducesResponseType<AuthResponse>(StatusCodes.Status200OK)]
|
|
|
|
public async Task<IActionResult> RegisterAsync([FromBody] OauthRegisterRequest req)
|
2024-06-13 02:23:55 +02:00
|
|
|
{
|
2024-12-08 15:07:25 +01:00
|
|
|
RemoteAuthService.RemoteUser? remoteUser =
|
|
|
|
await keyCacheService.GetKeyAsync<RemoteAuthService.RemoteUser>(
|
|
|
|
$"discord:{req.Ticket}"
|
|
|
|
);
|
2024-10-02 00:28:07 +02:00
|
|
|
if (remoteUser == null)
|
|
|
|
throw new ApiError.BadRequest("Invalid ticket", "ticket", req.Ticket);
|
|
|
|
if (
|
|
|
|
await db.AuthMethods.AnyAsync(a =>
|
|
|
|
a.AuthType == AuthType.Discord && a.RemoteId == remoteUser.Id
|
|
|
|
)
|
|
|
|
)
|
2024-06-13 02:23:55 +02:00
|
|
|
{
|
2024-10-02 00:28:07 +02:00
|
|
|
_logger.Error(
|
|
|
|
"Discord user {Id} has valid ticket but is already linked to an existing account",
|
|
|
|
remoteUser.Id
|
|
|
|
);
|
2024-09-14 16:37:52 +02:00
|
|
|
throw new ApiError.BadRequest("Invalid ticket", "ticket", req.Ticket);
|
2024-06-13 02:23:55 +02:00
|
|
|
}
|
|
|
|
|
2024-12-08 15:07:25 +01:00
|
|
|
User user = await authService.CreateUserWithRemoteAuthAsync(
|
2024-10-02 00:28:07 +02:00
|
|
|
req.Username,
|
|
|
|
AuthType.Discord,
|
|
|
|
remoteUser.Id,
|
|
|
|
remoteUser.Username
|
|
|
|
);
|
2024-06-13 02:23:55 +02:00
|
|
|
|
2024-11-03 02:07:07 +01:00
|
|
|
return Ok(await authService.GenerateUserTokenAsync(user));
|
2024-06-12 16:19:49 +02:00
|
|
|
}
|
|
|
|
|
2024-11-03 13:53:16 +01:00
|
|
|
[HttpGet("add-account")]
|
|
|
|
[Authorize("*")]
|
|
|
|
public async Task<IActionResult> AddDiscordAccountAsync()
|
|
|
|
{
|
|
|
|
CheckRequirements();
|
|
|
|
|
2024-12-08 15:07:25 +01:00
|
|
|
string state = await remoteAuthService.ValidateAddAccountRequestAsync(
|
2024-12-04 01:48:52 +01:00
|
|
|
CurrentUser!.Id,
|
|
|
|
AuthType.Discord
|
2024-11-03 13:53:16 +01:00
|
|
|
);
|
|
|
|
|
2024-12-08 15:07:25 +01:00
|
|
|
string url =
|
2024-12-08 15:17:18 +01:00
|
|
|
"https://discord.com/oauth2/authorize?response_type=code"
|
2024-11-03 13:53:16 +01:00
|
|
|
+ $"&client_id={config.DiscordAuth.ClientId}&scope=identify"
|
|
|
|
+ $"&prompt=none&state={state}"
|
|
|
|
+ $"&redirect_uri={HttpUtility.UrlEncode($"{config.BaseUrl}/auth/callback/discord")}";
|
|
|
|
|
2024-12-08 20:17:30 +01:00
|
|
|
return Ok(new SingleUrlResponse(url));
|
2024-11-03 13:53:16 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
[HttpPost("add-account/callback")]
|
|
|
|
[Authorize("*")]
|
2024-12-08 20:17:30 +01:00
|
|
|
public async Task<IActionResult> AddAccountCallbackAsync([FromBody] CallbackRequest req)
|
2024-11-03 13:53:16 +01:00
|
|
|
{
|
|
|
|
CheckRequirements();
|
|
|
|
|
2024-12-04 01:48:52 +01:00
|
|
|
await remoteAuthService.ValidateAddAccountStateAsync(
|
|
|
|
req.State,
|
|
|
|
CurrentUser!.Id,
|
|
|
|
AuthType.Discord
|
|
|
|
);
|
2024-11-03 13:53:16 +01:00
|
|
|
|
2024-12-08 15:07:25 +01:00
|
|
|
RemoteAuthService.RemoteUser remoteUser = await remoteAuthService.RequestDiscordTokenAsync(
|
|
|
|
req.Code
|
|
|
|
);
|
2024-11-03 13:53:16 +01:00
|
|
|
try
|
|
|
|
{
|
2024-12-08 15:07:25 +01:00
|
|
|
AuthMethod authMethod = await authService.AddAuthMethodAsync(
|
2024-11-03 13:53:16 +01:00
|
|
|
CurrentUser.Id,
|
|
|
|
AuthType.Discord,
|
|
|
|
remoteUser.Id,
|
|
|
|
remoteUser.Username
|
|
|
|
);
|
|
|
|
_logger.Debug(
|
|
|
|
"Added new Discord auth method {AuthMethodId} to user {UserId}",
|
|
|
|
authMethod.Id,
|
|
|
|
CurrentUser.Id
|
|
|
|
);
|
|
|
|
|
|
|
|
return Ok(
|
2024-12-08 20:17:30 +01:00
|
|
|
new AddOauthAccountResponse(
|
2024-11-03 13:53:16 +01:00
|
|
|
authMethod.Id,
|
|
|
|
AuthType.Discord,
|
|
|
|
authMethod.RemoteId,
|
|
|
|
authMethod.RemoteUsername
|
|
|
|
)
|
|
|
|
);
|
|
|
|
}
|
|
|
|
catch (UniqueConstraintException)
|
|
|
|
{
|
|
|
|
throw new ApiError(
|
|
|
|
"That account is already linked.",
|
|
|
|
HttpStatusCode.BadRequest,
|
|
|
|
ErrorCode.AccountAlreadyLinked
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-06-12 03:47:20 +02:00
|
|
|
private void CheckRequirements()
|
2024-06-10 16:25:49 +02:00
|
|
|
{
|
2024-06-12 16:19:49 +02:00
|
|
|
if (!config.DiscordAuth.Enabled)
|
2024-12-08 15:07:25 +01:00
|
|
|
{
|
2024-10-02 00:28:07 +02:00
|
|
|
throw new ApiError.BadRequest(
|
|
|
|
"Discord authentication is not enabled on this instance."
|
|
|
|
);
|
2024-12-08 15:07:25 +01:00
|
|
|
}
|
2024-06-10 16:25:49 +02:00
|
|
|
}
|
2024-10-02 00:28:07 +02:00
|
|
|
}
|