增加 新版本登录请求
This commit is contained in:
1 parent
afeb7e5d90
commit
b28940c02d
10 files changed
+865
-592
No files matched your search
@@ -0,0 +1,17 @@
|
||||
using CsharpHttpHelper;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace Work.Store.Api;
|
||||
|
||||
/// <summary>保留业务错误数据,供批量接口识别部分失败项。</summary>
|
||||
public sealed class ApiException : HttpException
|
||||
{
|
||||
public int? Code { get; }
|
||||
public JToken ResponseData { get; }
|
||||
|
||||
public ApiException(string message, int? code, JToken responseData) : base(message)
|
||||
{
|
||||
Code = code;
|
||||
ResponseData = responseData;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
using CsharpHttpHelper;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace Work.Store.Api;
|
||||
|
||||
/// <summary>管理 API 的统一 HTTP 出口,负责 JSON、Bearer 认证和错误处理。</summary>
|
||||
public sealed class ApiTransport
|
||||
{
|
||||
private readonly string _baseUrl;
|
||||
private string _token;
|
||||
private Func<string> _login;
|
||||
internal object SessionGate { get; } = new object();
|
||||
|
||||
internal void SetSession(string token, Func<string> login)
|
||||
{
|
||||
lock (SessionGate)
|
||||
{
|
||||
_token = token;
|
||||
_login = login;
|
||||
}
|
||||
}
|
||||
|
||||
public ApiTransport(string baseUrl)
|
||||
{
|
||||
if (!Uri.TryCreate(baseUrl, UriKind.Absolute, out var uri) ||
|
||||
(uri.Scheme != "http" && uri.Scheme != "https") ||
|
||||
uri.UserInfo.Length != 0 || uri.Query.Length != 0 || uri.Fragment.Length != 0)
|
||||
throw new ArgumentException("必须提供无凭据、查询参数和片段的 HTTP(S) 根地址。", nameof(baseUrl));
|
||||
|
||||
_baseUrl = uri.AbsoluteUri.TrimEnd('/') + "/";
|
||||
}
|
||||
|
||||
/// <summary>仅存于内存;手动赋值会清除自动登录凭据,设为 null 退出本地会话。</summary>
|
||||
public string Token
|
||||
{
|
||||
get { lock (SessionGate) return _token; }
|
||||
set
|
||||
{
|
||||
if (value != null && (string.IsNullOrWhiteSpace(value) || value.IndexOfAny(new[] { '\r', '\n' }) >= 0))
|
||||
throw new ArgumentException("Token 不能为空白或包含换行。", nameof(value));
|
||||
SetSession(value, null);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>同步请求;无 data 时返回 default(T),界面调用需放在后台线程。</summary>
|
||||
public T Send<T>(string route, MethodType method, object body = null,
|
||||
IDictionary<string, string> query = null, bool authenticated = true,
|
||||
int timeoutMilliseconds = 30000)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(route) ||
|
||||
!Regex.IsMatch(route, @"\A[A-Za-z0-9_-]+(/[A-Za-z0-9_-]+)*\z"))
|
||||
throw new ArgumentException("接口必须使用相对路由,例如 Auth/Login。", nameof(route));
|
||||
if (body != null) Validator.ValidateObject(body, new ValidationContext(body), true);
|
||||
if (timeoutMilliseconds <= 0) throw new ArgumentOutOfRangeException(nameof(timeoutMilliseconds));
|
||||
string token = authenticated ? Token : null;
|
||||
if (authenticated && token == null)
|
||||
throw new HttpException("请先登录。") { IsOnline = false };
|
||||
|
||||
var url = new StringBuilder(_baseUrl).Append(route);
|
||||
if (query != null)
|
||||
{
|
||||
bool first = true;
|
||||
foreach (var pair in query)
|
||||
{
|
||||
if (pair.Value == null) continue;
|
||||
url.Append(first ? '?' : '&').Append(Uri.EscapeDataString(pair.Key))
|
||||
.Append('=').Append(Uri.EscapeDataString(pair.Value));
|
||||
first = false;
|
||||
}
|
||||
}
|
||||
var item = new HttpItem
|
||||
{
|
||||
URL = url.ToString(),
|
||||
Method = method,
|
||||
ContentType = "application/json; charset=utf-8",
|
||||
Accept = "application/json",
|
||||
PostDataType = PostDataType.Byte,
|
||||
PostdataByte = body == null ? null : Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(body)),
|
||||
Encoding = Encoding.UTF8,
|
||||
Timeout = timeoutMilliseconds,
|
||||
ReadWriteTimeout = timeoutMilliseconds,
|
||||
Allowautoredirect = false
|
||||
};
|
||||
for (int attempt = 0; ; attempt++)
|
||||
{
|
||||
if (token != null) item.Header["Authorization"] = "Bearer " + token;
|
||||
var response = HttpHelper.Request(item);
|
||||
int status = (int)response.StatusCode;
|
||||
if (status == 0) throw new HttpException("无法连接服务器或请求超时。");
|
||||
|
||||
JObject result = null;
|
||||
JsonException parseError = null;
|
||||
try { result = JObject.Parse(response.Html ?? ""); }
|
||||
catch (JsonException ex) { parseError = ex; }
|
||||
|
||||
var code = result?["code"];
|
||||
if (status == 401 || (code?.Type == JTokenType.Integer && code.ToString() == "401"))
|
||||
{
|
||||
if (authenticated)
|
||||
{
|
||||
lock (SessionGate)
|
||||
{
|
||||
// 并发旧请求复用已更新的 Token;同一请求最多重新发送一次。
|
||||
if (_token == token)
|
||||
{
|
||||
_token = null;
|
||||
if (attempt == 0 && _login != null)
|
||||
_token = _login();
|
||||
}
|
||||
if (attempt == 0 && _token != null)
|
||||
{
|
||||
token = _token;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
throw new HttpException(result?["msg"]?.ToString() ?? "登录已失效,请重新登录。") { IsOnline = false };
|
||||
}
|
||||
if (status < 200 || status >= 300)
|
||||
throw new HttpException($"请求失败(HTTP {status}):{result?["msg"]}");
|
||||
if (result == null)
|
||||
throw new HttpException("服务器响应不是有效的 JSON 对象。", parseError);
|
||||
// 先检查业务码,避免错误响应的 data 结构掩盖服务端错误。
|
||||
if (code?.Type != JTokenType.Integer || code.ToString() != "200")
|
||||
throw new ApiException("请求失败:" + (result["msg"]?.ToString() ?? "响应缺少成功状态码。"),
|
||||
code?.Type == JTokenType.Integer && int.TryParse(code.ToString(), out var businessCode) ? businessCode : (int?)null,
|
||||
result["data"]);
|
||||
if (result["data"] == null || result["data"].Type == JTokenType.Null) return default;
|
||||
try { return result["data"].ToObject<T>(); }
|
||||
catch (JsonException ex) { throw new HttpException("服务器响应 data 格式无效。", ex); }
|
||||
}
|
||||
}
|
||||
|
||||
public T GetRequired<T>(string route, MethodType method, object body = null,
|
||||
IDictionary<string, string> query = null, bool authenticated = true,
|
||||
int timeoutMilliseconds = 30000) where T : class
|
||||
=> Send<T>(route, method, body, query, authenticated, timeoutMilliseconds)
|
||||
?? throw new HttpException("服务器响应缺少 data。");
|
||||
}
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
using CsharpHttpHelper;
|
||||
using System;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
|
||||
namespace Work.Store.Api;
|
||||
|
||||
public sealed class LoginRequest
|
||||
{
|
||||
[Required]
|
||||
public string UserName { get; set; }
|
||||
|
||||
/// <summary>UTF-8 密码的 32 位大写 MD5,由调用方计算。</summary>
|
||||
[Required]
|
||||
public string Password { get; set; }
|
||||
|
||||
[StringLength(100)]
|
||||
public string DeviceId { get; set; }
|
||||
|
||||
[StringLength(100)]
|
||||
public string DeviceName { get; set; }
|
||||
}
|
||||
|
||||
public sealed class LoginResult
|
||||
{
|
||||
public string TokenType { get; set; } = "Bearer";
|
||||
public string Token { get; set; }
|
||||
public uint ExpiresInMinutes { get; set; }
|
||||
}
|
||||
|
||||
public sealed class AuthApi
|
||||
{
|
||||
private readonly ApiTransport _transport;
|
||||
private readonly string _deviceId;
|
||||
|
||||
public AuthApi(string baseUrl) : this(new ApiTransport(baseUrl)) { }
|
||||
|
||||
public AuthApi(ApiTransport transport, string deviceId = null)
|
||||
{
|
||||
_transport = transport ?? throw new ArgumentNullException(nameof(transport));
|
||||
_deviceId = deviceId;
|
||||
}
|
||||
|
||||
/// <summary>同步登录,凭据快照仅存内存,供 401 时自动重登;界面调用需放在后台线程。</summary>
|
||||
public LoginResult Login(LoginRequest request)
|
||||
{
|
||||
if (request == null) throw new ArgumentNullException(nameof(request));
|
||||
var credentials = new LoginRequest
|
||||
{
|
||||
UserName = request.UserName,
|
||||
Password = request.Password,
|
||||
DeviceId = _deviceId ?? request.DeviceId,
|
||||
DeviceName = request.DeviceName
|
||||
};
|
||||
lock (_transport.SessionGate)
|
||||
{
|
||||
var result = LoginCore(credentials);
|
||||
_transport.SetSession(result.Token, () => LoginCore(credentials).Token);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
private LoginResult LoginCore(LoginRequest request)
|
||||
{
|
||||
var result = _transport.GetRequired<LoginResult>("Auth/Login", MethodType.Post, request, authenticated: false);
|
||||
if (result == null || string.IsNullOrWhiteSpace(result.Token) ||
|
||||
result.Token.IndexOfAny(new[] { '\r', '\n' }) >= 0 ||
|
||||
!string.Equals(result.TokenType, "Bearer", StringComparison.OrdinalIgnoreCase))
|
||||
throw new HttpException("登录响应缺少有效的 Bearer Token。");
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
using AllBase.Model.Result;
|
||||
using CsharpHttpHelper;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Threading.Tasks;
|
||||
using Work.Services;
|
||||
|
||||
namespace Work.Store.Api;
|
||||
|
||||
/// <summary>云商品接口,沿用服务端不带版本号的路由。</summary>
|
||||
public sealed class CloudGoodsApi
|
||||
{
|
||||
private readonly ApiTransport _transport;
|
||||
|
||||
public CloudGoodsApi(ApiTransport transport)
|
||||
=> _transport = transport ?? throw new ArgumentNullException(nameof(transport));
|
||||
|
||||
public Task<PageData<CloudGoods>> GetGoods(GoodsSearchRequest request)
|
||||
=> Task.Run(() => _transport.GetRequired<PageData<CloudGoods>>("CloudGoods/SearchGoods", MethodType.Post, request));
|
||||
|
||||
public string GetGoodsDetail(long goodsId)
|
||||
=> _transport.GetRequired<string>("CloudGoods/GetGoodsRawData", MethodType.Post,
|
||||
query: new Dictionary<string, string> { ["goodsId"] = goodsId.ToString(CultureInfo.InvariantCulture) });
|
||||
|
||||
public Task<List<ReportGoodsViolationResult>> ReportViolations(List<ReportGoodsViolationItem> items)
|
||||
=> Task.Run(() => _transport.GetRequired<List<ReportGoodsViolationResult>>("CloudGoods/ReportViolations", MethodType.Post, items,
|
||||
timeoutMilliseconds: 5000));
|
||||
|
||||
public List<GoodsViolationStatus> GetViolationStatus(List<long> goodsIds)
|
||||
=> _transport.GetRequired<List<GoodsViolationStatus>>("CloudGoods/GetViolationStatus", MethodType.Post, goodsIds,
|
||||
timeoutMilliseconds: 5000);
|
||||
|
||||
public Task RecordViolationLogs(IReadOnlyList<RecordViolationLogRequest> requests)
|
||||
=> Task.Run(() => _transport.Send<object>("CloudGoods/RecordViolationLog", MethodType.Post, requests,
|
||||
timeoutMilliseconds: 5000));
|
||||
|
||||
public Task<List<CloudGoodsService.ViolationReason>> GetViolationReasons()
|
||||
=> Task.Run(() => _transport.GetRequired<List<CloudGoodsService.ViolationReason>>("CloudGoods/GetViolationReasons", MethodType.Get));
|
||||
|
||||
public Task<List<GoodsViolationLogEntity>> GetViolationLogs(GetViolationLogsRequest request)
|
||||
=> Task.Run(() => _transport.GetRequired<List<GoodsViolationLogEntity>>("CloudGoods/GetViolationLogs", MethodType.Post, request,
|
||||
timeoutMilliseconds: 5000));
|
||||
|
||||
public Task<PageData<CloudGoods>> SearchFavorites(UserFavoritesGoodsSearchRequest request)
|
||||
=> Task.Run(() => _transport.GetRequired<PageData<CloudGoods>>("CloudGoods/SearchFavorites", MethodType.Post, request));
|
||||
|
||||
public Task<int> Favorite(string userName, List<long> goodsIds)
|
||||
=> Task.Run(() => _transport.Send<int>("CloudGoods/AddFavorite", MethodType.Post,
|
||||
new { UserName = userName, GoodsIds = goodsIds }));
|
||||
|
||||
public Task<int> RemoveFavorites(string userName, List<long> goodsIds)
|
||||
=> Task.Run(() => _transport.Send<int>("CloudGoods/RemoveFavorites", MethodType.Post,
|
||||
new { UserName = userName, GoodsIds = goodsIds }));
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
using CsharpHttpHelper;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using Work.Services;
|
||||
|
||||
namespace Work.Store.Api;
|
||||
|
||||
/// <summary>图片缓存接口,返回批量保存失败的 MD5 列表。</summary>
|
||||
public sealed class ImageCacheApi
|
||||
{
|
||||
private readonly ApiTransport _transport;
|
||||
|
||||
public ImageCacheApi(ApiTransport transport)
|
||||
=> _transport = transport ?? throw new ArgumentNullException(nameof(transport));
|
||||
|
||||
public List<ImageCache> GetImageCaches(List<string> md5s)
|
||||
=> _transport.GetRequired<List<ImageCache>>("ImageCache/GetImageCache", MethodType.Post, new { md5s });
|
||||
|
||||
public List<string> SaveImageCaches(int platform, IReadOnlyList<ImageCache> images)
|
||||
{
|
||||
if (images == null) throw new ArgumentNullException(nameof(images));
|
||||
if (images.Count == 0) return new List<string>();
|
||||
try
|
||||
{
|
||||
_transport.Send<object>("ImageCache/AddOrUpdate", MethodType.Post,
|
||||
images.Select(image => new { md5 = image.Md5, Platform = platform, PlatformUrl = image.PlatformUrl }).ToArray());
|
||||
return new List<string>();
|
||||
}
|
||||
catch (ApiException ex) when (ex.Code == 500)
|
||||
{
|
||||
// 兼容旧服务的部分失败响应;没有明确失败项时保持整体失败。
|
||||
if (ex.ResponseData is JArray array && array.Count > 0 && array.All(item => item.Type == JTokenType.String))
|
||||
return array.ToObject<List<string>>();
|
||||
if (ex.ResponseData?.Type == JTokenType.String && !string.IsNullOrWhiteSpace((string)ex.ResponseData))
|
||||
return new List<string> { (string)ex.ResponseData };
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
using Microsoft.Win32;
|
||||
using AllBase.Helper;
|
||||
using System;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace Work.Store.Api;
|
||||
|
||||
/// <summary>全局共用一个用户会话与请求出口,窗体通过 Instance 访问。</summary>
|
||||
public sealed class StoreApiClient
|
||||
{
|
||||
private static readonly string BaseUrl = EnvironmentHelper.IsDevelopment
|
||||
? "http://localhost:14312/api/"
|
||||
: "http://103.90.155.78:9001/api/";
|
||||
|
||||
public static StoreApiClient Instance { get; } = new StoreApiClient();
|
||||
|
||||
public ApiTransport Transport { get; }
|
||||
public AuthApi Auth { get; }
|
||||
public CloudGoodsApi CloudGoods { get; }
|
||||
public ImageCacheApi ImageCache { get; }
|
||||
/// <summary>当前 Windows 安装的 SHA-256 设备指纹,登录时作为 DeviceId 发送。</summary>
|
||||
public string DeviceId { get; }
|
||||
|
||||
private StoreApiClient()
|
||||
{
|
||||
DeviceId = CreateDeviceId();
|
||||
Transport = new ApiTransport(BaseUrl);
|
||||
Auth = new AuthApi(Transport, DeviceId);
|
||||
CloudGoods = new CloudGoodsApi(Transport);
|
||||
ImageCache = new ImageCacheApi(Transport);
|
||||
}
|
||||
|
||||
private static string CreateDeviceId()
|
||||
{
|
||||
using (var machine = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64))
|
||||
using (var key = machine.OpenSubKey(@"SOFTWARE\Microsoft\Cryptography"))
|
||||
{
|
||||
if (!Guid.TryParse(key?.GetValue("MachineGuid") as string, out var machineGuid) || machineGuid == Guid.Empty)
|
||||
throw new InvalidOperationException("无法读取有效的 Windows MachineGuid,不能生成设备指纹。");
|
||||
|
||||
using (var sha256 = SHA256.Create())
|
||||
return BitConverter.ToString(sha256.ComputeHash(
|
||||
Encoding.UTF8.GetBytes("Store.Api:" + machineGuid.ToString("D")))).Replace("-", "");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>清除内存中的 Token 和自动登录凭据,不调用服务端退出接口。</summary>
|
||||
public void ClearSession() => Transport.Token = null;
|
||||
}
|
||||
Reference in new issue
Block a user