diff --git a/DysonNetwork.Sphere/.gitignore b/DysonNetwork.Sphere/.gitignore index dea484d..eccb44f 100644 --- a/DysonNetwork.Sphere/.gitignore +++ b/DysonNetwork.Sphere/.gitignore @@ -1,5 +1,6 @@ Keys Uploads +DataProtection-Keys node_modules bun.lock diff --git a/DysonNetwork.Sphere/Auth/OpenId/ConnectionController.cs b/DysonNetwork.Sphere/Auth/OpenId/ConnectionController.cs index ba93e44..ecaad6f 100644 --- a/DysonNetwork.Sphere/Auth/OpenId/ConnectionController.cs +++ b/DysonNetwork.Sphere/Auth/OpenId/ConnectionController.cs @@ -192,32 +192,51 @@ public class ConnectionController( } catch (Exception ex) { - return BadRequest($"Error processing callback: {ex.Message}"); + return BadRequest($"Error processing {provider} authentication: {ex.Message}"); } + if (string.IsNullOrEmpty(userInfo.UserId)) + { + return BadRequest($"{provider} did not return a valid user identifier."); + } + + // Check if this provider account is already connected to any user var existingConnection = await db.AccountConnections .FirstOrDefaultAsync(c => c.Provider.Equals(provider, StringComparison.OrdinalIgnoreCase) && c.ProvidedIdentifier == userInfo.UserId); + // If it's connected to a different user, return error if (existingConnection != null && existingConnection.AccountId != accountId) { return BadRequest($"This {provider} account is already linked to another user."); } - var userConnection = await db.AccountConnections - .FirstOrDefaultAsync(c => - c.AccountId == accountId && c.Provider.Equals(provider, StringComparison.OrdinalIgnoreCase)); + // Check if the current user already has this provider connected + var userHasProvider = await db.AccountConnections + .AnyAsync(c => + c.AccountId == accountId && + c.Provider.Equals(provider, StringComparison.OrdinalIgnoreCase)); - var clock = SystemClock.Instance; - if (userConnection != null) + if (userHasProvider) { - userConnection.AccessToken = userInfo.AccessToken; - userConnection.RefreshToken = userInfo.RefreshToken; - userConnection.LastUsedAt = clock.GetCurrentInstant(); + // Update existing connection with new tokens + var connection = await db.AccountConnections + .FirstOrDefaultAsync(c => + c.AccountId == accountId && + c.Provider.Equals(provider, StringComparison.OrdinalIgnoreCase)); + + if (connection != null) + { + connection.AccessToken = userInfo.AccessToken; + connection.RefreshToken = userInfo.RefreshToken; + connection.LastUsedAt = SystemClock.Instance.GetCurrentInstant(); + connection.Meta = userInfo.ToMetadata(); + } } else { + // Create new connection db.AccountConnections.Add(new AccountConnection { AccountId = accountId, @@ -225,17 +244,26 @@ public class ConnectionController( ProvidedIdentifier = userInfo.UserId!, AccessToken = userInfo.AccessToken, RefreshToken = userInfo.RefreshToken, - LastUsedAt = clock.GetCurrentInstant(), + LastUsedAt = SystemClock.Instance.GetCurrentInstant(), Meta = userInfo.ToMetadata(), }); } - await db.SaveChangesAsync(); + try + { + await db.SaveChangesAsync(); + } + catch (DbUpdateException ex) + { + return StatusCode(500, $"Failed to save {provider} connection. Please try again."); + } + // Clean up and redirect var returnUrl = HttpContext.Session.GetString($"oidc_return_url_{callbackData.State}"); HttpContext.Session.Remove($"oidc_return_url_{callbackData.State}"); + HttpContext.Session.Remove($"oidc_state_{callbackData.State}"); - return Redirect(string.IsNullOrEmpty(returnUrl) ? "/" : returnUrl); + return Redirect(string.IsNullOrEmpty(returnUrl) ? "/settings/connections" : returnUrl); } private async Task HandleLoginOrRegistration( diff --git a/DysonNetwork.Sphere/Auth/OpenId/OidcController.cs b/DysonNetwork.Sphere/Auth/OpenId/OidcController.cs index 4e42927..ada8bc1 100644 --- a/DysonNetwork.Sphere/Auth/OpenId/OidcController.cs +++ b/DysonNetwork.Sphere/Auth/OpenId/OidcController.cs @@ -23,7 +23,7 @@ public class OidcController( { var oidcService = GetOidcService(provider); - // If user is already authenticated, treat as an account connection request + // If the user is already authenticated, treat as an account connection request if (HttpContext.Items["CurrentUser"] is Account.Account currentUser) { var state = Guid.NewGuid().ToString(); diff --git a/DysonNetwork.Sphere/DysonNetwork.Sphere.csproj b/DysonNetwork.Sphere/DysonNetwork.Sphere.csproj index 084f9d2..0b42478 100644 --- a/DysonNetwork.Sphere/DysonNetwork.Sphere.csproj +++ b/DysonNetwork.Sphere/DysonNetwork.Sphere.csproj @@ -16,38 +16,39 @@ - - - - - - + + + + + + - - - - + + + + + all runtime; build; native; contentfiles; analyzers; buildtransitive - + all runtime; build; native; contentfiles; analyzers; buildtransitive - - - - + + + + - + - - - - - + + + + + @@ -59,18 +60,18 @@ - - - + + + - - - + + + @@ -80,7 +81,7 @@ - + @@ -151,13 +152,13 @@ - <_ContentIncludedByDefault Remove="app\publish\appsettings.json"/> - <_ContentIncludedByDefault Remove="app\publish\DysonNetwork.Sphere.deps.json"/> - <_ContentIncludedByDefault Remove="app\publish\DysonNetwork.Sphere.runtimeconfig.json"/> - <_ContentIncludedByDefault Remove="app\publish\DysonNetwork.Sphere.staticwebassets.endpoints.json"/> - <_ContentIncludedByDefault Remove="app\publish\Keys\Solian.json"/> - <_ContentIncludedByDefault Remove="app\publish\package-lock.json"/> - <_ContentIncludedByDefault Remove="app\publish\package.json"/> + <_ContentIncludedByDefault Remove="app\publish\appsettings.json" /> + <_ContentIncludedByDefault Remove="app\publish\DysonNetwork.Sphere.deps.json" /> + <_ContentIncludedByDefault Remove="app\publish\DysonNetwork.Sphere.runtimeconfig.json" /> + <_ContentIncludedByDefault Remove="app\publish\DysonNetwork.Sphere.staticwebassets.endpoints.json" /> + <_ContentIncludedByDefault Remove="app\publish\Keys\Solian.json" /> + <_ContentIncludedByDefault Remove="app\publish\package-lock.json" /> + <_ContentIncludedByDefault Remove="app\publish\package.json" /> diff --git a/DysonNetwork.Sphere/Program.cs b/DysonNetwork.Sphere/Program.cs index e1515d7..4b4272d 100644 --- a/DysonNetwork.Sphere/Program.cs +++ b/DysonNetwork.Sphere/Program.cs @@ -35,6 +35,7 @@ using Quartz; using StackExchange.Redis; using tusdotnet; using tusdotnet.Stores; +using Microsoft.AspNetCore.DataProtection; var builder = WebApplication.CreateBuilder(args); @@ -90,12 +91,41 @@ builder.Services.AddSingleton(); builder.Services.AddHttpClient(); +// Configure Data Protection for persistent session keys +var keysDirectory = Path.Combine(builder.Environment.ContentRootPath, "DataProtection-Keys"); +Directory.CreateDirectory(keysDirectory); + +builder.Services.AddDataProtection() + .PersistKeysToFileSystem(new DirectoryInfo(keysDirectory)) + .SetApplicationName("DysonNetwork.Sphere"); + +// Configure cookie policy to be essential for session +builder.Services.Configure(options => +{ + options.CheckConsentNeeded = _ => false; // Required for session to work without consent + options.MinimumSameSitePolicy = SameSiteMode.Lax; +}); + +// Add session with consistent cookie settings +builder.Services.AddSession(options => +{ + options.Cookie.Name = "_dynses"; + options.Cookie.HttpOnly = true; + options.Cookie.IsEssential = true; + options.IdleTimeout = TimeSpan.FromMinutes(30); +}); + // Register OIDC services builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); builder.Services.AddControllers().AddJsonOptions(options => { options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower;