using System;
using System.Threading.Tasks;
using CellularManagement.Domain.Services;
using Microsoft.Extensions.Caching.Distributed;
using System.Text.Json;
namespace CellularManagement.Infrastructure.Services;
///
/// 邮箱验证码服务
/// 提供验证码生成、发送和验证的具体实现
///
public class EmailVerificationService : IEmailVerificationService
{
private readonly IEmailService _emailService;
private readonly IDistributedCache _cache;
private const string CacheKeyPrefix = "EmailVerification_";
private const int VerificationCodeLength = 6;
private const int VerificationCodeExpirationMinutes = 5;
///
/// 构造函数
///
/// 邮箱服务
/// 分布式缓存
public EmailVerificationService(IEmailService emailService, IDistributedCache cache)
{
_emailService = emailService;
_cache = cache;
}
///
/// 生成并发送验证码
///
/// 邮箱地址
/// 是否发送成功
public async Task GenerateAndSendVerificationCodeAsync(string email)
{
if (!_emailService.ValidateEmail(email))
{
return false;
}
// 生成6位数字验证码
var verificationCode = GenerateVerificationCode();
// 将验证码保存到缓存
var cacheKey = $"{CacheKeyPrefix}{email}";
var cacheValue = JsonSerializer.Serialize(new
{
Code = verificationCode,
CreatedAt = DateTime.UtcNow
});
await _cache.SetStringAsync(
cacheKey,
cacheValue,
new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(VerificationCodeExpirationMinutes)
});
// 发送验证码邮件
return await _emailService.SendVerificationCodeAsync(email, verificationCode);
}
///
/// 验证验证码
///
/// 邮箱地址
/// 验证码
/// 验证结果
public async Task VerifyCodeAsync(string email, string code)
{
var cacheKey = $"{CacheKeyPrefix}{email}";
var cachedValue = await _cache.GetStringAsync(cacheKey);
if (string.IsNullOrEmpty(cachedValue))
{
return false;
}
var verificationData = JsonSerializer.Deserialize(cachedValue);
if (verificationData == null)
{
return false;
}
// 验证码是否过期
if (DateTime.UtcNow - verificationData.CreatedAt > TimeSpan.FromMinutes(VerificationCodeExpirationMinutes))
{
await _cache.RemoveAsync(cacheKey);
return false;
}
// 验证码是否匹配
if (verificationData.Code != code)
{
return false;
}
// 验证成功后删除缓存
await _cache.RemoveAsync(cacheKey);
return true;
}
///
/// 生成验证码
///
private string GenerateVerificationCode()
{
var random = new Random();
var code = string.Empty;
for (int i = 0; i < VerificationCodeLength; i++)
{
code += random.Next(0, 10).ToString();
}
return code;
}
///
/// 验证数据
///
private class VerificationData
{
public string Code { get; set; } = string.Empty;
public DateTime CreatedAt { get; set; }
}
}