# Google 로그인 붙이기

> 방명록 예제에 somaro의 방문자 로그인을 붙이고, Google 없이 로그인된 쪽을 시험해 봐요.

웹 페이지: https://guides.somaro.ai/guides/add-login.html

앱 방문자가 Google로 로그인하게 하고 싶다면 somaro의 로그인을 쓰세요. Google에 앱을 등록하지 않아도 되고 OAuth 라이브러리도, 보관할 클라이언트 ID나 비밀 키도 없어요. 앱은 링크 하나를 걸고 요청 헤더를 읽기만 하면 돼요. 이 가이드에서는 [SQLite를 쓰는 앱 올리기](https://guides.somaro.ai/guides/sqlite-app.html)의 방명록에 로그인을 붙여서 로그인한 사람만 글을 남기게 해 봐요. (상태: 서버 앱만)

서버가 있는 앱에서만 되고 정적 사이트에서는 안 돼요.

에이전트에게 맡긴다면 이 한 줄이면 돼요. 아래는 에이전트가 하는 일을 직접 따라가 보는 내용이에요.

> 에이전트에게 이렇게 말해요: 이 앱에 somaro 로그인을 붙여줘. 로그인한 사람만 글을 남길 수 있게 해줘

## 로그인이 동작하는 방식

| 하는 일 | 방법 |
| --- | --- |
| 로그인시키기 | 앱 주소의 `/.somaro/login?next=/path`로 링크를 걸어요. 로그인이 끝나면 `next`의 경로로 돌아와요. |
| 누구인지 알기 | 로그인한 방문자의 모든 요청에 `X-Somaro-User-Id` 같은 헤더가 붙어 와요. |
| 로그인 요구하기 | 헤더가 없으면 로그인 링크로 리다이렉트해요. |
| 로그아웃 | `/.somaro/logout?next=/`로 POST를 보내요. 버튼 하나짜리 폼이면 돼요. |
| 다른 계정으로 로그인 | `/.somaro/login?next=/&account=choose`로 링크를 걸어요. |
| 페이지의 스크립트에서 확인 | `GET /.somaro/me`를 불러요. 로그인했으면 200과 방문자 정보(JSON), 아니면 401이에요. |

`/.somaro/` 아래 경로는 somaro가 직접 답하고 앱에는 도달하지 않아요. `next`에는 앱 안의 경로(`/notes?x=1` 같은)만 쓸 수 있고 그 밖의 값은 `/`로 처리돼요.

로그인한 방문자의 요청에 붙는 헤더는 이래요.

| 헤더 | 내용 |
| --- | --- |
| `X-Somaro-User-Id` | 이 앱에서만 쓰이는, 변하지 않는 사용자 ID. 앱의 사용자를 이 값으로 구분해요. 이 헤더가 없으면 아무도 로그인하지 않은 거예요. |
| `X-Somaro-User-Email` | 이메일 주소 |
| `X-Somaro-User-Email-Verified` | Google이 주소를 확인했으면 `true` |
| `X-Somaro-User-Name` | 이름. 퍼센트 인코딩된 UTF-8이라 디코드해서 써요. 이름 없는 계정이면 헤더가 없을 수 있어요. |
| `X-Somaro-User-Picture` | 프로필 사진의 https 주소. 없을 수 있어요. |

방문자가 이 헤더들을 직접 보내도 somaro가 떼어 버려요. 그래서 앱은 헤더를 그대로 믿어도 돼요.

## 코드 고치기

방명록의 `app.py`를 아래처럼 바꿔요. 이름 입력 칸을 없애고 로그인한 사람의 이름을 써요.

```python title="guestbook/app.py"
import html
import os
import sqlite3
import tempfile
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs, unquote

DATA_DIR = "/workspace" if os.path.isdir("/workspace") else tempfile.gettempdir()
DB_PATH = os.path.join(DATA_DIR, "guestbook.db")
ON_SOMARO = bool(os.environ.get("PUBLIC_URL"))

def connect():
    return sqlite3.connect(DB_PATH)

def visitor(headers):
    """로그인한 방문자를 돌려준다. 아무도 로그인하지 않았으면 None."""
    if not ON_SOMARO:
        # 내 컴퓨터에는 somaro가 없으니 고정 테스트 사용자로 돌린다.
        return {"id": "u_local", "name": "로컬 테스트"}
    user_id = headers.get("X-Somaro-User-Id")
    if not user_id:
        return None
    name = unquote(headers.get("X-Somaro-User-Name", ""))
    return {"id": user_id, "name": name or headers.get("X-Somaro-User-Email", "이름 없음")}

def page(user):
    with connect() as db:
        rows = db.execute("SELECT name, body, at FROM notes ORDER BY id DESC LIMIT 50").fetchall()
    notes = "".join(
        f"<li><b>{html.escape(name)}</b> {html.escape(body)} <small>{at}</small></li>"
        for name, body, at in rows
    )
    if user:
        top = f"""<p>{html.escape(user["name"])} 님으로 쓰는 중이에요.</p>
<form method="post" action="/notes">
  <input name="body" placeholder="한마디" required maxlength="200">
  <button>남기기</button>
</form>
<form method="post" action="/.somaro/logout?next=/"><button>로그아웃</button></form>"""
    else:
        top = '<p><a href="/.somaro/login?next=/">Google로 로그인</a>하면 글을 남길 수 있어요.</p>'
    return f"""<!doctype html>
<html lang="ko"><meta charset="utf-8"><title>방명록</title>
<h1>방명록</h1>
{top}
<ul>{notes}</ul>
</html>"""

class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path != "/":
            self.send_error(404)
            return
        body = page(visitor(self.headers)).encode()
        self.send_response(200)
        self.send_header("Content-Type", "text/html; charset=utf-8")
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def do_POST(self):
        if self.path != "/notes":
            self.send_error(404)
            return
        user = visitor(self.headers)
        if not user:
            # 로그인하지 않은 요청은 로그인 화면으로 보낸다.
            self.send_response(303)
            self.send_header("Location", "/.somaro/login?next=/")
            self.end_headers()
            return
        length = int(self.headers.get("Content-Length", 0))
        form = parse_qs(self.rfile.read(length).decode())
        body = form.get("body", [""])[0].strip()
        if body:
            with connect() as db:
                db.execute(
                    "INSERT INTO notes (user_id, name, body) VALUES (?, ?, ?)",
                    (user["id"], user["name"], body),
                )
        self.send_response(303)
        self.send_header("Location", "/")
        self.end_headers()

if __name__ == "__main__":
    with connect() as db:
        db.execute(
            "CREATE TABLE IF NOT EXISTS notes ("
            "id INTEGER PRIMARY KEY, name TEXT, body TEXT, "
            "at TEXT DEFAULT CURRENT_TIMESTAMP)"
        )
        columns = [row[1] for row in db.execute("PRAGMA table_info(notes)")]
        if "user_id" not in columns:
            db.execute("ALTER TABLE notes ADD COLUMN user_id TEXT")
    port = int(os.environ.get("PORT", "5000"))
    ThreadingHTTPServer(("0.0.0.0", port), Handler).serve_forever()
```

바뀐 곳을 짚어 볼게요.

- `visitor()`가 헤더에서 방문자를 읽어요. `X-Somaro-User-Id`가 없으면 `None`을 돌려줘요. 이름은 `unquote`로 디코드하고 이름이 없으면 이메일을 대신 보여 줘요.
- 내 컴퓨터에는 somaro가 없어서 헤더가 오지 않아요. somaro는 앱에 `PUBLIC_URL` 환경 변수로 공개 주소를 알려 주니, 이 값이 없으면 내 컴퓨터로 보고 고정된 테스트 사용자로 돌려요. 그래야 로컬에서도 앱이 돌아가요.
- `POST /notes`는 방문자가 없으면 `/.somaro/login?next=/`로 보내요.
- 로그인한 사람에게는 글쓰기 폼과 로그아웃 버튼을, 아닌 사람에게는 로그인 링크를 보여 줘요. 로그아웃은 링크가 아니라 POST 폼이에요.
- 글에 `user_id`를 함께 저장해요. 이미 있는 표에는 시작할 때 열을 하나 더해요.

**도움말: 폼 위조를 따로 막지 않아도 돼요**
로그인 쿠키는 somaro의 것이고 `SameSite=Lax`에 이 앱 주소 전용이에요. 다른 사이트에서 보낸 폼은 `X-Somaro-User-Id` 없이 도착하니, 로그인이 필요한 동작을 바깥에서 위조할 수 없어요.

## 올리고 시험하기

1. 내 컴퓨터에서 먼저 돌려 봐요. `PUBLIC_URL`이 없으니 "로컬 테스트"라는 이름으로 글이 남아요.

   ```sh
   python3 app.py
   ```

2. 다시 올려요.

   **curl**

   ```sh
   tar -czf "$HOME/.somaro/guestbook.tgz" --exclude .git --exclude node_modules --exclude .env .
   curl -sS -K "$HOME/.somaro/somaro.ai/token" -H "X-Somaro-Skill: 2026-12-04c" -T "$HOME/.somaro/guestbook.tgz" "https://somaro.ai/v1/apps/guestbook?yes"
   ```

   **CLI**

   ```sh
   somaro deploy . --yes
   ```

3. 로그인하지 않은 쪽을 확인해요. 주소를 열면 "Google로 로그인" 링크가 보여야 해요.

4. 시험 글을 나중에 지울 수 있게 복원 지점을 하나 만들어 둬요.

   **curl**

   ```sh
   curl -sS -K "$HOME/.somaro/somaro.ai/token" -X POST https://somaro.ai/v1/apps/guestbook/backup
   ```

   **CLI**

   ```sh
   somaro backup guestbook
   ```

5. 테스트 방문자 쿠키를 받아요. somaro가 만든 테스트 방문자로 15분 동안 이 앱에 로그인된 요청을 보낼 수 있어요.

   **curl**

   ```sh
   curl -sS -K "$HOME/.somaro/somaro.ai/token" -X POST https://somaro.ai/v1/apps/guestbook/test-visitor
   ```

   응답에 `cookie`, `try`, `visitor`, `expires_at`이 들어 있어요.

   **CLI**

   ```sh
   somaro visitor guestbook
   ```

6. 받은 쿠키로 로그인된 쪽을 확인해요. `<cookie>`에 받은 값을, 주소에는 내 앱 주소를 넣어요.

   ```sh
   curl -H 'Cookie: <cookie>' https://guestbook.somaro.dev/
   curl -H 'Cookie: <cookie>' -d 'body=테스트 글' -o /dev/null -w "%{http_code}\n" https://guestbook.somaro.dev/notes
   ```

   첫 줄의 응답에 글쓰기 폼이 보이고 둘째 줄은 303으로 답해야 해요.

7. 시험하면서 남긴 글이 방명록에 보이면 지워요. 이 예제에는 글을 지우는 기능이 없으니 4번에서 만든 복원 지점으로 되돌리면 돼요. 방법은 [SQLite를 쓰는 앱 올리기](https://guides.somaro.ai/guides/sqlite-app.html)에 있어요.

8. 마지막으로 브라우저에서 내가 직접 Google로 한 번 로그인해 봐요. Google 화면을 거치는 단계는 테스트 쿠키로 확인할 수 없어요.

테스트 방문자는 앱이 보기에 로그인한 여느 사람과 같아요. 이름은 Test Visitor, 이메일은 `test-visitor@somaro.invalid`, ID는 `u_test_`로 시작해요. 실제 사람에게는 없는 `X-Somaro-User-Test: true` 헤더가 함께 붙어서 앱이 원하면 테스트 요청을 가려낼 수 있어요.

## 방문자가 보게 되는 것

로그인 링크를 누른 방문자에게는 먼저 somaro의 페이지가 나와요. 어떤 앱에 로그인하려는지 앱 이름을 보여 주고 이 앱이 somaro가 만든 것이 아니라고 알려 줘요. 무료 앱에서는 이 페이지가 몇 초 기다리게 하고 유료 플랜에서는 기다림이 없어요. 로그인을 붙일 때 방문자에게 이 화면이 보인다는 걸 알아 두세요.

로그인은 7일 동안 유지돼요. 로그아웃은 이 앱에서만 끝나고 그 뒤 이 앱에 다시 로그인할 때는 Google이 어느 계정을 쓸지 물어봐요.

## 원래 로그인이 있던 앱이라면

자체 로그인이 있는 앱은 그대로 둬도 돼요. somaro 로그인으로 옮기고 싶을 때만 옮기고 그때는 기존 사용자와 이메일 주소로 맞춰 주세요.

자체 로그인을 쿠키로 유지한다면 쿠키 이름에 `__Host-` 접두사를 붙이고(`__Host-session` 같은 식) `Secure`, `Path=/`로, `Domain` 없이 설정하세요. 다른 사람의 앱도 같은 상위 도메인 아래에 있어서 접두사 없는 쿠키는 다른 앱이 심어 놓을 수 있어요.

## 관련 문서

- [방문자 로그인](https://guides.somaro.ai/features/login.html)
- [앱 주소에서 쓰는 경로와 헤더](https://guides.somaro.ai/api/in-app.html)
- [SQLite를 쓰는 앱 올리기](https://guides.somaro.ai/guides/sqlite-app.html)
- [플랜과 결제](https://guides.somaro.ai/features/plans.html)
