2026-11-17 04:55:28 +00:00
|
|
|
using System;
|
|
|
|
|
using System.Collections;
|
2026-11-17 06:56:37 +00:00
|
|
|
using System.Collections.Generic;
|
2026-11-17 04:55:28 +00:00
|
|
|
using System.Globalization;
|
|
|
|
|
using System.IO;
|
|
|
|
|
using System.Text;
|
|
|
|
|
using Newtonsoft.Json;
|
|
|
|
|
using Newtonsoft.Json.Linq;
|
|
|
|
|
using UnityEngine;
|
|
|
|
|
using UnityEngine.Networking;
|
|
|
|
|
|
|
|
|
|
namespace TKS.OutGame.Net
|
|
|
|
|
{
|
|
|
|
|
/// <summary>요청 1건의 결과. 값은 Str·Num·Bool 로 꺼낸다(경로 예 「account.stamina.amount」 · 「heroes[0].lv」).</summary>
|
|
|
|
|
public class ServerResult
|
|
|
|
|
{
|
|
|
|
|
public bool ok;
|
|
|
|
|
public long status;
|
|
|
|
|
/// <summary>연결 문제(끊김 · 시간 초과 · 서버 오류 5xx) = 다시 보내면 될 수 있다 · false = 서버가 요청을 거절했다.</summary>
|
|
|
|
|
public bool network;
|
|
|
|
|
public string error;
|
|
|
|
|
internal JObject json;
|
|
|
|
|
|
|
|
|
|
/// <summary>서버가 거절한 이유 코드(예 STAGE_LOCKED) · 없으면 "".</summary>
|
|
|
|
|
public string Message
|
|
|
|
|
{
|
|
|
|
|
get { return Str("message"); }
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
internal JToken At(string path)
|
|
|
|
|
{
|
|
|
|
|
return json != null ? json.SelectToken(path) : null;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public bool Has(string path)
|
|
|
|
|
{
|
|
|
|
|
var t = At(path);
|
|
|
|
|
return t != null && t.Type != JTokenType.Null;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public string Str(string path)
|
|
|
|
|
{
|
|
|
|
|
var t = At(path);
|
|
|
|
|
return t == null || t.Type == JTokenType.Null ? "" : t.ToString();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public long Num(string path)
|
|
|
|
|
{
|
|
|
|
|
long n;
|
|
|
|
|
return long.TryParse(Str(path), NumberStyles.Integer, CultureInfo.InvariantCulture, out n) ? n : 0;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public float Float(string path)
|
|
|
|
|
{
|
|
|
|
|
var t = At(path);
|
|
|
|
|
return t == null || (t.Type != JTokenType.Float && t.Type != JTokenType.Integer) ? 0f : (float)t.Value<double>();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <summary>글자 배열(없으면 빈 목록).</summary>
|
|
|
|
|
public System.Collections.Generic.List<string> Strings(string path)
|
|
|
|
|
{
|
|
|
|
|
var list = new System.Collections.Generic.List<string>();
|
|
|
|
|
var arr = At(path) as JArray;
|
|
|
|
|
if (arr != null)
|
|
|
|
|
foreach (var x in arr) list.Add(x.Type == JTokenType.Null ? "" : x.ToString());
|
|
|
|
|
return list;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <summary>배열 길이(없으면 0).</summary>
|
|
|
|
|
public int Count(string path)
|
|
|
|
|
{
|
|
|
|
|
var arr = At(path) as JArray;
|
|
|
|
|
return arr != null ? arr.Count : 0;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public bool Bool(string path)
|
|
|
|
|
{
|
|
|
|
|
var t = At(path);
|
|
|
|
|
return t != null && t.Type == JTokenType.Boolean && (bool)t;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// 서버와 HTTP 로 말하는 가장 아래 층 — 주소 붙이기 · 로그인 증표 · 응답 해석만 한다(게임 규칙은 모른다).
|
2026-11-17 06:56:37 +00:00
|
|
|
/// 로그인 = 게스트(새 계정) 또는 소셜 계정(구글 플레이 · 게임센터) · 다음부터는 기기에 저장한 재발급 증표로 이어 한다(앱을 켤 때 = 새 세션).
|
|
|
|
|
/// 한 계정은 한 기기에서만 접속한다 — 다른 기기에서 접속하면 서버가 이쪽 증표를 못 쓰게 하고(401 SESSION_REPLACED), 그 사실을 LostReason 으로 알린다.
|
2026-11-17 04:55:28 +00:00
|
|
|
/// </summary>
|
|
|
|
|
public class ServerClient
|
|
|
|
|
{
|
|
|
|
|
readonly string baseUrl;
|
|
|
|
|
readonly int timeoutSec;
|
|
|
|
|
/// <summary>재발급 증표를 기기에 저장하는가(테스트 = 저장 안 함 → 매번 새 계정).</summary>
|
|
|
|
|
readonly bool persist;
|
|
|
|
|
string accessToken;
|
|
|
|
|
string refreshToken;
|
|
|
|
|
|
2026-11-17 06:56:37 +00:00
|
|
|
// 서버가 「이 세션은 끝났다」고 알리는 이유 코드
|
|
|
|
|
public const string LostReplaced = "SESSION_REPLACED"; // 다른 기기에서 접속(또는 로그아웃 · 연동 변경)
|
|
|
|
|
public const string LostDeleted = "ACCOUNT_DELETED";
|
|
|
|
|
public const string LostExpired = "SESSION_EXPIRED"; // 증표를 다시 받지 못함
|
|
|
|
|
public const string MethodGuest = "guest";
|
|
|
|
|
// 계정 삭제 요청의 확인 값 — 유저가 화면에서 확인 문구를 입력한 뒤에만 보낸다(서버 규칙과 같은 값)
|
|
|
|
|
const string DeleteConfirm = "DELETE";
|
|
|
|
|
|
|
|
|
|
/// <summary>세션을 잃은 이유(null = 정상) — 값이 있으면 다시 로그인해야 한다.</summary>
|
|
|
|
|
public string LostReason { get; private set; }
|
|
|
|
|
/// <summary>지금 세션의 로그인 방식(guest · google · apple).</summary>
|
|
|
|
|
public string Method { get; private set; }
|
|
|
|
|
|
|
|
|
|
// 기기에 저장하지 않는 모드(테스트)의 임시 보관 — 씬을 다시 열어도 남는다(ClearMemory 로 비운다)
|
|
|
|
|
static readonly Dictionary<string, string> memory = new Dictionary<string, string>();
|
|
|
|
|
|
|
|
|
|
public static void ClearMemory()
|
|
|
|
|
{
|
|
|
|
|
memory.Clear();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <summary>storeTag = 저장 칸을 따로 쓰게 하는 꼬리표(테스트에서 「다른 기기」를 흉내 낼 때 — 같은 기기의 로그인 정보를 덮지 않게).</summary>
|
|
|
|
|
public ServerClient(string baseUrl, int timeoutSec, bool persist, string storeTag = "")
|
2026-11-17 04:55:28 +00:00
|
|
|
{
|
|
|
|
|
this.baseUrl = baseUrl;
|
|
|
|
|
this.timeoutSec = timeoutSec;
|
|
|
|
|
this.persist = persist;
|
2026-11-17 06:56:37 +00:00
|
|
|
this.storeTag = storeTag ?? "";
|
2026-11-17 04:55:28 +00:00
|
|
|
}
|
|
|
|
|
|
2026-11-17 06:56:37 +00:00
|
|
|
readonly string storeTag;
|
|
|
|
|
|
2026-11-17 04:55:28 +00:00
|
|
|
/// <summary>기기에 저장하는 재발급 증표의 키 — 서버 주소마다 따로(개발 서버와 라이브 서버의 계정이 섞이지 않게).</summary>
|
|
|
|
|
public static string RefreshKey(string baseUrl)
|
|
|
|
|
{
|
|
|
|
|
return "tks.server.refresh." + Animator.StringToHash(baseUrl).ToString(CultureInfo.InvariantCulture);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public bool LoggedIn
|
|
|
|
|
{
|
|
|
|
|
get { return !string.IsNullOrEmpty(accessToken); }
|
|
|
|
|
}
|
|
|
|
|
|
2026-11-17 06:56:37 +00:00
|
|
|
// ---------- 기기에 저장하는 로그인 정보 (서버 주소마다 따로) ----------
|
|
|
|
|
|
|
|
|
|
string Key(string name)
|
|
|
|
|
{
|
|
|
|
|
return "tks.server." + name + "." + Animator.StringToHash(baseUrl).ToString(CultureInfo.InvariantCulture) + storeTag;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
string Load(string name)
|
|
|
|
|
{
|
|
|
|
|
if (persist) return PlayerPrefs.GetString(Key(name), "");
|
|
|
|
|
string v;
|
|
|
|
|
return memory.TryGetValue(Key(name), out v) ? v : "";
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
void Keep(string name, string value)
|
|
|
|
|
{
|
|
|
|
|
if (!persist)
|
|
|
|
|
{
|
|
|
|
|
memory[Key(name)] = value ?? "";
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
if (string.IsNullOrEmpty(value)) PlayerPrefs.DeleteKey(Key(name));
|
|
|
|
|
else PlayerPrefs.SetString(Key(name), value);
|
|
|
|
|
PlayerPrefs.Save();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <summary>이어 할 증표가 기기에 있는가(로그아웃 · 계정 삭제 뒤에는 없다).</summary>
|
|
|
|
|
public bool HasSaved
|
|
|
|
|
{
|
|
|
|
|
get { return !string.IsNullOrEmpty(Load("refresh")); }
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <summary>마지막으로 로그인한 방식(guest · google · apple) — 로그아웃해도 남는다(로그인 화면이 「마지막 로그인」을 보여 준다).</summary>
|
|
|
|
|
public string LastMethod
|
|
|
|
|
{
|
|
|
|
|
get { return Load("method"); }
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <summary>마지막으로 쓴 시험용 소셜 계정 번호(개발용 입력 칸의 기본값).</summary>
|
|
|
|
|
public string LastSocialId
|
|
|
|
|
{
|
|
|
|
|
get { return Load("devid"); }
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <summary>기기의 로그인 상태를 지운다(증표) — 마지막 로그인 방식은 남긴다. all = 방식까지 지운다(계정 삭제).</summary>
|
|
|
|
|
public void Forget(bool all = false)
|
|
|
|
|
{
|
|
|
|
|
accessToken = null;
|
|
|
|
|
refreshToken = null;
|
|
|
|
|
Method = null;
|
|
|
|
|
Keep("refresh", "");
|
|
|
|
|
if (all)
|
|
|
|
|
{
|
|
|
|
|
Keep("method", "");
|
|
|
|
|
Keep("devid", "");
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-11-17 04:55:28 +00:00
|
|
|
/// <summary>날짜처럼 생긴 글자를 날짜로 바꾸지 않고 그대로 읽는다(시각 글자를 ISO 그대로 써야 한다).</summary>
|
|
|
|
|
static JObject Parse(string text)
|
|
|
|
|
{
|
|
|
|
|
using (var reader = new JsonTextReader(new StringReader(text)) { DateParseHandling = DateParseHandling.None })
|
|
|
|
|
return JObject.Load(reader);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <summary>요청 1건. auth = 로그인 증표를 붙임 · 401 이면 증표를 한 번 재발급해 다시 보낸다.</summary>
|
|
|
|
|
public IEnumerator Send(string method, string path, string body, bool auth, ServerResult res)
|
|
|
|
|
{
|
|
|
|
|
for (int attempt = 0; attempt < 2; attempt++)
|
|
|
|
|
{
|
|
|
|
|
yield return SendOnce(method, path, body, auth, res);
|
2026-11-17 06:56:37 +00:00
|
|
|
if (res.status != 401 || !auth) yield break;
|
|
|
|
|
// 서버가 세션이 끝났다고 알렸다(다른 기기에서 접속 · 삭제된 계정) — 증표를 다시 받으려 하지 않는다
|
|
|
|
|
if (res.Message == LostReplaced || res.Message == LostDeleted)
|
|
|
|
|
{
|
|
|
|
|
LostReason = res.Message;
|
|
|
|
|
yield break;
|
|
|
|
|
}
|
|
|
|
|
if (attempt > 0 || string.IsNullOrEmpty(refreshToken))
|
|
|
|
|
{
|
|
|
|
|
LostReason = LostExpired;
|
|
|
|
|
yield break;
|
|
|
|
|
}
|
2026-11-17 04:55:28 +00:00
|
|
|
var again = new ServerResult();
|
|
|
|
|
yield return Refresh(again);
|
2026-11-17 06:56:37 +00:00
|
|
|
if (!again.ok)
|
|
|
|
|
{
|
|
|
|
|
if (!again.network) LostReason = LostExpired; // 재발급 증표도 받아 주지 않는다 = 다시 로그인해야 한다
|
|
|
|
|
yield break;
|
|
|
|
|
}
|
2026-11-17 04:55:28 +00:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
IEnumerator SendOnce(string method, string path, string body, bool auth, ServerResult res)
|
|
|
|
|
{
|
|
|
|
|
res.ok = false;
|
|
|
|
|
res.network = false;
|
|
|
|
|
res.status = 0;
|
|
|
|
|
res.error = null;
|
|
|
|
|
res.json = null;
|
|
|
|
|
using (var req = new UnityWebRequest(baseUrl + path, method))
|
|
|
|
|
{
|
|
|
|
|
req.downloadHandler = new DownloadHandlerBuffer();
|
|
|
|
|
if (body != null)
|
|
|
|
|
{
|
|
|
|
|
req.uploadHandler = new UploadHandlerRaw(Encoding.UTF8.GetBytes(body));
|
|
|
|
|
req.SetRequestHeader("Content-Type", "application/json");
|
|
|
|
|
}
|
|
|
|
|
if (auth && !string.IsNullOrEmpty(accessToken)) req.SetRequestHeader("Authorization", "Bearer " + accessToken);
|
|
|
|
|
req.timeout = timeoutSec;
|
|
|
|
|
|
|
|
|
|
UnityWebRequestAsyncOperation op = null;
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
op = req.SendWebRequest();
|
|
|
|
|
}
|
|
|
|
|
catch (Exception e)
|
|
|
|
|
{
|
|
|
|
|
// 예: 프로젝트 설정이 http 접속을 막고 있을 때(Player Settings > Allow downloads over HTTP)
|
|
|
|
|
res.network = true;
|
|
|
|
|
res.error = e.Message;
|
|
|
|
|
}
|
|
|
|
|
if (op == null) yield break;
|
|
|
|
|
yield return op;
|
|
|
|
|
|
|
|
|
|
res.status = req.responseCode;
|
|
|
|
|
bool transport = req.result == UnityWebRequest.Result.ConnectionError || req.result == UnityWebRequest.Result.DataProcessingError;
|
|
|
|
|
var text = req.downloadHandler != null ? req.downloadHandler.text : null;
|
|
|
|
|
if (!string.IsNullOrEmpty(text))
|
|
|
|
|
{
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
res.json = Parse(text);
|
|
|
|
|
}
|
|
|
|
|
catch (Exception)
|
|
|
|
|
{
|
|
|
|
|
res.json = null; // JSON 이 아닌 응답(프록시 오류 화면 등)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
res.ok = !transport && res.status >= 200 && res.status < 300;
|
|
|
|
|
res.network = transport || res.status == 0 || res.status >= 500;
|
|
|
|
|
if (!res.ok) res.error = transport || res.status == 0 ? req.error : "HTTP " + res.status + " " + res.Message;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-11-17 06:56:37 +00:00
|
|
|
/// <summary>테스트용 자동 로그인 — 저장한 증표가 있으면 이어 하기 → 없거나 서버가 받지 않으면 새 게스트 계정(로그인 화면 없음).</summary>
|
2026-11-17 04:55:28 +00:00
|
|
|
public IEnumerator Login(int gameId, ServerResult res)
|
|
|
|
|
{
|
2026-11-17 06:56:37 +00:00
|
|
|
if (HasSaved)
|
2026-11-17 04:55:28 +00:00
|
|
|
{
|
2026-11-17 06:56:37 +00:00
|
|
|
yield return Resume(res);
|
2026-11-17 04:55:28 +00:00
|
|
|
if (res.ok || res.network) yield break; // 연결 문제면 새 계정을 만들지 않는다(계정을 잃지 않게)
|
|
|
|
|
Debug.LogWarning("[TKS] 저장한 로그인 증표를 서버가 받지 않아 새 게스트 계정으로 시작합니다: " + res.error);
|
|
|
|
|
}
|
2026-11-17 06:56:37 +00:00
|
|
|
yield return GuestLogin(gameId, res);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <summary>세션 이어 하기(앱을 켤 때) — 저장한 증표로 새 세션을 연다. 같은 계정의 다른 기기 세션은 서버가 끊는다.</summary>
|
|
|
|
|
public IEnumerator Resume(ServerResult res)
|
|
|
|
|
{
|
|
|
|
|
refreshToken = Load("refresh");
|
|
|
|
|
var body = new JObject { ["refreshToken"] = refreshToken };
|
|
|
|
|
yield return SendOnce("POST", "/auth/session", body.ToString(Formatting.None), false, res);
|
|
|
|
|
if (res.ok) Store(res, null, null);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <summary>게스트로 시작 = 새 게스트 계정.</summary>
|
|
|
|
|
public IEnumerator GuestLogin(int gameId, ServerResult res)
|
|
|
|
|
{
|
2026-11-17 04:55:28 +00:00
|
|
|
var body = new JObject { ["gameId"] = gameId };
|
|
|
|
|
yield return SendOnce("POST", "/auth/guest/login", body.ToString(Formatting.None), false, res);
|
2026-11-17 06:56:37 +00:00
|
|
|
if (res.ok) Store(res, MethodGuest, null);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <summary>소셜 로그인 — method = google · apple · credential = 기기의 소셜 로그인이 준 증표. 그 소셜 계정에 연동된 게임 계정으로 들어간다(없으면 새 계정).</summary>
|
|
|
|
|
public IEnumerator SocialLogin(int gameId, string method, string credential, string socialId, ServerResult res)
|
|
|
|
|
{
|
|
|
|
|
var body = new JObject { ["gameId"] = gameId, ["idToken"] = credential };
|
|
|
|
|
yield return SendOnce("POST", "/auth/" + SocialSignIn.PlatformPath(method) + "/login", body.ToString(Formatting.None), false, res);
|
|
|
|
|
if (res.ok) Store(res, method, socialId);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// 게스트 계정을 소셜 계정에 연동. resolve = null(처음) · keep_current(지금 계정에 연동) · use_existing(기존 연동 계정으로 들어감).
|
|
|
|
|
/// 그 소셜 계정이 이미 다른 게임 계정에 연동돼 있으면 409 와 두 계정의 요약(current · existing)이 온다 — 유저가 고른 뒤 resolve 를 붙여 다시 부른다.
|
|
|
|
|
/// </summary>
|
|
|
|
|
public IEnumerator Link(string method, string credential, string socialId, string resolve, ServerResult res)
|
|
|
|
|
{
|
|
|
|
|
var body = new JObject { ["idToken"] = credential };
|
|
|
|
|
if (!string.IsNullOrEmpty(resolve)) body["resolve"] = resolve;
|
|
|
|
|
yield return SendOnce("POST", "/auth/guest/link/" + SocialSignIn.PlatformPath(method), body.ToString(Formatting.None), true, res);
|
|
|
|
|
if (res.ok) Store(res, method, socialId);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <summary>로그아웃(소셜 계정) — 서버가 증표를 못 쓰게 하고, 기기의 증표를 지운다(마지막 로그인 방식은 남는다).</summary>
|
|
|
|
|
public IEnumerator Logout(ServerResult res)
|
|
|
|
|
{
|
|
|
|
|
yield return Send("POST", "/auth/logout", null, true, res);
|
|
|
|
|
if (res.ok) Forget();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <summary>계정 삭제 — 서버가 게임 데이터를 지우고 계정을 삭제 상태로 바꾼다. 기기의 로그인 상태를 전부 지운다.</summary>
|
|
|
|
|
public IEnumerator DeleteAccount(ServerResult res)
|
|
|
|
|
{
|
|
|
|
|
var body = new JObject { ["confirm"] = DeleteConfirm };
|
|
|
|
|
yield return Send("POST", "/auth/delete-account", body.ToString(Formatting.None), true, res);
|
|
|
|
|
if (res.ok) Forget(true);
|
2026-11-17 04:55:28 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
IEnumerator Refresh(ServerResult res)
|
|
|
|
|
{
|
|
|
|
|
var body = new JObject { ["refreshToken"] = refreshToken };
|
|
|
|
|
yield return SendOnce("POST", "/auth/refresh", body.ToString(Formatting.None), false, res);
|
2026-11-17 06:56:37 +00:00
|
|
|
if (res.ok) Store(res, null, null);
|
2026-11-17 04:55:28 +00:00
|
|
|
}
|
|
|
|
|
|
2026-11-17 06:56:37 +00:00
|
|
|
/// <summary>받은 증표를 쓰기 시작하고 기기에 저장한다. method = null 이면 서버가 알려 준 방식(게스트 · 소셜 서비스)을 쓴다.</summary>
|
|
|
|
|
void Store(ServerResult res, string method, string socialId)
|
2026-11-17 04:55:28 +00:00
|
|
|
{
|
|
|
|
|
accessToken = res.Str("accessToken");
|
|
|
|
|
refreshToken = res.Str("refreshToken");
|
2026-11-17 06:56:37 +00:00
|
|
|
LostReason = null;
|
|
|
|
|
if (method == null && res.Has("accountType")) method = res.Has("provider") ? res.Str("provider") : MethodGuest;
|
|
|
|
|
if (method != null) Method = method;
|
|
|
|
|
Keep("refresh", refreshToken);
|
|
|
|
|
if (method != null) Keep("method", method);
|
|
|
|
|
if (!string.IsNullOrEmpty(socialId)) Keep("devid", socialId);
|
2026-11-17 04:55:28 +00:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|