Nuxt v3 での Supabase 認証のセットアップ

Barbara Streisand
リリース: 2024-10-17 08:24:03
オリジナル
594 人が閲覧しました

認証の実装はほとんどのプロジェクトで行うことですが、実際に行う頻度が高いため、方法を覚えていない可能性があります。

ここでは、Nuxt v3 を使用した Supabase Auth の実装に関する簡単なハウツーを示します。この例では OTP を使用しますが、これはあらゆるケースに適用されます。

まず、Supabase の Web サイトにアクセスしてプロジェクトを開始します。

Supabase でプロジェクトを作成し、Nuxt でプロジェクトを開始した後、次の手順で Supabase Nuxt パッケージをインストールします。

npx nuxi@最新モジュール追加 supabase

次に、.env ファイルを作成し、次の環境変数を追加します。

SUPABASE_URL=<your_supabase_url>
SUPABASE_KEY=<your_supabase_key>
ログイン後にコピー

これらは、プロジェクトの Supabase ダッシュボードの [設定] -> [設定] で見つけることができます。 API

Setting up Supabase Auth with Nuxt v3

その後、プロジェクトをセットアップできます。これまでに 2 つの非常に基本的なファイルを作成しました:

  1. auth.ts (私は Pinia ストアを使用しましたが、通常のファイルだけを使用しても構いません)
import { defineStore } from "pinia";

export const useAuthStore = defineStore("auth", () => {
  const supabase = useSupabaseClient();

  const sendOtp = async (email: string) => {
    const { error } = await supabase.auth.signInWithOtp({
      email,
    });

    if (error) {
      throw error;
    }

    return true;
  };

  const verifyOtp = async (email: string, otp: string) => {
    const { error } = await supabase.auth.verifyOtp({
      type: "email",
      token: otp,
      email,
    });

    if (error) {
      throw error;
    }

    return true;
  };

  return {
    sendOtp,
    verifyOtp,
  };
});
ログイン後にコピー
  1. ログインフォーム.vue
<template>
  <div class="max-w-md mx-auto bg-white p-8 rounded-lg shadow-md">
    <h2 class="text-3xl font-bold mb-6 text-center text-gray-800">Welcome</h2>
    <form @submit.prevent="handleSubmit" class="space-y-6">
      <div v-if="mode === 'email'">
        <label for="email" class="block mb-2 font-medium text-gray-700"
          >Email</label
        >
        <input
          type="email"
          id="email"
          v-model="email"
          required
          placeholder="Enter your email"
          class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 transition duration-200"
        />
      </div>

      <div v-else-if="mode === 'code'">
        <p class="mb-2 font-medium text-gray-700">
          Enter the 6-digit code sent to {{ email }}
        </p>
        <input
          type="text"
          v-model="otpCode"
          required
          placeholder="Enter 6-digit code"
          maxlength="6"
          class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 transition duration-200"
        />
      </div>

      <UButton
        icon="i-heroicons-paper-airplane"
        size="lg"
        color="primary"
        variant="solid"
        :label="buttonLabel"
        :trailing="true"
        block
      />
    </form>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from "vue";
import { useAuthStore } from "~/stores/auth";

const authStore = useAuthStore();

const email = ref("");
const otpCode = ref("");
const mode = ref("email");

const buttonLabel = computed(() => {
  return mode.value === "email" ? "Send One-Time Password" : "Verify Code";
});

const handleSubmit = async () => {
  if (mode.value === "email") {
    try {
      await authStore.sendOtp(email.value);
      mode.value = "code";
    } catch (error) {
      console.log("Error sending OTP: ", error);
    }
  } else {
    try {
      await authStore.verifyOtp(email.value, otpCode.value);
    } catch (error) {
      console.log("Error verifying OTP: ", error);
    }
  }
};
</script>

<style scoped></style>
ログイン後にコピー

エラーが発生した場合に備えて、NuxtUI も使用していることに注意してください。

デフォルトでは、signInWithOtp 関数はマジック リンクを送信するため、トークンを送信するには Supabase のダッシュボードで電子メール テンプレートを変更する必要があります。

Setting up Supabase Auth with Nuxt v3
これは、「認証 ->」の下にあります。メールテンプレート -> {{ .Token }}

を使用するようにサインアップの確認と Magic Link テンプレートを変更します。

これでほぼ完了です。有効な認証が得られました!
サインアウトを追加したい場合は、次のようなメソッドを前のファイルに追加することもできます。

const signOut = async () => {
  const { error } = await supabase.auth.signOut();

  if (error) {
    throw error;
  }

  return true;
};
ログイン後にコピー

ただし、特定のルートを保護したい場合は、ミドルウェアを追加することもできます。

ルートに middleware という名前のフォルダー (名前は key) と auth.ts というファイルを作成します。

次のようなものを追加できます:

export default defineNuxtRouteMiddleware((to) => {
  const user = useSupabaseUser();

  const protectedRoutes = ["/app"];

  if (!user.value && protectedRoutes.includes(to.path)) {
    return navigateTo("/auth");
  }

  if (user.value && to.path === "/auth") {
    return navigateTo("/");
  }
});
ログイン後にコピー

これにより、基本的にサーバーから /app ルートが保護されるため、サインインせずに /app にアクセスしようとすると、/auth にリダイレクトされます。

同様に、既にサインインしているときに /auth にアクセスしようとすると、ホームページ /.

にリダイレクトされます。

これを使用するには、

著者別の最新記事
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!