> ## Documentation Index
> Fetch the complete documentation index at: https://docs.base44.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Auth モジュール

> `base44.auth` を介したユーザー認証、登録、セッション管理。

<Warning>
  このページは AI コーディングエージェントスキルの一部で、人間ではなくエージェント向けに書かれています。人間向けの Base44 ドキュメントは [デベロッパードキュメント](/developers) を参照してください。
</Warning>

# Auth モジュール

`base44.auth` を介したユーザー認証、登録、セッション管理。

## 目次

* [TypeScript の型](#typescript-types)
* [メソッド](#methods)
* [例](#examples)
* [エラー処理](#error-handling)
* [認証プロバイダー](#auth-providers)
* [環境での可用性](#environment-availability)
* [アプリの可視性](#app-visibility)
* [制限事項](#limitations)

***

## TypeScript の型

### User インターフェース

```typescript theme={null}
interface User {
  id: string;
  created_date: string;
  updated_date: string;
  email: string;
  full_name: string | null;
  disabled: boolean | null;
  is_verified: boolean;
  app_id: string;
  is_service: boolean;
  role: string;
  [key: string]: any; // Custom schema fields
}
```

### LoginResponse インターフェース

```typescript theme={null}
interface LoginResponse {
  access_token: string;  // JWT token
  user: User;           // Complete user object
}
```

### パラメーターインターフェース

#### RegisterParams

```typescript theme={null}
interface RegisterParams {
  email: string;                    // Required
  password: string;                 // Required
  turnstile_token?: string | null;  // Optional: Cloudflare Turnstile for bot protection
  referral_code?: string | null;    // Optional: Referral code
}
```

#### VerifyOtpParams

```typescript theme={null}
interface VerifyOtpParams {
  email: string;     // User's email
  otpCode: string;   // OTP code from email
}
```

#### ResetPasswordParams

```typescript theme={null}
interface ResetPasswordParams {
  resetToken: string;   // Token from password reset email
  newPassword: string;  // New password to set
}
```

#### ChangePasswordParams

```typescript theme={null}
interface ChangePasswordParams {
  userId: string;          // User ID
  currentPassword: string; // Current password for verification
  newPassword: string;     // New password to set
}
```

### Provider 型

```typescript theme={null}
type Provider = 'google' | 'microsoft' | 'facebook';
```

***

## メソッド

### モジュールインターフェース

```typescript theme={null}
interface AuthModule {
  // User Info
  me(): Promise<User>;
  updateMe(data: Partial<Omit<User, 'id' | 'created_date' | 'updated_date' | 'app_id' | 'is_service'>>): Promise<User>;
  isAuthenticated(): Promise<boolean>;

  // Login/Logout
  loginViaEmailPassword(email: string, password: string, turnstileToken?: string): Promise<LoginResponse>;
  loginWithProvider(provider: Provider, fromUrl?: string): void;
  logout(redirectUrl?: string): void;
  redirectToLogin(nextUrl: string): void;

  // Token Management
  setToken(token: string, saveToStorage?: boolean): void;

  // Registration
  register(params: RegisterParams): Promise<any>;
  verifyOtp(params: VerifyOtpParams): Promise<any>;
  resendOtp(email: string): Promise<any>;

  // User Management
  inviteUser(userEmail: string, role: string): Promise<any>;

  // Password Management
  resetPasswordRequest(email: string): Promise<any>;
  resetPassword(params: ResetPasswordParams): Promise<any>;
  changePassword(params: ChangePasswordParams): Promise<any>;
}
```

### メソッドリファレンス表

| メソッド                      | パラメーター                                                     | 戻り値の型                    | 説明                                                                                 |
| ------------------------- | ---------------------------------------------------------- | ------------------------ | ---------------------------------------------------------------------------------- |
| `register()`              | `params: RegisterParams`                                   | `Promise<any>`           | 新規ユーザーアカウントを作成                                                                     |
| `loginViaEmailPassword()` | `email: string, password: string, turnstileToken?: string` | `Promise<LoginResponse>` | メール/パスワードで認証                                                                       |
| `loginWithProvider()`     | `provider: Provider, fromUrl?: string`                     | `void`                   | OAuth ログインフローを開始。プロバイダー: `'google'` (デフォルト)、`'microsoft'`、`'facebook'` (アプリ設定で有効化) |
| `me()`                    | なし                                                         | `Promise<User>`          | 現在認証されているユーザーを取得                                                                   |
| `updateMe()`              | `data: Partial<User>`                                      | `Promise<User>`          | 現在のユーザーのプロフィールを更新                                                                  |
| `logout()`                | `redirectUrl?: string`                                     | `void`                   | サーバーサイドのログアウトへリダイレクト (HTTP-only cookies とセッションをクリア)、その後 redirectUrl または現在の URL へ   |
| `redirectToLogin()`       | `nextUrl: string`                                          | `void`                   | ⚠️ **回避** - `loginViaEmailPassword()` または `loginWithProvider()` でカスタムログイン UI を優先   |
| `isAuthenticated()`       | なし                                                         | `Promise<boolean>`       | ユーザーがログイン済みか確認                                                                     |
| `setToken()`              | `token: string, saveToStorage?: boolean`                   | `void`                   | 認証トークンを手動で設定                                                                       |
| `inviteUser()`            | `userEmail: string, role: string`                          | `Promise<any>`           | 招待メールを送信                                                                           |
| `verifyOtp()`             | `params: VerifyOtpParams`                                  | `Promise<any>`           | OTP コードを検証                                                                         |
| `resendOtp()`             | `email: string`                                            | `Promise<any>`           | OTP コードを再送                                                                         |
| `resetPasswordRequest()`  | `email: string`                                            | `Promise<any>`           | パスワードリセットを要求                                                                       |
| `resetPassword()`         | `params: ResetPasswordParams`                              | `Promise<any>`           | トークンでパスワードをリセット                                                                    |
| `changePassword()`        | `params: ChangePasswordParams`                             | `Promise<any>`           | ユーザーパスワードを変更                                                                       |

***

## 例

### 新規ユーザーの登録 (完全なフロー)

登録はログイン前にメール検証が必要です。完全なフロー:

1. **Register** - ユーザーアカウントを作成
2. **Verification email sent** - ユーザーが OTP コードを受信
3. **Verify OTP** - ユーザーがメールを検証するためにコードを入力
4. **Login** - ユーザーがログイン可能になる

```javascript theme={null}
try {
  // Step 1: Register the user
  await base44.auth.register({
    email: "user@example.com",
    password: "securePassword123",
    referral_code: "OPTIONAL_CODE",    // optional
    turnstile_token: "CAPTCHA_TOKEN"   // optional, for bot protection
  });
  console.log('Registration successful. Check email for OTP code.');

  // Step 2: User receives email with OTP code (e.g., "123456")

  // Step 3: Verify the OTP code
  await base44.auth.verifyOtp({
    email: "user@example.com",
    otpCode: "123456"  // code from verification email
  });
  console.log('Email verified successfully.');

  // Step 4: Now the user can log in
  const loginResponse = await base44.auth.loginViaEmailPassword(
    "user@example.com",
    "securePassword123"
  );
  console.log('Login successful:', loginResponse.user);

} catch (error) {
  console.error('Registration flow failed:', error.message);
  // Handle specific errors (see Error Handling section)
}
```

> **重要**: ユーザーは OTP 検証を完了するまでログインできません。検証前に `loginViaEmailPassword` を呼び出すと失敗します。

### メール/パスワードでログイン

```javascript theme={null}
try {
  const response = await base44.auth.loginViaEmailPassword(
    "user@example.com",
    "password123",
    turnstileToken  // optional: for bot protection
  );

  console.log('Login successful');
  console.log('User:', response.user);
  console.log('Token:', response.access_token);

  // JWT is automatically stored for subsequent requests

} catch (error) {
  console.error('Login failed:', error.message);
  if (error.status === 401) {
    console.error('Invalid credentials');
  } else if (error.status === 403) {
    console.error('Email not verified. Please check your email for OTP.');
  }
}
```

### OAuth プロバイダーでログイン

サポートされているプロバイダー: `'google'` (デフォルトで有効)、`'microsoft'`、`'facebook'`。Microsoft または Facebook を使用する前に、アプリの認証設定で有効化してください。

```javascript theme={null}
// Redirect to Google OAuth
base44.auth.loginWithProvider('google');

// Redirect to Google OAuth and return to current page after
base44.auth.loginWithProvider('google', window.location.href);

// Microsoft or Facebook (enable in app settings first)
base44.auth.loginWithProvider('microsoft');
base44.auth.loginWithProvider('facebook', '/dashboard');
```

### 現在のユーザーを取得

```javascript theme={null}
try {
  const user = await base44.auth.me();

  if (user) {
    console.log('User ID:', user.id);
    console.log('Email:', user.email);
    console.log('Name:', user.full_name);
    console.log('Role:', user.role);
    console.log('Verified:', user.is_verified);
  } else {
    console.log('User not authenticated');
  }

} catch (error) {
  console.error('Failed to fetch user:', error.message);
  if (error.status === 401) {
    // Token expired or invalid - navigate to your custom login page
    navigate('/login');
  }
}
```

### ユーザープロフィールの更新

```javascript theme={null}
try {
  const updatedUser = await base44.auth.updateMe({
    full_name: "John Doe",
    // Custom schema fields can be updated here
    phone: "+1234567890",
    preferences: { theme: "dark" }
  });

  console.log('Profile updated:', updatedUser);

} catch (error) {
  console.error('Profile update failed:', error.message);
  if (error.status === 400) {
    console.error('Invalid data provided');
  } else if (error.status === 401) {
    console.error('Authentication required');
    navigate('/login');
  }
}
```

### 認証状態の確認

```javascript theme={null}
try {
  const isLoggedIn = await base44.auth.isAuthenticated();

  if (isLoggedIn) {
    // Show authenticated UI
    console.log('User is authenticated');
  } else {
    // Show login button
    console.log('User is not authenticated');
  }

} catch (error) {
  console.error('Failed to check authentication:', error.message);
  // On error, treat as not authenticated
}
```

### ログアウト

Logout はユーザーをサーバーサイドのログアウトエンドポイント (`/api/apps/auth/logout`) にリダイレクトして HTTP-only クッキーとセッションをクリアし、その後指定された URL (省略時は現在のページ) にリダイレクトします。ブラウザー環境が必要です。

```javascript theme={null}
// Logout: clears session via server, then redirects to current page
base44.auth.logout();

// Logout and redirect to goodbye page after
base44.auth.logout("/goodbye");

// Logout and redirect to homepage
base44.auth.logout("/");
```

### 保護されたルートのパターン

```javascript theme={null}
// Using a navigation function (e.g., React Router's useNavigate, Next.js router)
async function requireAuth(navigate) {
  try {
    const user = await base44.auth.me();

    if (!user) {
      // Navigate to your custom login page
      navigate('/login', { state: { returnTo: window.location.pathname } });
      return null;
    }

    return user;

  } catch (error) {
    console.error('Authentication check failed:', error.message);
    navigate('/login', { state: { returnTo: window.location.pathname } });
    return null;
  }
}

// Usage in your app
async function loadProtectedPage(navigate) {
  const user = await requireAuth(navigate);
  if (!user) {
    // Will navigate to login
    return;
  }

  // Continue with authenticated logic
  console.log('Welcome,', user.full_name);
}
```

### 認証トークンの設定

```javascript theme={null}
// SECURITY WARNING: Never hardcode tokens or expose them in client code
// Tokens should only be received from secure authentication flows

// Set token and save to localStorage (default)
base44.auth.setToken(receivedToken);

// Set token without saving to localStorage (temporary session)
base44.auth.setToken(receivedToken, false);

// Verify token was set
try {
  const isAuthenticated = await base44.auth.isAuthenticated();
  if (!isAuthenticated) {
    console.error('Token validation failed');
  }
} catch (error) {
  console.error('Failed to set token:', error.message);
}
```

### アプリケーションへのユーザー招待

```javascript theme={null}
try {
  // Note: Typically requires admin privileges
  const response = await base44.auth.inviteUser(
    "newuser@example.com",
    "user"  // or "admin"
  );

  console.log('Invitation sent successfully');

} catch (error) {
  console.error('Failed to invite user:', error.message);
  if (error.status === 403) {
    console.error('Insufficient permissions to invite users');
  } else if (error.status === 400) {
    console.error('Invalid email or role');
  }
}
```

### OTP 検証

```javascript theme={null}
try {
  // Verify OTP code sent to user's email
  await base44.auth.verifyOtp({
    email: "user@example.com",
    otpCode: "123456"
  });

  console.log('OTP verified successfully');

} catch (error) {
  console.error('OTP verification failed:', error.message);
  if (error.status === 400) {
    console.error('Invalid or expired OTP code');
  } else if (error.status === 429) {
    console.error('Too many attempts. Please try again later.');
  }
}

// Resend OTP if needed
try {
  await base44.auth.resendOtp("user@example.com");
  console.log('OTP resent successfully');

} catch (error) {
  console.error('Failed to resend OTP:', error.message);
  if (error.status === 429) {
    console.error('Too many requests. Please wait before trying again.');
  }
}
```

### パスワードリセットフロー

```javascript theme={null}
// Step 1: Request password reset
try {
  await base44.auth.resetPasswordRequest("user@example.com");
  console.log('Password reset email sent. Check your inbox.');

} catch (error) {
  console.error('Password reset request failed:', error.message);
  if (error.status === 429) {
    console.error('Too many requests. Please try again later.');
  }
  // Note: For security, don't reveal if email exists
}

// Step 2: Reset password with token from email
try {
  await base44.auth.resetPassword({
    resetToken: "token-from-email",
    newPassword: "newSecurePassword123"
  });

  console.log('Password reset successfully. You can now log in.');

} catch (error) {
  console.error('Password reset failed:', error.message);
  if (error.status === 400) {
    console.error('Invalid or expired reset token');
  } else if (error.status === 422) {
    console.error('Password does not meet requirements');
  }
}
```

### パスワードの変更

```javascript theme={null}
try {
  const currentUser = await base44.auth.me();

  if (!currentUser) {
    throw new Error('User must be authenticated to change password');
  }

  await base44.auth.changePassword({
    userId: currentUser.id,
    currentPassword: "oldPassword123",
    newPassword: "newSecurePassword456"
  });

  console.log('Password changed successfully');

} catch (error) {
  console.error('Password change failed:', error.message);
  if (error.status === 401) {
    console.error('Current password is incorrect');
  } else if (error.status === 422) {
    console.error('New password does not meet requirements');
  } else if (error.status === 403) {
    console.error('Not authorized to change this password');
  }
}
```

***

## エラー処理

### 一般的なエラーシナリオ

auth モジュールはさまざまなエラーをスローする可能性があります。ここでは一般的なシナリオとその処理方法を示します:

#### 認証エラー (401/403)

```javascript theme={null}
try {
  const user = await base44.auth.me();
} catch (error) {
  if (error.status === 401) {
    // Token expired or invalid - navigate to your custom login page
    navigate('/login');
  } else if (error.status === 403) {
    // Email not verified or insufficient permissions
    console.error('Access denied:', error.message);
  }
}
```

#### 検証エラー (400/422)

```javascript theme={null}
try {
  await base44.auth.register({
    email: "invalid-email",
    password: "weak"
  });
} catch (error) {
  if (error.status === 400) {
    console.error('Invalid input:', error.message);
    // Handle validation errors
  } else if (error.status === 422) {
    console.error('Data validation failed:', error.details);
  }
}
```

#### レート制限 (429)

```javascript theme={null}
try {
  await base44.auth.resendOtp("user@example.com");
} catch (error) {
  if (error.status === 429) {
    console.error('Too many requests. Please wait before trying again.');
    // Show countdown or disable button temporarily
  }
}
```

#### 汎用エラーハンドラー

```javascript theme={null}
function handleAuthError(error) {
  switch (error.status) {
    case 400:
      return 'Invalid input. Please check your data.';
    case 401:
      return 'Authentication required. Redirecting to login...';
    case 403:
      return 'Access denied. You may need to verify your email.';
    case 404:
      return 'Resource not found.';
    case 422:
      return 'Validation failed. Please check your input.';
    case 429:
      return 'Too many requests. Please try again later.';
    case 500:
      return 'Server error. Please try again.';
    default:
      return 'An unexpected error occurred.';
  }
}

// Usage
try {
  await base44.auth.loginViaEmailPassword(email, password);
} catch (error) {
  console.error(handleAuthError(error));
}
```

***

## 認証プロバイダー

アプリダッシュボードで認証プロバイダーを構成します:

### 利用可能なプロバイダー

**組み込み (すべてのプラン):**

* **Email/Password** - デフォルト、常に有効
* **Google** - OAuth 認証
* **Microsoft** - OAuth 認証
* **Facebook** - OAuth 認証

**SSO プロバイダー (Elite プラン):**

* **Okta**
* **Azure AD**
* **GitHub**

### OAuth プロバイダーの使用

* **Google** – デフォルトで有効。
* **Microsoft** – 使用前にアプリの認証設定で有効化してください。
* **Facebook** – 使用前にアプリの認証設定で有効化してください。

```javascript theme={null}
// Initiate OAuth login flow
base44.auth.loginWithProvider('google');

// Return to specific page after authentication
base44.auth.loginWithProvider('microsoft', '/dashboard');

// Supported values: 'google', 'microsoft', 'facebook'
```

***

## 環境での可用性

| 環境           | 可用性   | 注意事項                                            |
| ------------ | ----- | ----------------------------------------------- |
| **フロントエンド**  | ✅ はい  | すべてのメソッドが利用可能                                   |
| **バックエンド関数** | ✅ はい  | 認証済みクライアントには `createClientFromRequest(req)` を使用 |
| **サービスロール**  | ❌ いいえ | Auth メソッドはサービスロールコンテキストでは利用不可                   |

### フロントエンドの使用

```javascript theme={null}
// Standard browser usage
const user = await base44.auth.me();
```

### バックエンド関数の使用

```javascript theme={null}
import { createClientFromRequest } from "@base44/sdk";

Deno.serve(async (req) => {
  const base44 = createClientFromRequest(req);

  // Get user from request context
  const user = await base44.auth.me();

  // User operations here...
  return Response.json({ user });
});
```

***

## アプリの可視性

アプリ設定でアプリにアクセスできる人を制御します:

### 公開アプリ

* 基本的なアクセスにログイン不要
* ユーザーは認証なしで公開コンテンツを閲覧可能
* 認証されたユーザーは追加機能/データを取得

### プライベートアプリ

* 任意のコンテンツにアクセスするにはログインが必要
* 未認証ユーザーは自動的にログインにリダイレクト
* すべてのコンテンツはデフォルトで保護

***

## 制限事項

### 認証 UI オプション

* **推奨:** `loginViaEmailPassword()` と `loginWithProvider()` を使用してカスタムログイン/サインアップ UI を構築し、ユーザーエクスペリエンスとブランディングを完全に制御します
* **代替:** `redirectToLogin()` は Base44 のホスト型認証ページを使用しますが、カスタマイズは限定的です

### ホスト型ログイン (redirectToLogin 経由)

* `redirectToLogin()` は同じページにログインとサインアップの両方のオプションを表示します
* 別の `redirectToSignup()` メソッドはありません
* ユーザーはホストページ上でログイン/サインアップを切り替え可能
* ⚠️ **注意:** より良いユーザーエクスペリエンスのためにカスタムログイン UI の構築を推奨します

### パスワード要件

* 最小長と複雑性要件が強制されます
* 要件は API 経由で公開されません
* 要件を満たさない場合、検証エラーが返されます

### レート制限

* 悪用を防ぐため、OTP リクエストはレート制限されます
* パスワードリセットリクエストはレート制限されます
* Turnstile 保護でログイン試行がレート制限される場合があります

### トークン管理

* JWT はデフォルトで localStorage に自動的に保存されます
* トークンの有効期限とリフレッシュは API に公開されていません
* トークンの有効性を検証するには `me()` または `isAuthenticated()` を呼び出します

***

## ベストプラクティス

### 1. 常にエラーを処理する

```javascript theme={null}
try {
  await base44.auth.loginViaEmailPassword(email, password);
} catch (error) {
  // Always handle authentication errors
  console.error('Login failed:', error.message);
}
```

### 2. 保護されたアクションの前に認証を確認する

```javascript theme={null}
const user = await requireAuth();
if (!user) return; // Will redirect to login
// Proceed with authenticated action
```

### 3. TypeScript で型安全性を使用する

```typescript theme={null}
import type { User, LoginResponse } from '@base44/sdk';

const user: User = await base44.auth.me();
const response: LoginResponse = await base44.auth.loginViaEmailPassword(email, password);
```

### 4. 認証情報をハードコードしない

```javascript theme={null}
// ❌ BAD
base44.auth.setToken("hardcoded-token-here");

// ✅ GOOD
const token = await secureAuthFlow();
base44.auth.setToken(token);
```

### 5. ユーザーにフィードバックを提供する

```javascript theme={null}
try {
  await base44.auth.register(params);
  showSuccessMessage('Registration successful! Check your email for verification code.');
} catch (error) {
  showErrorMessage('Registration failed: ' + error.message);
}
```

### 6. トークンの有効期限を優雅に処理する

```javascript theme={null}
try {
  const user = await base44.auth.me();
} catch (error) {
  if (error.status === 401) {
    // Clear local state and navigate to login
    localStorage.clear();
    navigate('/login');
  }
}
```

### 7. カスタムログイン UI を構築する (推奨)

```javascript theme={null}
// ✅ RECOMMENDED - Custom login form with direct methods
const handleLogin = async (email, password) => {
  try {
    const { user } = await base44.auth.loginViaEmailPassword(email, password);
    navigate('/dashboard');
  } catch (error) {
    setError(error.message);
  }
};

const handleGoogleLogin = () => {
  base44.auth.loginWithProvider('google', '/dashboard');
};

// ❌ AVOID - Redirecting to hosted login page
// base44.auth.redirectToLogin(window.location.href);
```

<Note>このページは AI を使用して翻訳されました。最も正確で最新の情報については、[英語版](/) を参照してください。 </Note>
