XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

STHApplication

【MAUI】寄当家——安卓端交易管理系统

公开
关注 0 Fork 0 Star 0
UTF-8
using System.Globalization;
using System.Net.Http.Json;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using static JiDangJia.Server.ServerStore;

namespace JiDangJia.Server;

public sealed record PhoneCodeRequest(string Phone);
public sealed record PhoneBindRequest(string Phone,string Code);
public interface IPhoneCodeSender { bool Configured { get; } Task Send(string phone,string code,CancellationToken ct); }
// Tencent Cloud SendSms v2021-01-11. Only a phone and OTP leave this service.
public sealed class TencentPhoneCodeSender(IConfiguration configuration,HttpClient? client=null) : IPhoneCodeSender
{
    private string Config(string name)=>configuration[name]??"";
    public bool Configured=>new[]{"TENCENTCLOUD_SECRET_ID","TENCENTCLOUD_SECRET_KEY","JDJ_SMS_APP_ID","JDJ_SMS_SIGN","JDJ_SMS_TEMPLATE_ID"}.All(k=>Config(k).Length>0);
    private static string Hex(byte[] value)=>Convert.ToHexString(value).ToLowerInvariant();
    private static byte[] Hmac(byte[] key,string value)=>HMACSHA256.HashData(key,Encoding.UTF8.GetBytes(value));
    public async Task Send(string phone,string code,CancellationToken ct)
    {
        if(!Configured)throw new CommunityException(503,"腾讯云短信尚未配置,请联系管理员人工核验手机号");
        var parameters=Config("JDJ_SMS_TEMPLATE_MINUTES")=="true"?new[]{code,"5"}:new[]{code};
        var payload=JsonSerializer.Serialize(new{PhoneNumberSet=new[]{"+86"+phone},SmsSdkAppId=Config("JDJ_SMS_APP_ID"),SignName=Config("JDJ_SMS_SIGN"),TemplateId=Config("JDJ_SMS_TEMPLATE_ID"),TemplateParamSet=parameters});
        var timestamp=DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString(CultureInfo.InvariantCulture);var date=DateTime.UtcNow.ToString("yyyy-MM-dd",CultureInfo.InvariantCulture);
        const string host="sms.tencentcloudapi.com",headers="content-type;host;x-tc-action";
        var canonical="POST\n/\n\ncontent-type:application/json; charset=utf-8\nhost:"+host+"\nx-tc-action:sendsms\n\n"+headers+"\n"+Hex(SHA256.HashData(Encoding.UTF8.GetBytes(payload)));
        var scope=date+"/sms/tc3_request";var sign=Hmac(Hmac(Hmac(Encoding.UTF8.GetBytes("TC3"+Config("TENCENTCLOUD_SECRET_KEY")),date),"sms"),"tc3_request");
        var signature=Hex(Hmac(sign,"TC3-HMAC-SHA256\n"+timestamp+"\n"+scope+"\n"+Hex(SHA256.HashData(Encoding.UTF8.GetBytes(canonical)))));
        using var request=new HttpRequestMessage(HttpMethod.Post,"https://"+host){Content=new StringContent(payload,Encoding.UTF8,"application/json")};
        request.Headers.TryAddWithoutValidation("Authorization","TC3-HMAC-SHA256 Credential="+Config("TENCENTCLOUD_SECRET_ID")+"/"+scope+", SignedHeaders="+headers+", Signature="+signature);
        request.Headers.Add("X-TC-Action","SendSms");request.Headers.Add("X-TC-Version","2021-01-11");request.Headers.Add("X-TC-Timestamp",timestamp);request.Headers.Add("X-TC-Region",Config("JDJ_SMS_REGION") is {Length:>0} region?region:"ap-guangzhou");
        using var ownedClient=client is null?new HttpClient{Timeout=TimeSpan.FromSeconds(20)}:null;using var response=await (client??ownedClient!).SendAsync(request,ct);
        if(!response.IsSuccessStatusCode)throw new CommunityException(502,"短信服务暂不可用,请稍后重试");using var data=await JsonDocument.ParseAsync(await response.Content.ReadAsStreamAsync(ct),cancellationToken:ct);
        var result=data.RootElement.GetProperty("Response");if(!result.TryGetProperty("SendStatusSet",out var statuses)||statuses.GetArrayLength()!=1||statuses[0].GetProperty("Code").GetString()!="Ok")throw new CommunityException(502,"腾讯云短信发送未成功,请管理员检查签名、模板与短信额度");
    }
}
public sealed class PhoneVerification
{
    private readonly ServerStore store;private readonly IPhoneCodeSender sender;
    public PhoneVerification(ServerStore store,IPhoneCodeSender sender)
    {
        this.store=store;this.sender=sender;store.Write(c=>Exec(c,"CREATE TABLE IF NOT EXISTS PhoneChallenges(accountId TEXT PRIMARY KEY,phone TEXT NOT NULL,salt TEXT NOT NULL,codeHash TEXT NOT NULL,state TEXT NOT NULL,expiresAt TEXT NOT NULL,createdAt TEXT NOT NULL,attempts INTEGER NOT NULL DEFAULT 0); CREATE TABLE IF NOT EXISTS PhoneSendHistory(accountId TEXT NOT NULL,phone TEXT NOT NULL,createdAt TEXT NOT NULL)"));
    }
    private static string Phone(string? phone){if(phone is null||!Regex.IsMatch(phone,"^1[3-9][0-9]{9}$"))throw new ArgumentException("请填写有效的 11 位手机号");return phone;}
    public object Status(Account actor)=>store.Read(c=>{var a=SafetyAccount(c,actor.Id);var phone=Text(a,"phone");return new{configured=sender.Configured,phone=phone.Length==11?phone[..3]+"****"+phone[^4..]:"",method=Text(a,"phoneMethod")};});
    public async Task<object> Send(Account actor,PhoneCodeRequest request,CancellationToken ct)
    {
        var phone=Phone(request.Phone);if(!sender.Configured)throw new CommunityException(503,"腾讯云短信暂未配置,可由管理员人工核验并绑定手机号");var code=RandomNumberGenerator.GetInt32(100000,1000000).ToString();var salt=Guid.NewGuid().ToString("N");var now=Now;
        store.Write(c=>{SafetyAccount(c,actor.Id);if(Rows(c,"SELECT id FROM Accounts WHERE phone=@p0 AND id<>@p1",phone,actor.Id).Count>0)throw new CommunityException(409,"手机号不可绑定,请联系管理员");
            if(Rows(c,"SELECT accountId FROM PhoneSendHistory WHERE (accountId=@p0 OR phone=@p1) AND createdAt>@p2",actor.Id,phone,DateTime.UtcNow.AddSeconds(-60).ToString("O")).Count>0)throw new CommunityException(429,"请等待 60 秒再发送");
            if(Rows(c,"SELECT accountId FROM PhoneSendHistory WHERE (accountId=@p0 OR phone=@p1) AND createdAt>@p2",actor.Id,phone,DateTime.UtcNow.AddDays(-1).ToString("O")).Count>=5)throw new CommunityException(429,"今日验证码次数已用完");
            Exec(c,"INSERT INTO PhoneSendHistory VALUES(@p0,@p1,@p2)",actor.Id,phone,now);Exec(c,"INSERT INTO PhoneChallenges VALUES(@p0,@p1,@p2,@p3,'SENDING',@p4,@p5,0) ON CONFLICT(accountId) DO UPDATE SET phone=excluded.phone,salt=excluded.salt,codeHash=excluded.codeHash,state='SENDING',expiresAt=excluded.expiresAt,createdAt=excluded.createdAt,attempts=0",actor.Id,phone,salt,Hash(actor.Id+salt+code),DateTime.UtcNow.AddMinutes(5).ToString("O"),now);return 0;});
        try{await sender.Send(phone,code,ct);store.Write(c=>Exec(c,"UPDATE PhoneChallenges SET state='SENT' WHERE accountId=@p0 AND salt=@p1",actor.Id,salt));return new{ok=true,retryAfter=60,expiresIn=300};}
        catch{store.Write(c=>Exec(c,"UPDATE PhoneChallenges SET state='FAILED',codeHash='' WHERE accountId=@p0 AND salt=@p1",actor.Id,salt));throw;}
    }
    public object Bind(Account actor,PhoneBindRequest request)
    {
        var phone=Phone(request.Phone);bool success=store.Write(c=>{var account=SafetyAccount(c,actor.Id);
#if COMMUNITY_APP
        if(Text(account,"identityStatus")=="APPROVED"&&Text(account,"phone")!=phone)throw new CommunityException(409,"请先提交新手机号的认证资料,重新审核后再更换已认证手机号");
#endif
        var r=Rows(c,"SELECT * FROM PhoneChallenges WHERE accountId=@p0 AND phone=@p1 AND state='SENT' AND expiresAt>@p2 AND attempts<5",actor.Id,phone,Now).FirstOrDefault();if(r is null)return false;
            Exec(c,"UPDATE PhoneChallenges SET attempts=attempts+1 WHERE accountId=@p0",actor.Id);if(request.Code is null||!Regex.IsMatch(request.Code,"^[0-9]{6}$")||!CryptographicOperations.FixedTimeEquals(Encoding.ASCII.GetBytes(Hash(actor.Id+Text(r,"salt")+request.Code)),Encoding.ASCII.GetBytes(Text(r,"codeHash"))))return false;
            if(Rows(c,"SELECT id FROM Accounts WHERE phone=@p0 AND id<>@p1",phone,actor.Id).Count>0)throw new CommunityException(409,"手机号不可绑定,请联系管理员");Exec(c,"UPDATE Accounts SET phone=@p0,phoneMethod='SMS' WHERE id=@p1",phone,actor.Id);Exec(c,"UPDATE PhoneChallenges SET state='USED',codeHash='' WHERE accountId=@p0",actor.Id);return true;});
        if(!success)throw new CommunityException(403,"验证码错误、已使用、已过期或尝试次数已用完");return new{ok=true};
    }
}