> ## 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-Modul

> Nutzerauthentifizierung, -registrierung und Sitzungsverwaltung über base44.auth.

<Warning>
  Diese Seite ist Teil eines KI-Coding-Agent-Skills und für Agenten geschrieben, nicht für Menschen. Für die menschenlesbare Base44-Dokumentation siehe die [Entwicklerdokumentation](/developers).
</Warning>

# Auth-Modul

Nutzerauthentifizierung, -registrierung und Sitzungsverwaltung über `base44.auth`.

## Inhalt

* [TypeScript Types](#typescript-types)
* [Methoden](#methoden)
* [Beispiele](#beispiele)
* [Fehlerbehandlung](#fehlerbehandlung)
* [Auth-Anbieter](#auth-anbieter)
* [Verfügbarkeit in Umgebungen](#verfügbarkeit-in-umgebungen)
* [App-Sichtbarkeit](#app-sichtbarkeit)
* [Einschränkungen](#einschränkungen)

***

## TypeScript Types

### User-Interface

```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-Interface

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

### Parameter-Interfaces

#### 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-Typ

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

***

## Methoden

### Modul-Interface

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

### Methoden-Referenztabelle

| Methode                   | Parameter                                                  | Rückgabetyp              | Beschreibung                                                                                                             |
| ------------------------- | ---------------------------------------------------------- | ------------------------ | ------------------------------------------------------------------------------------------------------------------------ |
| `register()`              | `params: RegisterParams`                                   | `Promise<any>`           | Neues Nutzerkonto erstellen                                                                                              |
| `loginViaEmailPassword()` | `email: string, password: string, turnstileToken?: string` | `Promise<LoginResponse>` | Mit E-Mail/Passwort authentifizieren                                                                                     |
| `loginWithProvider()`     | `provider: Provider, fromUrl?: string`                     | `void`                   | OAuth-Login-Flow starten. Anbieter: `'google'` (Standard), `'microsoft'`, `'facebook'` (in App-Einstellungen aktivieren) |
| `me()`                    | Keine                                                      | `Promise<User>`          | Aktuell authentifizierten Nutzer holen                                                                                   |
| `updateMe()`              | `data: Partial<User>`                                      | `Promise<User>`          | Profil des aktuellen Nutzers aktualisieren                                                                               |
| `logout()`                | `redirectUrl?: string`                                     | `void`                   | Zum serverseitigen Logout weiterleiten (löscht HTTP-only-Cookies und Sitzung), dann zu redirectUrl oder aktueller URL    |
| `redirectToLogin()`       | `nextUrl: string`                                          | `void`                   | ⚠️ **Vermeiden** — bevorzuge benutzerdefinierte Login-UI mit `loginViaEmailPassword()` oder `loginWithProvider()`        |
| `isAuthenticated()`       | Keine                                                      | `Promise<boolean>`       | Prüfen, ob Nutzer eingeloggt ist                                                                                         |
| `setToken()`              | `token: string, saveToStorage?: boolean`                   | `void`                   | Auth-Token manuell setzen                                                                                                |
| `inviteUser()`            | `userEmail: string, role: string`                          | `Promise<any>`           | Einladungs-E-Mail senden                                                                                                 |
| `verifyOtp()`             | `params: VerifyOtpParams`                                  | `Promise<any>`           | OTP-Code verifizieren                                                                                                    |
| `resendOtp()`             | `email: string`                                            | `Promise<any>`           | OTP-Code erneut senden                                                                                                   |
| `resetPasswordRequest()`  | `email: string`                                            | `Promise<any>`           | Passwort-Reset anfordern                                                                                                 |
| `resetPassword()`         | `params: ResetPasswordParams`                              | `Promise<any>`           | Passwort mit Token zurücksetzen                                                                                          |
| `changePassword()`        | `params: ChangePasswordParams`                             | `Promise<any>`           | Nutzerpasswort ändern                                                                                                    |

***

## Beispiele

### Neuen Nutzer registrieren (vollständiger Ablauf)

Die Registrierung erfordert E-Mail-Verifizierung vor dem Login. Vollständiger Ablauf:

1. **Registrieren** — Das Nutzerkonto erstellen
2. **Verifizierungs-E-Mail versendet** — Nutzer erhält einen OTP-Code
3. **OTP verifizieren** — Nutzer gibt Code ein, um E-Mail zu verifizieren
4. **Login** — Nutzer kann sich jetzt anmelden

```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)
}
```

> **Wichtig**: Nutzer können sich nicht anmelden, bis sie die OTP-Verifizierung abgeschlossen haben. Ein Aufruf von `loginViaEmailPassword` vor der Verifizierung schlägt fehl.

### Login mit E-Mail/Passwort

```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.');
  }
}
```

### Login mit OAuth-Anbieter

Unterstützte Anbieter: `'google'` (standardmäßig aktiviert), `'microsoft'` und `'facebook'`. Aktiviere Microsoft oder Facebook in den Authentifizierungs-Einstellungen deiner App vor der Nutzung.

```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');
```

### Aktuellen Nutzer holen

```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');
  }
}
```

### Nutzerprofil aktualisieren

```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');
  }
}
```

### Authentifizierungsstatus prüfen

```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

Der Logout leitet den Nutzer zum serverseitigen Logout-Endpunkt (`/api/apps/auth/logout`) weiter, um HTTP-only-Cookies und die Sitzung zu löschen, und dann zur angegebenen URL (oder zur aktuellen Seite, wenn weggelassen). Erfordert eine Browser-Umgebung.

```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("/");
```

### Geschütztes-Routen-Muster

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

### Auth-Token setzen

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

### Nutzer in Anwendung einladen

```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-Verifizierung

```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.');
  }
}
```

### Passwort-Reset-Ablauf

```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');
  }
}
```

### Passwort ändern

```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');
  }
}
```

***

## Fehlerbehandlung

### Häufige Fehlerszenarien

Das Auth-Modul kann verschiedene Fehler werfen. Hier sind häufige Szenarien und wie du sie behandelst:

#### Authentifizierungsfehler (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);
  }
}
```

#### Validierungsfehler (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);
  }
}
```

#### Rate-Limiting (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
  }
}
```

#### Generischer Fehler-Handler

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

***

## Auth-Anbieter

Konfiguriere Authentifizierungsanbieter in deinem App-Dashboard:

### Verfügbare Anbieter

**Integriert (alle Tarife):**

* **E-Mail/Passwort** — Standard, immer aktiviert
* **Google** — OAuth-Authentifizierung
* **Microsoft** — OAuth-Authentifizierung
* **Facebook** — OAuth-Authentifizierung

**SSO-Anbieter (Elite-Tarif):**

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

### OAuth-Anbieter verwenden

* **Google** — standardmäßig aktiviert.
* **Microsoft** — vor der Nutzung in den Authentifizierungs-Einstellungen deiner App aktivieren.
* **Facebook** — vor der Nutzung in den Authentifizierungs-Einstellungen deiner App aktivieren.

```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'
```

***

## Verfügbarkeit in Umgebungen

| Umgebung               | Verfügbarkeit | Hinweise                                                                 |
| ---------------------- | ------------- | ------------------------------------------------------------------------ |
| **Frontend**           | ✅ Ja          | Alle Methoden verfügbar                                                  |
| **Backend-Funktionen** | ✅ Ja          | Verwende `createClientFromRequest(req)` für den authentifizierten Client |
| **Service-Rolle**      | ❌ Nein        | Auth-Methoden sind im Service-Rollen-Kontext nicht verfügbar             |

### Frontend-Nutzung

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

### Backend-Funktionen-Nutzung

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

***

## App-Sichtbarkeit

Steuere in den App-Einstellungen, wer auf deine App zugreifen kann:

### Öffentliche Apps

* Kein Login für grundlegenden Zugriff nötig
* Nutzer können öffentliche Inhalte ohne Authentifizierung ansehen
* Authentifizierte Nutzer erhalten zusätzliche Features/Daten

### Private Apps

* Login zum Zugriff auf jeden Inhalt nötig
* Nicht authentifizierte Nutzer werden automatisch zum Login weitergeleitet
* Alle Inhalte sind standardmäßig geschützt

***

## Einschränkungen

### Authentifizierungs-UI-Optionen

* **Empfohlen:** Baue eine benutzerdefinierte Login-/Signup-UI mit `loginViaEmailPassword()` und `loginWithProvider()` für volle Kontrolle über Nutzererlebnis und Branding
* **Alternative:** `redirectToLogin()` verwendet Base44s gehostete Authentifizierungsseiten mit begrenzter Anpassung

### Gehostetes Login (über redirectToLogin)

* `redirectToLogin()` zeigt Login- und Signup-Optionen auf derselben Seite
* Keine separate `redirectToSignup()`-Methode
* Nutzer können auf der gehosteten Seite zwischen Login/Signup wechseln
* ⚠️ **Hinweis:** Bevorzuge eine benutzerdefinierte Login-UI für ein besseres Nutzererlebnis

### Passwort-Anforderungen

* Mindestlänge und Komplexitätsanforderungen werden durchgesetzt
* Anforderungen sind nicht per API einsehbar
* Bei Nichterfüllung werden Validierungsfehler zurückgegeben

### Rate-Limiting

* OTP-Anfragen sind ratenbegrenzt, um Missbrauch zu verhindern
* Passwort-Reset-Anfragen sind ratenbegrenzt
* Login-Versuche können mit Turnstile-Schutz ratenbegrenzt sein

### Token-Management

* JWTs werden standardmäßig automatisch im localStorage gespeichert
* Token-Ablauf und -Refresh sind nicht per API einsehbar
* Rufe `me()` oder `isAuthenticated()` auf, um die Token-Gültigkeit zu prüfen

***

## Best Practices

### 1. Immer Fehler behandeln

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

### 2. Authentifizierung vor geschützten Aktionen prüfen

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

### 3. Typsicherheit mit TypeScript nutzen

```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. Keine Anmeldedaten hartcodieren

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

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

### 5. Nutzerfeedback geben

```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. Token-Ablauf sauber handhaben

```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. Benutzerdefinierte Login-UI bauen (empfohlen)

```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>Diese Seite wurde mit KI übersetzt. Für die genauesten und aktuellsten Informationen siehe die [englische Version](/). </Note>
