runlot
데이터인증

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()에는 반드시 요청 객체를 전달하세요. 세션 정보는 요청의 쿠키 또는 헤더에 있으며, env의 수명은 요청보다 길기 때문입니다. 인수를 빼면 env.auth.user(request): 요청 객체를 넘겨야 해요라는 오류가 발생합니다. Next.js의 @runlot/next에서는 어댑터가 현재 요청을 관리하므로 인수 없이 호출하는 예외가 있습니다.

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;
}

idrunlot_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("[email protected]");
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에 외부 URL을 전달하면 보안을 위해 무시합니다.

요청 없이 호출하는 방식

요청 인수 없이 env.auth.user()를 호출하는 방식은 프레임워크 어댑터가 제공하는 기능입니다. 현재 제공되는 어댑터는 Next.js의 @runlot/next뿐입니다. 다른 환경에서는 항상 요청 객체를 전달하세요.

이 페이지의 목차