feat(upserver): 接入认证与KV存档并完成限定钓鱼闭环
This commit is contained in:
@@ -6,6 +6,8 @@ using System.Net.Http;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using UnityEngine;
|
||||
using game.Account;
|
||||
using game.PlayerDataStorage;
|
||||
|
||||
public interface ICustomServerMgr
|
||||
{
|
||||
@@ -21,6 +23,11 @@ public interface ICustomServerMgr
|
||||
Task<T> EventPartnerRequest<T>(string url, object data = null);
|
||||
Task<string> EventPartnerRequest(string url, object data);
|
||||
CookieContainer Cookie { get; }
|
||||
Uri ApiBaseUri { get; }
|
||||
int SessionVersion { get; }
|
||||
event Action SessionChanged;
|
||||
void UseAccountSession(S101AccountSession session);
|
||||
void ClearAccountSession();
|
||||
}
|
||||
|
||||
public class CustomServerMgr : ICustomServerMgr
|
||||
@@ -31,87 +38,122 @@ public class CustomServerMgr : ICustomServerMgr
|
||||
HttpClient client;
|
||||
|
||||
private CookieContainer _cookie;
|
||||
private readonly Func<CookieContainer, HttpMessageHandler> handlerFactory;
|
||||
public int SessionVersion { get; private set; }
|
||||
public event Action SessionChanged;
|
||||
PlayerKVAccountLease kvLease;
|
||||
bool kvOnly;
|
||||
int pfRequests;
|
||||
internal event Action<int> KVUnauthorized;
|
||||
internal bool IsFreshForKVLoad => pfRequests==0 && kvLease==null;
|
||||
internal void BindKVForValidation(PlayerKVAccountLease lease)
|
||||
{
|
||||
if(lease==null || !lease.IsCurrent || lease.ApiBaseUri!=ApiBaseUri || !IsFreshForKVLoad)
|
||||
throw new InvalidOperationException("Fresh matching KV lease required.");
|
||||
kvOnly=true; SessionVersion++; kvLease=lease; _cookie=null;
|
||||
var previous=client; client=null; previous?.Dispose(); SessionChanged?.Invoke();
|
||||
}
|
||||
internal Task ClearKVForValidation()
|
||||
{
|
||||
SessionVersion++; var previous=kvLease; kvLease=null;
|
||||
var closing=previous?.CloseAsync() ?? Task.CompletedTask;
|
||||
SessionChanged?.Invoke(); return closing;
|
||||
}
|
||||
internal async Task<PlayerKVAccountResponse> SendKVForValidationAsync(string route)
|
||||
{
|
||||
var lease=kvLease; int version=SessionVersion;
|
||||
if(!kvOnly || lease==null) return new PlayerKVAccountResponse(false);
|
||||
var response=await lease.SendAsync(HttpMethod.Get,route);
|
||||
if(version!=SessionVersion || !ReferenceEquals(lease,kvLease) || !response.IsCurrent) return new PlayerKVAccountResponse(false);
|
||||
if(response.StatusCode==401 || response.StatusCode==403)
|
||||
{
|
||||
KVUnauthorized?.Invoke(version);
|
||||
return new PlayerKVAccountResponse(false,response.StatusCode);
|
||||
}
|
||||
return response;
|
||||
}
|
||||
|
||||
|
||||
public CookieContainer Cookie => _cookie ?? throw new System.NullReferenceException();
|
||||
public Uri ApiBaseUri { get; }
|
||||
|
||||
public CustomServerMgr(IConfig config)
|
||||
public CustomServerMgr(IConfig config) : this(config, null) { }
|
||||
|
||||
public CustomServerMgr(IConfig config, Func<CookieContainer, HttpMessageHandler> handlerFactory)
|
||||
{
|
||||
this.handlerFactory = handlerFactory ?? (cookies => new HttpClientHandler
|
||||
{
|
||||
CookieContainer = cookies, UseCookies = true, AllowAutoRedirect = false
|
||||
});
|
||||
this.config = config;
|
||||
|
||||
var httpClientHandler = new HttpClientHandler();
|
||||
_cookie = new CookieContainer();
|
||||
httpClientHandler.CookieContainer = _cookie;
|
||||
client = new HttpClient(httpClientHandler);
|
||||
|
||||
client.BaseAddress =
|
||||
new System.Uri(config.Get<string>(GConstant.K_Event_API_URL,
|
||||
"http://192.168.9.101:5292/"));
|
||||
client.Timeout = TimeSpan.FromSeconds(15);
|
||||
var url = config.Get<string>(GConstant.K_Event_API_URL, S101AccountSession.DefaultApiUrl);
|
||||
if (string.IsNullOrWhiteSpace(url)) url = S101AccountSession.DefaultApiUrl;
|
||||
ApiBaseUri = new Uri(url.TrimEnd('/') + "/");
|
||||
ClearAccountSession();
|
||||
}
|
||||
|
||||
public async Task<string> CustomServerPost(string url, string bodyString,
|
||||
string contentType = "application/json")
|
||||
public void UseAccountSession(S101AccountSession session)
|
||||
{
|
||||
if(kvOnly) throw new InvalidOperationException("Controlled container cannot switch to PlayFab.");
|
||||
if (session == null || !session.IsAuthenticated || session.ApiBaseUri != ApiBaseUri)
|
||||
throw new ArgumentException("An authenticated session for this API is required.", nameof(session));
|
||||
ReplaceTransport(session.Cookies);
|
||||
}
|
||||
|
||||
public void ClearAccountSession()
|
||||
{
|
||||
if(kvOnly) { PlayerKVShutdownRegistry.Process.Register(ClearKVForValidation()); return; }
|
||||
ReplaceTransport(new CookieContainer());
|
||||
}
|
||||
|
||||
private void ReplaceTransport(CookieContainer cookies)
|
||||
{
|
||||
SessionVersion++;
|
||||
var previous = client;
|
||||
_cookie = cookies;
|
||||
client = new HttpClient(handlerFactory(cookies)) { BaseAddress = ApiBaseUri, Timeout = TimeSpan.FromSeconds(15) };
|
||||
previous?.Dispose();
|
||||
SessionChanged?.Invoke();
|
||||
}
|
||||
|
||||
public Task<string> CustomServerPost(string url, string bodyString,
|
||||
string contentType = "application/json") => SendAsync(HttpMethod.Post, url, bodyString, contentType);
|
||||
|
||||
public Task<string> GetStringAsync(string url) => SendAsync(HttpMethod.Get, url, null, null);
|
||||
|
||||
// Unity callers use the main thread. Capture a fixed transport before the first await.
|
||||
private async Task<string> SendAsync(HttpMethod method, string url, string body, string contentType)
|
||||
{
|
||||
if(kvOnly) throw new InvalidOperationException("Only controlled validation routes are enabled.");
|
||||
pfRequests++;
|
||||
var transport = client;
|
||||
var version = SessionVersion;
|
||||
try
|
||||
{
|
||||
#if UNITY_EDITOR
|
||||
Debug.Log("client.BaseAddress.AbsoluteUri:" + client.BaseAddress.AbsoluteUri);
|
||||
Debug.Log("CustomServerPost url:" + url);
|
||||
Debug.Log("CustomServerPost bodyString:" + bodyString);
|
||||
#endif
|
||||
var content = new StringContent(bodyString, Encoding.UTF8, "application/json");
|
||||
var response = await client.PostAsync(url, content);
|
||||
string result = await response.Content.ReadAsStringAsync();
|
||||
if (response.StatusCode == System.Net.HttpStatusCode.OK)
|
||||
using (var request = new HttpRequestMessage(method, url))
|
||||
{
|
||||
//GameDebug.Log("CustomServerPost result:" + result.ToString());
|
||||
return result;
|
||||
}
|
||||
else if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized || response.StatusCode == System.Net.HttpStatusCode.Forbidden)
|
||||
{
|
||||
GContext.Publish(new game.EvtAPISvrUnauthorized());
|
||||
return null;
|
||||
}
|
||||
else
|
||||
{
|
||||
Debug.LogError(response.StatusCode.ToString() + "+++CustomServerPost error:" +
|
||||
result.ToString() + "+++CustomServerPost url:" + url + ":" +
|
||||
bodyString);
|
||||
return null;
|
||||
if (body != null) request.Content = new StringContent(body, Encoding.UTF8, contentType);
|
||||
using (var response = await transport.SendAsync(request))
|
||||
{
|
||||
var result = await response.Content.ReadAsStringAsync();
|
||||
if (version != SessionVersion) return null;
|
||||
if (response.StatusCode == HttpStatusCode.OK) return result;
|
||||
if (response.StatusCode == HttpStatusCode.Unauthorized || response.StatusCode == HttpStatusCode.Forbidden)
|
||||
GContext.Publish(new game.EvtAPISvrUnauthorized { SessionVersion = version });
|
||||
else
|
||||
Debug.LogError($"API request failed: HTTP {(int)response.StatusCode}");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Debug.LogError("CustomServerPost error:" + e.Message + "---CustomServerPost url:" +
|
||||
url + ":" + bodyString + "\n" + e.StackTrace);
|
||||
if (version == SessionVersion) Debug.LogError($"API request failed: {e.GetType().Name}");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<string> GetStringAsync(string url)
|
||||
{
|
||||
var response = await client.GetAsync(url);
|
||||
|
||||
if (response.StatusCode == HttpStatusCode.OK)
|
||||
{
|
||||
return await response.Content.ReadAsStringAsync();
|
||||
}
|
||||
else
|
||||
{
|
||||
string result = await response.Content.ReadAsStringAsync();
|
||||
Debug.LogError(response.StatusCode.ToString() + "+++GetStringAsync error:" +
|
||||
result.ToString() + "+++GetStringAsync url:" + url);
|
||||
}
|
||||
|
||||
if (response.StatusCode == HttpStatusCode.Unauthorized)
|
||||
{
|
||||
GContext.Publish(new game.EvtAPISvrUnauthorized());
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public async Task<string> AccountRequest(string url, object data)
|
||||
{
|
||||
return await CustomServerPost($"account/{url}",
|
||||
|
||||
Reference in New Issue
Block a user