Skip to content
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: 2 additions & 2 deletions .github/workflows/backend.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@ name: Backend CI

on:
push:
branches: [main]
branches: [main, develop]
paths:
- 'backend/**'
- '.github/workflows/backend.yml'
pull_request:
branches: [main]
branches: [main, develop]
paths:
- 'backend/**'
- '.github/workflows/backend.yml'
Expand Down
4 changes: 2 additions & 2 deletions .github/workflows/frontend.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@ name: Frontend CI

on:
push:
branches: [main]
branches: [main, develop]
paths:
- 'frontend/**'
- '.github/workflows/frontend.yml'
pull_request:
branches: [main]
branches: [main, develop]
paths:
- 'frontend/**'
- '.github/workflows/frontend.yml'
Expand Down
63 changes: 63 additions & 0 deletions backend/src/ExoAuth.Api/Controllers/AuthController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
using ExoAuth.Application.Features.Auth.Commands.DenyDevice;
using ExoAuth.Application.Features.Auth.Commands.ResendDeviceApproval;
using ExoAuth.Application.Features.Auth.Commands.ResendPasswordReset;
using ExoAuth.Application.Features.Auth.Commands.RequestMagicLink;
using ExoAuth.Application.Features.Auth.Commands.LoginWithMagicLink;
using ExoAuth.Application.Features.Auth.Models;
using ExoAuth.Application.Features.Auth.Queries.GetCurrentUser;
using ExoAuth.Application.Features.Auth.Queries.GetDevices;
Expand Down Expand Up @@ -312,6 +314,55 @@ public async Task<IActionResult> ResetPassword(ResetPasswordRequest request, Can
return ApiOk(result);
}

/// <summary>
/// Request a magic link email for passwordless login.
/// </summary>
[HttpPost("magic-link/request")]
[RateLimit("forgot-password")]
[ProducesResponseType(typeof(RequestMagicLinkResponse), StatusCodes.Status200OK)]
public async Task<IActionResult> RequestMagicLink(RequestMagicLinkRequest request, CancellationToken ct)
{
var command = new RequestMagicLinkCommand(
request.Email,
request.CaptchaToken,
HttpContext.Connection.RemoteIpAddress?.ToString()
);

var result = await Mediator.Send(command, ct);

return ApiOk(result);
}

/// <summary>
/// Login with magic link token.
/// </summary>
[HttpPost("magic-link/login")]
[RateLimit("sensitive")]
[ProducesResponseType(typeof(AuthResponse), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
public async Task<IActionResult> MagicLinkLogin(MagicLinkLoginRequest request, CancellationToken ct)
{
var command = new LoginWithMagicLinkCommand(
request.Token,
request.DeviceId,
request.DeviceFingerprint,
Request.Headers.UserAgent.ToString(),
HttpContext.Connection.RemoteIpAddress?.ToString(),
request.RememberMe
);

var result = await Mediator.Send(command, ct);

// Only set cookies when login is complete (not during MFA or device approval flow)
if (!result.MfaRequired && !result.MfaSetupRequired && !result.DeviceApprovalRequired)
{
SetAuthCookies(result.AccessToken!, result.RefreshToken!);
}

return ApiOk(result);
}

#region Devices

/// <summary>
Expand Down Expand Up @@ -813,6 +864,18 @@ public sealed record ResetPasswordRequest(
string NewPassword
);

public sealed record RequestMagicLinkRequest(
string Email,
string? CaptchaToken = null
);

public sealed record MagicLinkLoginRequest(
string Token,
string? DeviceId = null,
string? DeviceFingerprint = null,
bool RememberMe = false
);

public sealed record MfaSetupRequest(
string? SetupToken = null
);
Expand Down
2 changes: 2 additions & 0 deletions backend/src/ExoAuth.Api/ExoAuth.Api.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<NoWarn>$(NoWarn);1591</NoWarn>
</PropertyGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System.Reflection;
using System.Text;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
Expand All @@ -18,6 +19,11 @@ public static IServiceCollection AddSwaggerConfiguration(this IServiceCollection
Description = "Authentication and Authorization API"
});

// Include XML documentation
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
options.IncludeXmlComments(xmlPath, includeControllerXmlComments: true);

options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Name = "Authorization",
Expand Down
2 changes: 1 addition & 1 deletion backend/src/ExoAuth.Api/appsettings.Development.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
"Secure": false
},
"Captcha": {
"Enabled": true
"Enabled": false
},
"Serilog": {
"MinimumLevel": {
Expand Down
10 changes: 0 additions & 10 deletions backend/src/ExoAuth.Api/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,16 +19,6 @@
"RefreshTokenExpirationDays": 7,
"RememberMeExpirationDays": 30
},
"Email": {
"Provider": "SMTP",
"SmtpHost": "smtp.example.com",
"SmtpPort": 587,
"SmtpUsername": "",
"SmtpPassword": "",
"SmtpUseSsl": true,
"FromEmail": "noreply@exoauth.com",
"FromName": "ExoAuth"
},
"SystemInvite": {
"ExpirationHours": 24,
"BaseUrl": "http://localhost:5173"
Expand Down
11 changes: 11 additions & 0 deletions backend/src/ExoAuth.Application/Common/Exceptions/AuthException.cs
Original file line number Diff line number Diff line change
Expand Up @@ -494,3 +494,14 @@ public CaptchaExpiredException()
{
}
}

/// <summary>
/// Exception when magic link token is invalid.
/// </summary>
public sealed class MagicLinkTokenInvalidException : AuthException
{
public MagicLinkTokenInvalidException()
: base("MAGIC_LINK_TOKEN_INVALID", "Invalid or expired magic link token", 400)
{
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ public interface IAppDbContext
DbSet<SystemInvite> SystemInvites { get; }
DbSet<RefreshToken> RefreshTokens { get; }
DbSet<PasswordResetToken> PasswordResetTokens { get; }
DbSet<MagicLinkToken> MagicLinkTokens { get; }
DbSet<MfaBackupCode> MfaBackupCodes { get; }
DbSet<LoginPattern> LoginPatterns { get; }
DbSet<Device> Devices { get; }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,11 @@ public static class AuditActions
public const string PasswordResetCompleted = "system.password.reset_completed";
public const string PasswordChanged = "system.password.changed";

// Magic link actions
public const string MagicLinkRequested = "system.magic_link.requested";
public const string MagicLinkLogin = "system.magic_link.login";
public const string MagicLinkLoginFailed = "system.magic_link.login_failed";

// Session actions
public const string SessionCreated = "system.session.created";
public const string SessionRevoked = "system.session.revoked";
Expand Down
17 changes: 17 additions & 0 deletions backend/src/ExoAuth.Application/Common/Interfaces/IEmailService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,23 @@ Task SendPasswordResetAsync(
string language = "en-US",
CancellationToken cancellationToken = default);

/// <summary>
/// Sends a magic link email for passwordless login.
/// </summary>
/// <param name="email">The recipient email address.</param>
/// <param name="firstName">The recipient's first name.</param>
/// <param name="magicLinkToken">The magic link token for authentication.</param>
/// <param name="userId">The user ID for tracking.</param>
/// <param name="language">The language for the template (default: "en-US").</param>
/// <param name="cancellationToken">Cancellation token.</param>
Task SendMagicLinkAsync(
string email,
string firstName,
string magicLinkToken,
Guid userId,
string language = "en-US",
CancellationToken cancellationToken = default);

/// <summary>
/// Sends a password changed confirmation email.
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
using ExoAuth.Domain.Entities;

namespace ExoAuth.Application.Common.Interfaces;

/// <summary>
/// Service for managing magic link tokens.
/// </summary>
public interface IMagicLinkService
{
/// <summary>
/// Creates a new magic link token for a user.
/// Generates a URL token with collision prevention.
/// </summary>
/// <param name="userId">The user ID.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>The created token entity and the plain text token.</returns>
Task<MagicLinkResult> CreateMagicLinkAsync(Guid userId, CancellationToken cancellationToken = default);

/// <summary>
/// Validates a magic link token.
/// </summary>
/// <param name="token">The plain text token.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>The token entity if valid, null otherwise.</returns>
Task<MagicLinkToken?> ValidateTokenAsync(string token, CancellationToken cancellationToken = default);

/// <summary>
/// Marks a magic link token as used.
/// </summary>
/// <param name="token">The token entity.</param>
/// <param name="cancellationToken">Cancellation token.</param>
Task MarkAsUsedAsync(MagicLinkToken token, CancellationToken cancellationToken = default);

/// <summary>
/// Invalidates all pending magic link tokens for a user.
/// </summary>
/// <param name="userId">The user ID.</param>
/// <param name="cancellationToken">Cancellation token.</param>
Task InvalidateAllTokensAsync(Guid userId, CancellationToken cancellationToken = default);
}

/// <summary>
/// Result of creating a magic link token.
/// </summary>
public sealed record MagicLinkResult(
MagicLinkToken Entity,
string Token
);
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
using ExoAuth.Application.Features.Auth.Models;
using Mediator;

namespace ExoAuth.Application.Features.Auth.Commands.LoginWithMagicLink;

/// <summary>
/// Command to login a user with a magic link token.
/// </summary>
public sealed record LoginWithMagicLinkCommand(
string Token,
string? DeviceId = null,
string? DeviceFingerprint = null,
string? UserAgent = null,
string? IpAddress = null,
bool RememberMe = false
) : ICommand<AuthResponse>;
Loading
Loading