ガイド

ログインとセキュリティルール

ユーザーがアプリでアカウントを作成できるようにし、各ユーザーが何を見て何を変更できるかをデータベースで決めます。

← すべてのガイド

1. 設定

認証 › 設定で、Site URLにアプリのアドレスを設定します。確認メールとパスワードリセットのメールはそこにリンクします。「メール確認を必須にする」はオフにできます(テスト中など)。認証では、ユーザーの一覧表示、無効化、パスワードリセットの送信、全デバイスからのログアウトも行えます。

2. 新規登録とログイン

// Sign up: Espobase sends a confirmation email that links to your Site URL.
const { error } = await espobase.auth.signUp({ email, password }); // passwords need 8+ characters

// After confirming, sign in. The session is stored and refreshed automatically.
await espobase.auth.signInWithPassword({ email, password });

const { data } = await espobase.auth.getUser(); // data.user.id, data.user.email
await espobase.auth.signOut();

4. GoogleまたはGitHubでログイン

Authentication › Providers でプロバイダーをオンにします。GoogleまたはGitHubでOAuthアプリを作成し、そこに表示されるコールバックURLを登録して、アプリのクライアントIDとクライアントシークレットを入力してください。シークレットは暗号化して保存され、再表示されません。あとは1回の呼び出しでプロバイダーに移動し、?code=… 付きでサイトURL(または許可されたリダイレクトURL)に戻ってきます。

// Sends the browser to Google; afterwards it comes back with ?code=… (or ?error=…).
await espobase.auth.signInWithOAuth({ provider: "google" }); // or "github"

// On the page it comes back to (your Site URL, or options.redirectTo):
const params = new URL(window.location.href).searchParams;
const code = params.get("code");
if (code) {
  const { error } = await espobase.auth.exchangeCodeForSession(code); // signs the user in
  history.replaceState(null, "", window.location.pathname);
}

受け付けるのはプロバイダーが確認済みのメールアドレスだけです。既存のアカウントと結び付くのは、そのアカウントのメールも確認済みの場合に限ります。ログインを完了できない場合、URLには ?error=…(例: access_denied、account_exists)と表示用の error_description が付きます。

5. パスワードなしでログイン

Authentication › Settings で パスワードなしのメールログイン をオンにします。1通のメールにログイン用リンクと6桁のコードが入り、どちらも10分間、1回だけ使えます。別の端末ではコードを使うなど、使いやすい方でログインできます:

// Emails a sign-in link and a 6-digit code (same answer whether or not the account exists).
await espobase.auth.signInWithOtp({ email });

// The user types the code…
await espobase.auth.verifyOtp({ email, code });

// …or opens the link: your Site URL with #type=magiclink&token=…
const params = new URLSearchParams(window.location.hash.slice(1));
if (params.get("type") === "magiclink") {
  await espobase.auth.verifyOtp({ token: params.get("token")! });
  history.replaceState(null, "", window.location.pathname);
}

6. 2段階認証とメールアドレスの変更

Authentication › Settings で、2段階認証を任意または必須にできます。最初のステップの後に、認証アプリまたはメールのコード、またはリカバリーコードを入力します。「ユーザーによるメールアドレスの変更を許可」をオンにすると、ログイン中のユーザーが新しいアドレスに変更でき、リンクで確認されます。以前のアドレスには通知が送られます。

// With two-step sign-in, a sign-in can wait for its second step:
const { error } = await espobase.auth.signInWithPassword({ email, password });
if (error?.code === "mfa_required") {
  await espobase.auth.mfa.verify({ code }); // authenticator, emailed code (mfa.challenge()) or recovery code
}

// Signed in: set up an authenticator app (show data.uri as a QR code), then confirm it with a code.
const { data } = await espobase.auth.mfa.enroll({ type: "totp" });
const { data: done } = await espobase.auth.mfa.verifyEnrollment({ factorId: data!.factorId, code });
// done.recoveryCodes: show them once

// Change the email address (confirmed by a link to the new address: #type=email_change&token=…)
await espobase.auth.updateUser({ email: newEmail, currentPassword });
await espobase.auth.verifyEmailChange({ token });

7. セキュリティルール(行レベルセキュリティ)

行レベルセキュリティはすべてのテーブルで有効です。ポリシーを追加するまで、APIを通じてそのテーブルを読み書きできる人はいません。ポリシーの中では、espobase.user_id()がログイン中のユーザーのIDです(ログインしていない訪問者の場合は空)。

-- Each user sees and changes only their own rows:
create policy "Own notes" on notes
  for all
  using (owner_id = espobase.user_id())
  with check (owner_id = espobase.user_id());

-- Everyone may read published posts; only signed-in users may write:
create policy "Read published posts" on posts for select using (published);
create policy "Signed-in users post" on posts for insert with check (espobase.user_id() is not null);

ダッシュボードのデータベース › ポリシーでは、同じものをテンプレート(公開読み取り、ログインユーザーのみ、ユーザーが行の所有者、組織のメンバーシップ)として利用でき、適用前にSQLが表示されます。

8. どこでどのキーを使うか

  • 公開可能キー(eb_pk_…):アプリとブラウザで使います。すべてのリクエストはログイン中のユーザー(または訪問者)として実行されるため、ポリシーが判断します。
  • シークレットキー(eb_sk_…):Webhookなどの処理のために、自分のサーバーでのみ使います。ポリシーをバイパスするため、絶対にブラウザに送らないでください。