2026-10-17 03:13:16 +02:00
using Microsoft.Extensions.Localization ;
using MongoDB.Entities ;
using PrivaPub.Infrastructure.Jobs ;
using PrivaPub.Models.Jobs ;
using PrivaPub.Models.User ;
using PrivaPub.Resources ;
using System.Security.Cryptography ;
using System.Text.Json ;
namespace PrivaPub.Services
{
public sealed record EmailVerificationPayload ( string VerificationId );
// Sends the code that proves a login owns the address it asked for. The code exists only in the email; the row keeps its
// hash. An address another login has verified meanwhile gets nothing, so the answer to the request never told whether
// the address was taken, and no stranger's inbox receives a code it didn't ask for twice.
2026-11-10 01:24:43 +01:00
public class EmailVerificationJob (
IMailer mailer ,
IStringLocalizer < GenericRes > localizer ,
ILogger < EmailVerificationJob > logger ) : IJobHandler
2026-10-17 03:13:16 +02:00
{
public const string Host = "email" ;
public JobKind Kind => JobKind . SendEmailVerification ;
public int Concurrency => 1 ;
public int MaxAttempts => 3 ;
public int PerHostLimit => 1 ;
2026-11-10 01:24:43 +01:00
[System.Diagnostics.CodeAnalysis.SuppressMessage("HouseRules", "HR0011", Justification = "A six-digit code with its leading zeros, not a number shown to a reader.")]
2026-10-17 03:13:16 +02:00
public static string NewCode () => RandomNumberGenerator . GetInt32 ( 0 , 1_000_000 ). ToString ( "D6" );
public async Task < JobOutcome > Handle ( Job job , CancellationToken token )
{
var payload = JsonSerializer . Deserialize < EmailVerificationPayload >( job . Payload );
var now = DateTime . UtcNow ;
var pending = string . IsNullOrEmpty ( payload ?. VerificationId ) ? default
: await DB . Default . Find < EmailVerification >(). Match ( v => v . ID == payload . VerificationId && v . ExpiresAt > now ). ExecuteFirstAsync ( token );
if ( pending == default )
return JobOutcome . Done ;
var user = await DB . Default . Find < RootUser >(). MatchID ( pending . RootUserId ). ExecuteFirstAsync ( token );
if ( user is not { DeletedAt : null , IsBanned : false })
return JobOutcome . Done ;
if ( await DB . Default . Find < RootUser >(). Match ( u => u . Email == pending . Email && u . IsEmailValidated && u . ID != user . ID && u . DeletedAt == null ). ExecuteAnyAsync ( token ))
return JobOutcome . Done ;
var code = NewCode ();
await DB . Default . Update < EmailVerification >(). MatchID ( pending . ID ). Modify ( v => v . CodeHash , RecoveryJob . Hash ( code )). ExecuteAsync ( token );
try
{
2026-11-10 01:24:43 +01:00
await mailer . Send ( pending . Email , localizer [ "PrivaPub - Confirm your email address" ],
string . Format ( localizer [
2026-10-17 03:13:16 +02:00
"Hello,\n\nThe PrivaPub login {0} asked to use this address. If it was you, enter this code within an hour:\n\n{1}\n\nIf it was not you, ignore this email: the address is not used." ],
user . UserName , code ), token );
return JobOutcome . Done ;
}
catch ( Exception ex ) when ( ex is not OperationCanceledException || ! token . IsCancellationRequested )
{
2026-11-10 01:24:43 +01:00
logger . LogWarning ( ex , "The verification email could not be sent" );
2026-10-17 03:13:16 +02:00
return JobOutcome . Retry ( "smtp" );
}
}
}
}