Files
SocialPub/PrivaPub/Services/EmailVerificationJob.cs
T

67 lines
2.8 KiB
C#
Raw Normal View History

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.
public class EmailVerificationJob(
IMailer mailer,
IStringLocalizer<GenericRes> localizer,
ILogger<EmailVerificationJob> logger) : IJobHandler
{
public const string Host = "email";
public JobKind Kind => JobKind.SendEmailVerification;
public int Concurrency => 1;
public int MaxAttempts => 3;
public int PerHostLimit => 1;
[System.Diagnostics.CodeAnalysis.SuppressMessage("HouseRules", "HR0011", Justification = "A six-digit code with its leading zeros, not a number shown to a reader.")]
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
{
await mailer.Send(pending.Email, localizer["PrivaPub - Confirm your email address"],
string.Format(localizer[
"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)
{
logger.LogWarning(ex, "The verification email could not be sent");
return JobOutcome.Retry("smtp");
}
}
}
}