# 플레이어 계정과 백엔드

이 가이드는 누가 플레이하는지 읽고, 로그인을 제공하고, 검증된 신원을 자체 백엔드로 보내고, 기존 게임 계정을 연결하는 방법을 [계정 시나리오](https://docs.zokogames.com/kr/requirements/accounts)별로 필요한 최소한의 코드로 보여 줍니다. 플레이어는 ZokoGames에 로그인했거나 게스트이며, 게임은 둘 다에서 동작해야 합니다. 예제는 [SDK 소개](https://docs.zokogames.com/kr/sdk/introduction#loading)에서처럼 `const SDK = window.ZokoGames.SDK;`를 가정합니다. 게스트, 토큰 같은 용어는 [용어집](https://docs.zokogames.com/kr/getting-started/glossary)에 있습니다.

## 1. 누가 플레이하는지 보여 주기

```js
await SDK.init();
const user = await SDK.user.getUser();            // null for guests
if (user) hud.setName(user.username, user.profilePictureUrl);

SDK.user.addAuthListener((u) => hud.setName(u.username, u.profilePictureUrl));
```

인증 리스너는 게임이 열려 있는 동안 플레이어가 포털 자체의 헤더에서 로그인할 때도 호출됩니다. `getUser()`는 비동기이며 게스트에게는 `null`로 이행됩니다. 플레이어가 로그아웃하면 포털이 게임을 게스트로 다시 시작합니다.

다른 상황에서 보게 되는 것: 오프라인에서는 플레이어가 이 기기에서 마지막으로 로그인한 사람이거나 게스트입니다. 어린이 모드에는 로그인이 전혀 없습니다(`showAuthPrompt`가 `userCancelled`로 끝남). 로컬 모드(여러분의 `localhost` 페이지)에서는 5단계의 스위치를 쓰지 않는 한 플레이어가 가짜 `user1`입니다.

## 2. 플레이어의 동작에서 로그인 제공하기 {#2-offer-sign-in-on-a-player-action}

```js
if (SDK.user.isUserAccountAvailable && !user) signInButton.hidden = false;
signInButton.onclick = async () => {
  try { await SDK.user.showAuthPrompt(); }
  catch (e) { if (e.code !== "userCancelled") console.warn(e.code); }
};
```

시작할 때 프롬프트를 자동으로 열지 마세요.

## 3. 검증된 신원을 서버로 보내기

브라우저는 `__dangerousUserId`를 속일 수 있지만 토큰은 위조할 수 없습니다.

```js
async function callBackend(path, body) {
  let token = null;
  try { token = await SDK.user.getUserToken(); } catch (e) { /* userNotAuthenticated: guest */ }
  return fetch("https://api.example.com" + path, {
    method: "POST",
    headers: { "content-type": "application/json", ...(token ? { authorization: `Bearer ${token}` } : {}) },
    body: JSON.stringify(body),
  });
}
```

서버에서는 포털의 공개 키로 서명을 검증하고, 만료를 확인하고, `gameId`가 게임의 id와 같은지 확인하세요. Node.js, Python, C#으로 작성된 완전한 검증기는 [user 모듈 레퍼런스](https://docs.zokogames.com/kr/sdk/user#verifying-on-your-server)에 있습니다. Express 미들웨어는 다음과 같습니다.

```js
import { createRemoteJWKSet, jwtVerify } from "jose";
const JWKS = createRemoteJWKSet(new URL("https://www.zokogames.com/.well-known/jwks.json"));

export async function zokoAuth(req, res, next) {
  const raw = (req.headers.authorization || "").replace(/^Bearer /, "");
  if (!raw) { req.player = null; return next(); }            // guest
  try {
    const { payload } = await jwtVerify(raw, JWKS, {
      algorithms: ["RS256"],
      issuer: "zokogames",
      audience: process.env.ZOKO_GAME_ID,
      clockTolerance: 5,
    });
    if (payload.gameId !== process.env.ZOKO_GAME_ID) throw new Error("wrong game");
    req.player = { id: payload.userId, name: payload.username };
    next();
  } catch {
    res.status(401).json({ error: "invalid_token" });
  }
}
```

토큰은 한 시간 동안 유효하며 `userId`, `gameId`, `username`, `profilePictureUrl`을 담고 있습니다. SDK는 토큰이 만료되기 1분 전까지 토큰을 캐시하므로 백엔드 요청마다 `getUserToken()`을 호출하세요. 로컬 모드는 서명되지 않은 토큰을 발급하며, 올바른 검증기는 이를 거부합니다.

같은 토큰으로 주간 리더보드에 점수를 제출하려면 [리더보드 단계별 설정](https://docs.zokogames.com/kr/guides/leaderboard-setup)을 참고하세요.

## 4. 기존 게임 계정 연결하기(전체 통합)

```js
async function onSignedIn() {
  const { linked } = await (await callBackend("/session", {})).json();
  if (linked) return;                                           // userId already linked: load that account
  const { response } = await SDK.user.showAccountLinkPrompt();
  if (response === "yes") await callBackend("/link", {});       // server links the verified userId to this game account
}
```

둘 다 진행 상황이 있는 두 계정을 병합하기보다는 새 계정에 연결하는 쪽을 권합니다. 그리고 검증된 `userId`를 항상 키로 취급하세요. 서버 측 예제가 포함된 전체 안내는 [계정 연결 단계별 설정](https://docs.zokogames.com/kr/guides/account-linking)에 있습니다.

## 5. 모든 경로를 로컬에서 테스트하기

| 경로 | URL 스위치 |
| --- | --- |
| 게스트 | `?user_response=logged_out` |
| 시작 시 로그인됨 | `?user_response=user1` |
| 버튼으로 로그인 | `?user_response=logged_out&show_auth_prompt_response=user2` |
| 플레이어가 취소 | `?show_auth_prompt_response=user_cancelled` |
| 연결 수락 / 거절 | `?link_account_response=yes` / `no` |
| 토큰 실패 / 만료 | `?token_response=logged_out` / `expired_token` |
| 계정이 전혀 없음 | `?user_account_available=false` |

## 다음 단계 {#next-steps}

- [계정 연동 단계별 가이드](https://docs.zokogames.com/kr/guides/account-linking)
- [User 모듈](https://docs.zokogames.com/kr/sdk/user)
