데이터인증
env.auth.user
요청을 넘기면 누구인지 알려 줍니다. 아니면 null 입니다.
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const user = await env.auth.user(request);
if (!user) return Response.redirect(new URL("/__runlot/auth/sign-in", request.url));
return Response.json({ email: user.email });
},
};user() 에는 요청 객체를 넘겨야 합니다 (Next.js 의 @runlot/next 는 예외 — 어댑터가 요청을 대신 들고 있어 인자 없이 부릅니다). 세션은 요청의 쿠키나 헤더에 있고, env 는 요청보다 오래 살기 때문입니다. 빠뜨리면 이렇게 알려 줍니다 — env.auth.user(request): 요청 객체를 넘겨야 해요.User
export interface User {
id: string; // uuid
email: string | null;
emailVerified: boolean;
name: string | null;
avatarUrl: string | null;
providers: string[]; // 예: ["password", "github"]
createdAt: string; // ISO 8601
lastSignInAt: string | null;
}id 는 runlot_auth.users 의 기본 키입니다. 여러분의 표에서 소유자를 가리킬 때 이 값을 쓰세요.
create table posts (
id bigserial primary key,
owner_id uuid not null,
title text not null
);const user = await env.auth.user(request);
await env.db.exec("insert into posts (owner_id, title) values ($1, $2)", [user.id, title]);로그아웃
if (url.pathname === "/logout") {
return new Response(null, {
status: 302,
headers: { location: "/", ...(await env.auth.signOut(request)) },
});
}signOut 은 세션을 지우고, 쿠키를 비우는 헤더 객체를 돌려줍니다. 브라우저 폼으로 처리하시려면 POST /__runlot/auth/sign-out 로 보내셔도 됩니다.
사용자 관리
const u = await env.auth.users.get(id);
const byEmail = await env.auth.users.getByEmail("a@example.com");
const page = await env.auth.users.list({ limit: 50, cursor });
await env.auth.users.update(id, { name: "새 이름" });
await env.auth.users.delete(id);
await env.auth.sessions.revokeAll(userId);list 의 기본 개수는 50, 최대 200 입니다. cursor 가 빈 문자열이면 마지막 쪽입니다.
브라우저 쪽 헬퍼
import { session, signInUrl, signOutUrl } from "@runlot/auth/client";
const { user } = await session(); // 로그인 안 했으면 { user: null }
location.href = signInUrl("github", { next: "/app" });의존성이 없는 작은 모듈입니다. next 로 넘긴 값이 외부 주소면 조용히 무시합니다.
아직 없는 것
env.auth.user() 를 요청 없이 부르는 방식은 프레임워크 어댑터가 하는 일이고, 그 어댑터가 아직 없습니다. 지금은 언제나 요청을 넘겨 주세요.