52 lines
2.1 KiB
C#
52 lines
2.1 KiB
C#
using System;
|
|
using System.Collections;
|
|
using System.Text;
|
|
using UnityEngine;
|
|
using UnityEngine.Networking;
|
|
|
|
namespace XGame
|
|
{
|
|
// 账号鉴权 HTTP 客户端:POST /login、/register,拿 {token,pid}。
|
|
public static class AuthClient
|
|
{
|
|
[Serializable] class AuthReq { public string username; public string password; }
|
|
[Serializable] class AuthResp { public string token; public int pid; }
|
|
|
|
public static IEnumerator Login(string user, string pwd, Action<bool, string, int, string> done)
|
|
=> Post("/login", user, pwd, done);
|
|
|
|
public static IEnumerator Register(string user, string pwd, Action<bool, string, int, string> done)
|
|
=> Post("/register", user, pwd, done);
|
|
|
|
static IEnumerator Post(string path, string user, string pwd, Action<bool, string, int, string> done)
|
|
{
|
|
string url = GlobalData.ProductionAuthBase + path;
|
|
string body = JsonUtility.ToJson(new AuthReq { username = user, password = pwd });
|
|
using (var req = new UnityWebRequest(url, "POST"))
|
|
{
|
|
req.uploadHandler = new UploadHandlerRaw(Encoding.UTF8.GetBytes(body));
|
|
req.downloadHandler = new DownloadHandlerBuffer();
|
|
req.SetRequestHeader("Content-Type", "application/json");
|
|
yield return req.SendWebRequest();
|
|
|
|
if (req.result != UnityWebRequest.Result.Success)
|
|
{
|
|
string err = req.responseCode == 401 ? "账号或密码错误"
|
|
: req.responseCode == 409 ? "用户名已被占用"
|
|
: ("网络错误: " + req.error);
|
|
done(false, null, 0, err);
|
|
yield break;
|
|
}
|
|
AuthResp resp = null;
|
|
try { resp = JsonUtility.FromJson<AuthResp>(req.downloadHandler.text); } catch { }
|
|
if (resp == null || string.IsNullOrEmpty(resp.token))
|
|
{
|
|
done(false, null, 0, "响应解析失败");
|
|
yield break;
|
|
}
|
|
done(true, resp.token, resp.pid, null);
|
|
}
|
|
}
|
|
}
|
|
}
|