Add Facebook social login
Some checks failed
linter / quality (push) Has been cancelled
tests / ci (push) Has been cancelled
tests / ui (push) Has been cancelled

This commit is contained in:
Codex Agent
2026-01-23 20:19:15 +01:00
parent db90b9af2e
commit 73728f6baf
29 changed files with 991 additions and 88 deletions

View File

@@ -97,6 +97,11 @@ GOOGLE_CLIENT_ID=
GOOGLE_CLIENT_SECRET=
GOOGLE_REDIRECT_URI=${APP_URL}/checkout/auth/google/callback
# Facebook OAuth (Checkout comfort login)
FACEBOOK_CLIENT_ID=
FACEBOOK_CLIENT_SECRET=
FACEBOOK_REDIRECT_URI=${APP_URL}/checkout/auth/facebook/callback
VITE_APP_NAME="${APP_NAME}"
VITE_ENABLE_TENANT_SWITCHER=false
REVENUECAT_WEBHOOK_SECRET=

View File

@@ -48,6 +48,9 @@ class CheckoutController extends Controller
$googleStatus = session()->pull('checkout_google_status');
$googleError = session()->pull('checkout_google_error');
$googleProfile = session()->pull('checkout_google_profile');
$facebookStatus = session()->pull('checkout_facebook_status');
$facebookError = session()->pull('checkout_facebook_error');
$facebookProfile = session()->pull('checkout_facebook_profile');
$packageOptions = Package::orderBy('price')->get()
->map(fn (Package $pkg) => $this->presentPackage($pkg))
@@ -66,6 +69,11 @@ class CheckoutController extends Controller
'error' => $googleError,
'profile' => $googleProfile,
],
'facebookAuth' => [
'status' => $facebookStatus,
'error' => $facebookError,
'profile' => $facebookProfile,
],
'paddle' => [
'environment' => config('paddle.environment'),
'client_token' => config('paddle.client_token'),

View File

@@ -0,0 +1,216 @@
<?php
namespace App\Http\Controllers;
use App\Models\Package;
use App\Models\Tenant;
use App\Models\User;
use App\Support\CheckoutRoutes;
use App\Support\LocaleConfig;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Laravel\Socialite\Facades\Socialite;
use Symfony\Component\HttpFoundation\RedirectResponse;
class CheckoutFacebookController extends Controller
{
private const SESSION_KEY = 'checkout_facebook_payload';
public function redirect(Request $request): RedirectResponse
{
$validated = $request->validate([
'package_id' => ['required', 'exists:packages,id'],
'locale' => ['nullable', 'string'],
]);
$payload = [
'package_id' => (int) $validated['package_id'],
'locale' => $validated['locale'] ?? app()->getLocale(),
];
$request->session()->put(self::SESSION_KEY, $payload);
$request->session()->put('selected_package_id', $payload['package_id']);
return Socialite::driver('facebook')
->scopes(['email'])
->fields(['name', 'email', 'first_name', 'last_name'])
->redirect();
}
public function callback(Request $request): RedirectResponse
{
$payload = $request->session()->get(self::SESSION_KEY, []);
$packageId = $payload['package_id'] ?? null;
$locale = $payload['locale'] ?? null;
try {
$facebookUser = Socialite::driver('facebook')->user();
} catch (\Throwable $e) {
Log::warning('Facebook checkout login failed', ['message' => $e->getMessage()]);
$this->flashError($request, __('checkout.facebook_error_fallback'));
return $this->redirectBackToWizard($packageId, $locale);
}
$email = $facebookUser->getEmail();
if (! $email) {
$this->flashError($request, __('checkout.facebook_missing_email'));
return $this->redirectBackToWizard($packageId, $locale);
}
$raw = $facebookUser->getRaw();
$givenName = $raw['first_name'] ?? null;
$familyName = $raw['last_name'] ?? null;
$request->session()->put('checkout_facebook_profile', array_filter([
'email' => $email,
'name' => $facebookUser->getName(),
'given_name' => $givenName,
'family_name' => $familyName,
'avatar' => $facebookUser->getAvatar(),
'locale' => $raw['locale'] ?? null,
]));
$existing = User::where('email', $email)->first();
if (! $existing) {
$request->session()->put('checkout_facebook_profile', array_filter([
'email' => $email,
'name' => $facebookUser->getName(),
'given_name' => $givenName,
'family_name' => $familyName,
'avatar' => $facebookUser->getAvatar(),
'locale' => $raw['locale'] ?? null,
]));
$request->session()->put('checkout_facebook_status', 'prefill');
return $this->redirectBackToWizard($packageId, $locale);
}
$user = DB::transaction(function () use ($existing, $facebookUser, $email) {
$existing->forceFill([
'name' => $facebookUser->getName() ?: $existing->name,
'pending_purchase' => true,
'email_verified_at' => $existing->email_verified_at ?? now(),
])->save();
if (! $existing->tenant) {
$this->createTenantForUser($existing, $facebookUser->getName(), $email);
}
return $existing->fresh();
});
if (! $user->tenant) {
$this->createTenantForUser($user, $facebookUser->getName(), $email);
}
Auth::login($user, true);
$request->session()->regenerate();
$request->session()->forget(self::SESSION_KEY);
$request->session()->forget('checkout_facebook_profile');
$request->session()->put('checkout_facebook_status', 'signin');
if ($packageId) {
$this->ensurePackageAttached($user, (int) $packageId);
}
return $this->redirectBackToWizard($packageId, $locale);
}
private function createTenantForUser(User $user, ?string $displayName, string $email): Tenant
{
$tenantName = trim($displayName ?: Str::before($email, '@')) ?: 'Fotospiel Tenant';
$slugBase = Str::slug($tenantName) ?: 'tenant';
$slug = $slugBase;
$counter = 1;
while (Tenant::where('slug', $slug)->exists()) {
$slug = $slugBase.'-'.$counter;
$counter++;
}
$tenant = Tenant::create([
'user_id' => $user->id,
'name' => $tenantName,
'slug' => $slug,
'email' => $email,
'contact_email' => $email,
'is_active' => true,
'is_suspended' => false,
'subscription_tier' => 'free',
'subscription_status' => 'free',
'subscription_expires_at' => null,
'settings' => json_encode([
'branding' => [
'logo_url' => null,
'primary_color' => '#FF5A5F',
'secondary_color' => '#FFF8F5',
'font_family' => 'Inter, sans-serif',
],
'features' => [
'photo_likes_enabled' => false,
'event_checklist' => false,
'custom_domain' => false,
'advanced_analytics' => false,
],
'custom_domain' => null,
'contact_email' => $email,
'event_default_type' => 'general',
]),
]);
$user->forceFill(['tenant_id' => $tenant->id])->save();
return $tenant;
}
private function ensurePackageAttached(User $user, int $packageId): void
{
$tenant = $user->tenant;
if (! $tenant) {
return;
}
$package = Package::find($packageId);
if (! $package) {
return;
}
if ($tenant->packages()->where('package_id', $packageId)->exists()) {
return;
}
$tenant->packages()->attach($packageId, [
'price' => $package->price,
'purchased_at' => now(),
'expires_at' => now()->addYear(),
'active' => $package->price <= 0,
]);
}
private function redirectBackToWizard(?int $packageId, ?string $locale = null): RedirectResponse
{
if ($packageId) {
return redirect()->to(CheckoutRoutes::wizardUrl($packageId, $locale));
}
$firstPackageId = Package::query()->orderBy('price')->value('id');
if ($firstPackageId) {
return redirect()->to(CheckoutRoutes::wizardUrl($firstPackageId, $locale));
}
return redirect()->route('packages', [
'locale' => LocaleConfig::canonicalize($locale ?? app()->getLocale()),
]);
}
private function flashError(Request $request, string $message): void
{
$request->session()->flash('checkout_facebook_error', $message);
}
}

View File

@@ -0,0 +1,111 @@
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Laravel\Socialite\Facades\Socialite;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Throwable;
class TenantAdminFacebookController extends Controller
{
public function redirect(Request $request): RedirectResponse
{
$returnTo = $request->query('return_to');
if (is_string($returnTo) && $returnTo !== '') {
$request->session()->put('tenant_oauth_return_to', $returnTo);
}
return Socialite::driver('facebook')
->scopes(['email'])
->fields(['name', 'email', 'first_name', 'last_name'])
->redirect();
}
public function callback(Request $request): RedirectResponse
{
try {
$facebookUser = Socialite::driver('facebook')->user();
} catch (Throwable $exception) {
Log::warning('Tenant admin Facebook sign-in failed', [
'message' => $exception->getMessage(),
]);
return $this->sendBackWithError($request, 'facebook_failed', 'Unable to complete Facebook sign-in.');
}
$email = $facebookUser->getEmail();
if (! $email) {
return $this->sendBackWithError($request, 'facebook_failed', 'Facebook account did not provide an email address.');
}
/** @var User|null $user */
$user = User::query()->where('email', $email)->first();
if (! $user || ! in_array($user->role, ['tenant_admin', 'super_admin', 'superadmin'], true)) {
return $this->sendBackWithError($request, 'facebook_no_match', 'No tenant admin account is linked to this Facebook address.');
}
$user->forceFill([
'name' => $facebookUser->getName() ?: $user->name,
'email_verified_at' => $user->email_verified_at ?? now(),
])->save();
Auth::login($user, true);
$request->session()->regenerate();
$request->session()->forget('url.intended');
$returnTo = $request->session()->pull('tenant_oauth_return_to');
if (is_string($returnTo)) {
$decoded = $this->decodeReturnTo($returnTo, $request);
if ($decoded) {
return redirect()->to($decoded);
}
}
$fallback = $request->session()->pull('tenant_admin.return_to');
if (is_string($fallback) && str_starts_with($fallback, '/event-admin')) {
return redirect()->to($fallback);
}
return redirect()->to('/event-admin/dashboard');
}
private function sendBackWithError(Request $request, string $code, string $message): RedirectResponse
{
$query = [
'error' => $code,
'error_description' => $message,
];
if ($request->session()->has('tenant_oauth_return_to')) {
$query['return_to'] = $request->session()->get('tenant_oauth_return_to');
}
return redirect()->route('tenant.admin.login', $query);
}
private function decodeReturnTo(string $encoded, Request $request): ?string
{
$padded = str_pad($encoded, strlen($encoded) + ((4 - (strlen($encoded) % 4)) % 4), '=');
$normalized = strtr($padded, '-_', '+/');
$decoded = base64_decode($normalized);
if (! is_string($decoded) || $decoded === '') {
return null;
}
$targetHost = parse_url($decoded, PHP_URL_HOST);
$appHost = parse_url($request->getSchemeAndHttpHost(), PHP_URL_HOST);
if ($targetHost && $appHost && ! Str::endsWith($targetHost, $appHost)) {
return null;
}
return $decoded;
}
}

View File

@@ -57,6 +57,11 @@ return [
'client_secret' => env('GOOGLE_CLIENT_SECRET'),
'redirect' => env('GOOGLE_REDIRECT_URI', rtrim(env('APP_URL', ''), '/').'/checkout/auth/google/callback'),
],
'facebook' => [
'client_id' => env('FACEBOOK_CLIENT_ID'),
'client_secret' => env('FACEBOOK_CLIENT_SECRET'),
'redirect' => env('FACEBOOK_REDIRECT_URI', rtrim(env('APP_URL', ''), '/').'/checkout/auth/facebook/callback'),
],
'matomo' => [
'enabled' => env('MATOMO_ENABLED', false),

View File

@@ -3,4 +3,6 @@
return [
'google_error_fallback' => 'Die Google-Anmeldung konnte nicht abgeschlossen werden. Bitte versuche es erneut.',
'google_missing_email' => 'Wir konnten deine Google-E-Mail-Adresse nicht abrufen.',
'facebook_error_fallback' => 'Die Facebook-Anmeldung konnte nicht abgeschlossen werden. Bitte versuche es erneut.',
'facebook_missing_email' => 'Wir konnten deine Facebook-E-Mail-Adresse nicht abrufen.',
];

View File

@@ -3,4 +3,6 @@
return [
'google_error_fallback' => 'We could not complete the Google login. Please try again.',
'google_missing_email' => 'We could not retrieve your Google email address.',
'facebook_error_fallback' => 'We could not complete the Facebook login. Please try again.',
'facebook_missing_email' => 'We could not retrieve your Facebook email address.',
];

View File

@@ -61,6 +61,8 @@
"oauth_divider": "oder",
"google_cta": "Mit Google anmelden",
"google_helper": "Nutze dein Google-Konto, um dich sicher bei der Eventverwaltung anzumelden.",
"facebook_cta": "Mit Facebook anmelden",
"facebook_helper": "Nutze dein Facebook-Konto, um dich sicher bei der Eventverwaltung anzumelden.",
"no_account": "Noch keinen Zugang?",
"sign_up": "Jetzt registrieren"
},

View File

@@ -648,11 +648,17 @@
"switch_to_register": "Registrieren",
"switch_to_login": "Anmelden",
"continue_with_google": "Mit Google fortfahren",
"continue_with_facebook": "Mit Facebook fortfahren",
"google_success_toast": "Mit Google angemeldet.",
"google_error_title": "Google-Anmeldung fehlgeschlagen",
"google_missing_package": "Bitte wähle zuerst ein Paket aus, bevor du Google Login nutzt.",
"google_missing_email": "Wir konnten deine Google-E-Mail-Adresse nicht abrufen.",
"google_error_fallback": "Die Google-Anmeldung konnte nicht abgeschlossen werden. Bitte versuche es erneut.",
"facebook_success_toast": "Mit Facebook angemeldet.",
"facebook_error_title": "Facebook-Anmeldung fehlgeschlagen",
"facebook_missing_package": "Bitte wähle zuerst ein Paket aus, bevor du Facebook Login nutzt.",
"facebook_missing_email": "Wir konnten deine Facebook-E-Mail-Adresse nicht abrufen.",
"facebook_error_fallback": "Die Facebook-Anmeldung konnte nicht abgeschlossen werden. Bitte versuche es erneut.",
"google_helper": "Schneller Login über Google deine Daten werden ausschließlich zur Kontoeinrichtung verwendet.",
"google_helper_badge": "Warum Google?"
},

View File

@@ -61,6 +61,8 @@
"oauth_divider": "or",
"google_cta": "Continue with Google",
"google_helper": "Use your Google account to access the event dashboard securely.",
"facebook_cta": "Continue with Facebook",
"facebook_helper": "Use your Facebook account to access the event dashboard securely.",
"no_account": "Don't have access yet?",
"sign_up": "Create an account"
},

View File

@@ -645,11 +645,17 @@
"switch_to_register": "Register",
"switch_to_login": "Login",
"continue_with_google": "Continue with Google",
"continue_with_facebook": "Continue with Facebook",
"google_success_toast": "Signed in with Google.",
"google_error_title": "Google login failed",
"google_missing_package": "Please choose a package before using Google login.",
"google_missing_email": "We could not retrieve your Google email address.",
"google_error_fallback": "We couldn't complete the Google login. Please try again.",
"facebook_success_toast": "Signed in with Facebook.",
"facebook_error_title": "Facebook login failed",
"facebook_missing_package": "Please choose a package before using Facebook login.",
"facebook_missing_email": "We could not retrieve your Facebook email address.",
"facebook_error_fallback": "We couldn't complete the Facebook login. Please try again.",
"google_helper": "Sign in faster with Google we only use your details to create your Fotospiel account.",
"google_helper_badge": "Why Google?"
},

View File

@@ -39,9 +39,10 @@
"missing_token": "Reset-Token fehlt."
},
"actions_title": "Wähle deine Anmeldemethode",
"actions_copy": "Greife sicher mit deinem Fotospiel-Login oder deinem Google-Konto auf das Kunden-Dashboard zu.",
"actions_copy": "Greife sicher mit deinem Fotospiel-Login oder deinem Google- oder Facebook-Konto auf das Kunden-Dashboard zu.",
"cta": "Mit Fotospiel-Login fortfahren",
"google_cta": "Mit Google anmelden",
"facebook_cta": "Mit Facebook anmelden",
"open_account_login": "Konto-Login öffnen",
"loading": "Bitte warten …",
"oauth_error_title": "Login aktuell nicht möglich",
@@ -54,7 +55,9 @@
"invalid_scope": "Die App fordert Berechtigungen an, die nicht freigegeben sind.",
"tenant_mismatch": "Du hast keinen Zugriff auf das Kundenkonto, das diese Anmeldung angefordert hat.",
"google_failed": "Die Anmeldung mit Google war nicht erfolgreich. Bitte versuche es erneut oder wähle eine andere Methode.",
"google_no_match": "Wir konnten dieses Google-Konto keinem Kunden-Admin zuordnen. Bitte melde dich mit Fotospiel-Zugangsdaten an."
"google_no_match": "Wir konnten dieses Google-Konto keinem Kunden-Admin zuordnen. Bitte melde dich mit Fotospiel-Zugangsdaten an.",
"facebook_failed": "Die Anmeldung mit Facebook war nicht erfolgreich. Bitte versuche es erneut oder wähle eine andere Methode.",
"facebook_no_match": "Wir konnten dieses Facebook-Konto keinem Kunden-Admin zuordnen. Bitte melde dich mit Fotospiel-Zugangsdaten an."
},
"return_hint": "Nach dem Anmelden leiten wir dich automatisch zurück.",
"support": "Du brauchst Zugriff? Kontaktiere dein Event-Team oder schreib uns an support@fotospiel.de.",

View File

@@ -39,9 +39,10 @@
"missing_token": "Reset token missing."
},
"actions_title": "Choose your sign-in method",
"actions_copy": "Access the customer dashboard securely with your Fotospiel login or your Google account.",
"actions_copy": "Access the customer dashboard securely with your Fotospiel login or your Google or Facebook account.",
"cta": "Continue with Fotospiel login",
"google_cta": "Continue with Google",
"facebook_cta": "Continue with Facebook",
"open_account_login": "Open account login",
"loading": "Signing you in …",
"oauth_error_title": "Login not possible right now",
@@ -54,7 +55,9 @@
"invalid_scope": "The app asked for permissions it cannot receive.",
"tenant_mismatch": "You dont have access to the customer account that requested this login.",
"google_failed": "Google sign-in was not successful. Please try again or use another method.",
"google_no_match": "We couldnt link this Google account to a customer admin. Please sign in with Fotospiel credentials."
"google_no_match": "We couldnt link this Google account to a customer admin. Please sign in with Fotospiel credentials.",
"facebook_failed": "Facebook sign-in was not successful. Please try again or use another method.",
"facebook_no_match": "We couldnt link this Facebook account to a customer admin. Please sign in with Fotospiel credentials."
},
"return_hint": "After signing in youll be brought back automatically.",
"support": "Need access? Contact your event team or email support@fotospiel.de — we're happy to help.",

View File

@@ -105,6 +105,16 @@ export default function MobileLoginPage() {
return `/event-admin/auth/google?${params.toString()}`;
}, [encodedFinal]);
const facebookHref = React.useMemo(() => {
if (!encodedFinal) {
return '/event-admin/auth/facebook';
}
const params = new URLSearchParams({ return_to: encodedFinal });
return `/event-admin/auth/facebook?${params.toString()}`;
}, [encodedFinal]);
React.useEffect(() => {
if (status === 'authenticated') {
navigate(finalTarget, { replace: true });
@@ -115,6 +125,7 @@ export default function MobileLoginPage() {
const [password, setPassword] = React.useState('');
const [error, setError] = React.useState<string | null>(null);
const [isRedirectingToGoogle, setIsRedirectingToGoogle] = React.useState(false);
const [isRedirectingToFacebook, setIsRedirectingToFacebook] = React.useState(false);
const [installBannerDismissed, setInstallBannerDismissedState] = React.useState(() => getInstallBannerDismissed());
const installBanner = shouldShowInstallBanner(
{
@@ -170,6 +181,15 @@ export default function MobileLoginPage() {
window.location.assign(googleHref);
}, [googleHref]);
const handleFacebookLogin = React.useCallback(() => {
if (typeof window === 'undefined') {
return;
}
setIsRedirectingToFacebook(true);
window.location.assign(facebookHref);
}, [facebookHref]);
return (
<YStack
minHeight="100vh"
@@ -320,6 +340,29 @@ export default function MobileLoginPage() {
</Text>
</XStack>
</Button>
<Button
type="button"
onPress={handleFacebookLogin}
disabled={isRedirectingToFacebook || isSubmitting}
height={52}
borderRadius={16}
backgroundColor={surface}
borderColor={border}
borderWidth={1}
color={text}
>
<XStack alignItems="center" space="$2">
{isRedirectingToFacebook ? (
<Loader2 size={16} className="animate-spin" />
) : (
<FacebookIcon size={18} />
)}
<Text fontSize="$sm" color={text} fontWeight="700">
{t('login.facebook_cta', 'Mit Facebook anmelden')}
</Text>
</XStack>
</Button>
</YStack>
</form>
</MobileCard>
@@ -365,3 +408,14 @@ function GoogleIcon({ size = 18 }: { size?: number }) {
</svg>
);
}
function FacebookIcon({ size = 18 }: { size?: number }) {
return (
<svg width={size} height={size} viewBox="0 0 24 24" aria-hidden>
<path
fill="#1877F2"
d="M24 12.073C24 5.404 18.627 0 12 0S0 5.404 0 12.073C0 18.1 4.388 23.094 10.125 24v-8.437H7.078v-3.49h3.047V9.43c0-3.014 1.792-4.68 4.533-4.68 1.312 0 2.686.236 2.686.236v2.96h-1.513c-1.49 0-1.954.93-1.954 1.887v2.264h3.328l-.532 3.49h-2.796V24C19.612 23.094 24 18.1 24 12.073Z"
/>
</svg>
);
}

View File

@@ -103,13 +103,15 @@ vi.mock('lucide-react', () => ({
import MobileLoginPage from '../LoginPage';
describe('MobileLoginPage', () => {
it('renders Google login button', () => {
it('renders OAuth login buttons', () => {
locationSearch = '?return_to=encoded-value';
render(<MobileLoginPage />);
const googleButton = screen.getByText('Mit Google anmelden');
expect(googleButton).toBeInTheDocument();
const facebookButton = screen.getByText('Mit Facebook anmelden');
expect(facebookButton).toBeInTheDocument();
});
it('shows oauth error details when present', () => {

View File

@@ -51,9 +51,9 @@ export default function LoginForm({ onSuccess, canResetPassword = true, locale,
const loginEndpoint = '/checkout/login';
const canUseGoogle = typeof packageId === "number" && !Number.isNaN(packageId);
const canUseOauth = typeof packageId === "number" && !Number.isNaN(packageId);
const googleHref = useMemo(() => {
if (!canUseGoogle) {
if (!canUseOauth) {
return "";
}
@@ -63,7 +63,20 @@ export default function LoginForm({ onSuccess, canResetPassword = true, locale,
});
return `/checkout/auth/google?${params.toString()}`;
}, [canUseGoogle, packageId, resolvedLocale]);
}, [canUseOauth, packageId, resolvedLocale]);
const facebookHref = useMemo(() => {
if (!canUseOauth) {
return "";
}
const params = new URLSearchParams({
package_id: String(packageId),
locale: resolvedLocale,
});
return `/checkout/auth/facebook?${params.toString()}`;
}, [canUseOauth, packageId, resolvedLocale]);
const [values, setValues] = useState({
identifier: "",
@@ -73,6 +86,7 @@ export default function LoginForm({ onSuccess, canResetPassword = true, locale,
const [errors, setErrors] = useState<FieldErrors>({});
const [isSubmitting, setIsSubmitting] = useState(false);
const [isRedirectingToGoogle, setIsRedirectingToGoogle] = useState(false);
const [isRedirectingToFacebook, setIsRedirectingToFacebook] = useState(false);
const [hasTriedSubmit, setHasTriedSubmit] = useState(false);
const [shouldFocusError, setShouldFocusError] = useState(false);
@@ -188,6 +202,15 @@ export default function LoginForm({ onSuccess, canResetPassword = true, locale,
window.location.href = googleHref;
};
const handleFacebookLogin = () => {
if (!facebookHref) {
return;
}
setIsRedirectingToFacebook(true);
window.location.href = facebookHref;
};
return (
<form onSubmit={submit} className="flex flex-col gap-6" noValidate>
<div className="grid gap-6">
@@ -243,27 +266,43 @@ export default function LoginForm({ onSuccess, canResetPassword = true, locale,
</Button>
</div>
{canUseGoogle && (
{canUseOauth && (
<div className="space-y-3">
<div className="flex items-center gap-3 text-xs font-semibold uppercase tracking-[0.3em] text-muted-foreground">
<span className="h-px flex-1 bg-gray-200 dark:bg-gray-800" aria-hidden />
{t("login.oauth_divider", "oder")}
<span className="h-px flex-1 bg-gray-200 dark:bg-gray-800" aria-hidden />
</div>
<Button
type="button"
variant="outline"
onClick={handleGoogleLogin}
disabled={isSubmitting || isRedirectingToGoogle}
className="flex w-full items-center justify-center gap-2"
>
{isRedirectingToGoogle ? (
<LoaderCircle className="h-4 w-4 animate-spin" />
) : (
<GoogleIcon className="h-4 w-4" />
)}
<span>{t("login.google_cta")}</span>
</Button>
<div className="grid gap-3">
<Button
type="button"
variant="outline"
onClick={handleGoogleLogin}
disabled={isSubmitting || isRedirectingToGoogle}
className="flex w-full items-center justify-center gap-2"
>
{isRedirectingToGoogle ? (
<LoaderCircle className="h-4 w-4 animate-spin" />
) : (
<GoogleIcon className="h-4 w-4" />
)}
<span>{t("login.google_cta")}</span>
</Button>
<Button
type="button"
variant="outline"
onClick={handleFacebookLogin}
disabled={isSubmitting || isRedirectingToFacebook}
className="flex w-full items-center justify-center gap-2"
>
{isRedirectingToFacebook ? (
<LoaderCircle className="h-4 w-4 animate-spin" />
) : (
<FacebookIcon className="h-4 w-4" />
)}
<span>{t("login.facebook_cta")}</span>
</Button>
</div>
</div>
)}
@@ -286,3 +325,14 @@ function GoogleIcon({ className }: { className?: string }) {
</svg>
);
}
function FacebookIcon({ className }: { className?: string }) {
return (
<svg className={className} viewBox="0 0 24 24" aria-hidden>
<path
fill="#1877F2"
d="M24 12.073C24 5.404 18.627 0 12 0S0 5.404 0 12.073C0 18.1 4.388 23.094 10.125 24v-8.437H7.078v-3.49h3.047V9.43c0-3.014 1.792-4.68 4.533-4.68 1.312 0 2.686.236 2.686.236v2.96h-1.513c-1.49 0-1.954.93-1.954 1.887v2.264h3.328l-.532 3.49h-2.796V24C19.612 23.094 24 18.1 24 12.073Z"
/>
</svg>
);
}

View File

@@ -4,7 +4,7 @@ import { useTranslation } from 'react-i18next';
import toast from 'react-hot-toast';
import { LoaderCircle, User, Mail, Lock } from 'lucide-react';
import { Dialog, DialogContent, DialogTitle, DialogDescription } from '@/components/ui/dialog';
import type { GoogleProfilePrefill } from '../marketing/checkout/types';
import type { OAuthProfilePrefill } from '../marketing/checkout/types';
export interface RegisterSuccessPayload {
user: unknown | null;
@@ -17,8 +17,8 @@ interface RegisterFormProps {
onSuccess?: (payload: RegisterSuccessPayload) => void;
privacyHtml: string;
locale?: string;
prefill?: GoogleProfilePrefill;
onClearGoogleProfile?: () => void;
prefill?: OAuthProfilePrefill;
onClearPrefill?: () => void;
}
type RegisterFormFields = {
@@ -50,7 +50,7 @@ const resolveMetaCsrfToken = (): string => {
return (document.querySelector('meta[name="csrf-token"]') as HTMLMetaElement | null)?.content ?? '';
};
export default function RegisterForm({ packageId, onSuccess, privacyHtml, locale, prefill, onClearGoogleProfile }: RegisterFormProps) {
export default function RegisterForm({ packageId, onSuccess, privacyHtml, locale, prefill, onClearPrefill }: RegisterFormProps) {
const [privacyOpen, setPrivacyOpen] = useState(false);
const [hasTriedSubmit, setHasTriedSubmit] = useState(false);
const [isSubmitting, setIsSubmitting] = useState(false);
@@ -176,7 +176,7 @@ export default function RegisterForm({ packageId, onSuccess, privacyHtml, locale
redirect: json?.redirect ?? null,
pending_purchase: json?.pending_purchase ?? json?.user?.pending_purchase ?? false,
});
onClearGoogleProfile?.();
onClearPrefill?.();
reset();
setHasTriedSubmit(false);
return;

View File

@@ -39,15 +39,17 @@ vi.mock('react-hot-toast', () => ({
import LoginForm from '../LoginForm';
describe('LoginForm', () => {
it('renders Google login option when packageId is provided', () => {
it('renders OAuth login options when packageId is provided', () => {
render(<LoginForm packageId={12} />);
expect(screen.getByText('login.google_cta')).toBeInTheDocument();
expect(screen.getByText('login.facebook_cta')).toBeInTheDocument();
});
it('does not render Google login option without packageId', () => {
it('does not render OAuth login options without packageId', () => {
render(<LoginForm />);
expect(screen.queryByText('login.google_cta')).not.toBeInTheDocument();
expect(screen.queryByText('login.facebook_cta')).not.toBeInTheDocument();
});
});

View File

@@ -24,6 +24,7 @@ export default function Login({ status, canResetPassword }: LoginProps) {
const [hasTriedSubmit, setHasTriedSubmit] = useState(false);
const [rawReturnTo, setRawReturnTo] = useState<string | null>(null);
const [isRedirectingToGoogle, setIsRedirectingToGoogle] = useState(false);
const [isRedirectingToFacebook, setIsRedirectingToFacebook] = useState(false);
const { t } = useTranslation('auth');
const page = usePage<{ flash?: { verification?: { status: string; title?: string; message?: string } } }>();
const verificationFlash = page.props.flash?.verification;
@@ -98,6 +99,18 @@ export default function Login({ status, canResetPassword }: LoginProps) {
return `/event-admin/auth/google?${params.toString()}`;
}, [rawReturnTo]);
const facebookHref = useMemo(() => {
if (!rawReturnTo) {
return '/event-admin/auth/facebook';
}
const params = new URLSearchParams({
return_to: rawReturnTo,
});
return `/event-admin/auth/facebook?${params.toString()}`;
}, [rawReturnTo]);
const handleGoogleLogin = () => {
if (typeof window === 'undefined') {
return;
@@ -107,6 +120,15 @@ export default function Login({ status, canResetPassword }: LoginProps) {
window.location.href = googleHref;
};
const handleFacebookLogin = () => {
if (typeof window === 'undefined') {
return;
}
setIsRedirectingToFacebook(true);
window.location.href = facebookHref;
};
return (
<AuthLayout
title={t('login.title')}
@@ -271,9 +293,27 @@ export default function Login({ status, canResetPassword }: LoginProps) {
)}
<span>{t('login.google_cta')}</span>
</Button>
<Button
type="button"
variant="outline"
onClick={handleFacebookLogin}
disabled={processing || isRedirectingToFacebook}
className="flex h-12 w-full items-center justify-center gap-3 rounded-xl border-gray-200/80 bg-white/90 text-sm font-semibold text-gray-700 shadow-inner shadow-gray-200/40 transition hover:bg-white dark:border-gray-800/70 dark:bg-gray-900/60 dark:text-gray-100 dark:hover:bg-gray-900/80"
>
{isRedirectingToFacebook ? (
<LoaderCircle className="h-5 w-5 animate-spin" aria-hidden />
) : (
<FacebookIcon className="h-5 w-5" />
)}
<span>{t('login.facebook_cta')}</span>
</Button>
<p className="text-center text-xs text-muted-foreground dark:text-gray-300">
{t('login.google_helper', 'Nutze dein Google-Konto, um dich sicher bei der Eventverwaltung anzumelden.')}
</p>
<p className="text-center text-xs text-muted-foreground dark:text-gray-300">
{t('login.facebook_helper', 'Melde dich schnell mit deinem Facebook-Konto an.')}
</p>
</div>
<div className="rounded-2xl border border-gray-200/60 bg-gray-50/80 p-4 text-center text-sm text-muted-foreground shadow-inner dark:border-gray-800/70 dark:bg-gray-900/60">
@@ -315,3 +355,14 @@ function GoogleIcon({ className }: { className?: string }) {
</svg>
);
}
function FacebookIcon({ className }: { className?: string }) {
return (
<svg className={className} viewBox="0 0 24 24" aria-hidden>
<path
fill="#1877F2"
d="M24 12.073C24 5.404 18.627 0 12 0S0 5.404 0 12.073C0 18.1 4.388 23.094 10.125 24v-8.437H7.078v-3.49h3.047V9.43c0-3.014 1.792-4.68 4.533-4.68 1.312 0 2.686.236 2.686.236v2.96h-1.513c-1.49 0-1.954.93-1.954 1.887v2.264h3.328l-.532 3.49h-2.796V24C19.612 23.094 24 18.1 24 12.073Z"
/>
</svg>
);
}

View File

@@ -1,7 +1,7 @@
import React, { useEffect } from "react";
import { Head, usePage } from "@inertiajs/react";
import MarketingLayout from "@/layouts/mainWebsite";
import type { CheckoutPackage, GoogleProfilePrefill } from "./checkout/types";
import type { CheckoutPackage, OAuthProfilePrefill } from "./checkout/types";
import { CheckoutWizard } from "./checkout/CheckoutWizard";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import toast from "react-hot-toast";
@@ -14,7 +14,12 @@ interface CheckoutWizardPageProps {
googleAuth?: {
status?: string | null;
error?: string | null;
profile?: GoogleProfilePrefill | null;
profile?: OAuthProfilePrefill | null;
};
facebookAuth?: {
status?: string | null;
error?: string | null;
profile?: OAuthProfilePrefill | null;
};
paddle?: {
environment?: string | null;
@@ -27,11 +32,13 @@ const CheckoutWizardPage: React.FC<CheckoutWizardPageProps> = ({
packageOptions,
privacyHtml,
googleAuth,
facebookAuth,
paddle,
}) => {
const page = usePage<{ auth?: { user?: { id: number; email: string; name?: string; pending_purchase?: boolean } | null }, flash?: { verification?: { status: string; title?: string; message?: string } } }>();
const currentUser = page.props.auth?.user ?? null;
const googleProfile = googleAuth?.profile ?? null;
const facebookProfile = facebookAuth?.profile ?? null;
const { t: tAuth } = useTranslation('auth');
const verificationFlash = page.props.flash?.verification;
@@ -85,6 +92,7 @@ const CheckoutWizardPage: React.FC<CheckoutWizardPageProps> = ({
privacyHtml={privacyHtml}
initialAuthUser={currentUser ? { id: currentUser.id, email: currentUser.email ?? '', name: currentUser.name ?? undefined, pending_purchase: Boolean(currentUser.pending_purchase) } : null}
googleProfile={googleProfile}
facebookProfile={facebookProfile}
paddle={paddle ?? null}
/>
</div>

View File

@@ -4,7 +4,7 @@ import { Steps } from "@/components/ui/Steps";
import { Button } from "@/components/ui/button";
import { Progress } from "@/components/ui/progress";
import { CheckoutWizardProvider, useCheckoutWizard } from "./WizardContext";
import type { CheckoutPackage, CheckoutStepId, GoogleProfilePrefill } from "./types";
import type { CheckoutPackage, CheckoutStepId, OAuthProfilePrefill } from "./types";
import { PackageStep } from "./steps/PackageStep";
import { AuthStep } from "./steps/AuthStep";
import { ConfirmationStep } from "./steps/ConfirmationStep";
@@ -25,7 +25,8 @@ interface CheckoutWizardProps {
pending_purchase?: boolean;
} | null;
initialStep?: CheckoutStepId;
googleProfile?: GoogleProfilePrefill | null;
googleProfile?: OAuthProfilePrefill | null;
facebookProfile?: OAuthProfilePrefill | null;
paddle?: {
environment?: string | null;
client_token?: string | null;
@@ -68,9 +69,9 @@ const PaymentStepFallback: React.FC = () => (
const WizardBody: React.FC<{
privacyHtml: string;
googleProfile?: GoogleProfilePrefill | null;
onClearGoogleProfile?: () => void;
}> = ({ privacyHtml, googleProfile, onClearGoogleProfile }) => {
prefillProfile?: OAuthProfilePrefill | null;
onClearPrefill?: () => void;
}> = ({ privacyHtml, prefillProfile, onClearPrefill }) => {
const primaryCtaClassName = "min-w-[160px] disabled:bg-muted disabled:text-muted-foreground disabled:hover:bg-muted disabled:hover:text-muted-foreground";
const { t } = useTranslation('marketing');
const {
@@ -246,8 +247,8 @@ const WizardBody: React.FC<{
{currentStep === "auth" && (
<AuthStep
privacyHtml={privacyHtml}
googleProfile={googleProfile ?? undefined}
onClearGoogleProfile={onClearGoogleProfile}
prefill={prefillProfile ?? undefined}
onClearPrefill={onClearPrefill}
/>
)}
{currentStep === "payment" && (
@@ -288,9 +289,10 @@ export const CheckoutWizard: React.FC<CheckoutWizardProps> = ({
initialAuthUser,
initialStep,
googleProfile,
facebookProfile,
paddle,
}) => {
const [storedProfile, setStoredProfile] = useState<GoogleProfilePrefill | null>(() => {
const [storedGoogleProfile, setStoredGoogleProfile] = useState<OAuthProfilePrefill | null>(() => {
if (typeof window === 'undefined') {
return null;
}
@@ -301,7 +303,7 @@ export const CheckoutWizard: React.FC<CheckoutWizardProps> = ({
}
try {
return JSON.parse(raw) as GoogleProfilePrefill;
return JSON.parse(raw) as OAuthProfilePrefill;
} catch (error) {
console.warn('Failed to parse checkout google profile from storage', error);
window.localStorage.removeItem('checkout-google-profile');
@@ -314,21 +316,64 @@ export const CheckoutWizard: React.FC<CheckoutWizardProps> = ({
return;
}
setStoredProfile(googleProfile);
setStoredGoogleProfile(googleProfile);
if (typeof window !== 'undefined') {
window.localStorage.setItem('checkout-google-profile', JSON.stringify(googleProfile));
}
}, [googleProfile]);
const clearStoredProfile = useCallback(() => {
setStoredProfile(null);
const clearStoredGoogleProfile = useCallback(() => {
setStoredGoogleProfile(null);
if (typeof window !== 'undefined') {
window.localStorage.removeItem('checkout-google-profile');
}
}, []);
const effectiveProfile = googleProfile ?? storedProfile;
const [storedFacebookProfile, setStoredFacebookProfile] = useState<OAuthProfilePrefill | null>(() => {
if (typeof window === 'undefined') {
return null;
}
const raw = window.localStorage.getItem('checkout-facebook-profile');
if (!raw) {
return null;
}
try {
return JSON.parse(raw) as OAuthProfilePrefill;
} catch (error) {
console.warn('Failed to parse checkout facebook profile from storage', error);
window.localStorage.removeItem('checkout-facebook-profile');
return null;
}
});
useEffect(() => {
if (!facebookProfile) {
return;
}
setStoredFacebookProfile(facebookProfile);
if (typeof window !== 'undefined') {
window.localStorage.setItem('checkout-facebook-profile', JSON.stringify(facebookProfile));
}
}, [facebookProfile]);
const clearStoredFacebookProfile = useCallback(() => {
setStoredFacebookProfile(null);
if (typeof window !== 'undefined') {
window.localStorage.removeItem('checkout-facebook-profile');
}
}, []);
const clearStoredProfiles = useCallback(() => {
clearStoredGoogleProfile();
clearStoredFacebookProfile();
}, [clearStoredFacebookProfile, clearStoredGoogleProfile]);
const effectiveProfile = facebookProfile ?? storedFacebookProfile ?? googleProfile ?? storedGoogleProfile;
return (
<CheckoutWizardProvider
@@ -341,8 +386,8 @@ export const CheckoutWizard: React.FC<CheckoutWizardProps> = ({
>
<WizardBody
privacyHtml={privacyHtml}
googleProfile={effectiveProfile}
onClearGoogleProfile={clearStoredProfile}
prefillProfile={effectiveProfile}
onClearPrefill={clearStoredProfiles}
/>
</CheckoutWizardProvider>
);

View File

@@ -3,7 +3,7 @@ import { describe, expect, it, vi } from 'vitest';
import { fireEvent, render, screen } from '@testing-library/react';
vi.mock('@inertiajs/react', () => ({
usePage: () => ({ props: { locale: 'de', googleAuth: {} } }),
usePage: () => ({ props: { locale: 'de', googleAuth: {}, facebookAuth: {} } }),
}));
vi.mock('react-i18next', () => ({
@@ -77,14 +77,16 @@ vi.mock('lucide-react', () => ({
import { AuthStep } from '../steps/AuthStep';
describe('AuthStep Google controls', () => {
it('hides the top Google button when switching to login mode', () => {
describe('AuthStep OAuth controls', () => {
it('hides the OAuth buttons when switching to login mode', () => {
render(<AuthStep privacyHtml="" />);
expect(screen.getByText('checkout.auth_step.continue_with_google')).toBeInTheDocument();
expect(screen.getByText('checkout.auth_step.continue_with_facebook')).toBeInTheDocument();
fireEvent.click(screen.getByText('checkout.auth_step.switch_to_login'));
expect(screen.queryByText('checkout.auth_step.continue_with_google')).not.toBeInTheDocument();
expect(screen.queryByText('checkout.auth_step.continue_with_facebook')).not.toBeInTheDocument();
});
});

View File

@@ -3,7 +3,7 @@ import { usePage } from "@inertiajs/react";
import { Button } from "@/components/ui/button";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { useCheckoutWizard } from "../WizardContext";
import type { GoogleProfilePrefill } from '../types';
import type { OAuthProfilePrefill } from '../types';
import LoginForm, { AuthUserPayload } from "../../../auth/LoginForm";
import RegisterForm, { RegisterSuccessPayload } from "../../../auth/RegisterForm";
import { Trans, useTranslation } from 'react-i18next';
@@ -14,11 +14,11 @@ import { cn } from "@/lib/utils";
interface AuthStepProps {
privacyHtml: string;
googleProfile?: GoogleProfilePrefill;
onClearGoogleProfile?: () => void;
prefill?: OAuthProfilePrefill;
onClearPrefill?: () => void;
}
type GoogleAuthFlash = {
type OAuthAuthFlash = {
status?: string | null;
error?: string | null;
};
@@ -34,26 +34,55 @@ const GoogleIcon: React.FC<{ className?: string }> = ({ className }) => (
</svg>
);
export const AuthStep: React.FC<AuthStepProps> = ({ privacyHtml, googleProfile, onClearGoogleProfile }) => {
const FacebookIcon: React.FC<{ className?: string }> = ({ className }) => (
<svg
className={className}
viewBox="0 0 24 24"
aria-hidden="true"
focusable="false"
>
<path
fill="#1877F2"
d="M24 12.073C24 5.404 18.627 0 12 0S0 5.404 0 12.073C0 18.1 4.388 23.094 10.125 24v-8.437H7.078v-3.49h3.047V9.43c0-3.014 1.792-4.68 4.533-4.68 1.312 0 2.686.236 2.686.236v2.96h-1.513c-1.49 0-1.954.93-1.954 1.887v2.264h3.328l-.532 3.49h-2.796V24C19.612 23.094 24 18.1 24 12.073Z"
/>
</svg>
);
export const AuthStep: React.FC<AuthStepProps> = ({ privacyHtml, prefill, onClearPrefill }) => {
const { t } = useTranslation('marketing');
const page = usePage<{ locale?: string }>();
const locale = page.props.locale ?? "de";
const googleAuth = useMemo<GoogleAuthFlash>(() => {
const props = page.props as { googleAuth?: GoogleAuthFlash };
const googleAuth = useMemo<OAuthAuthFlash>(() => {
const props = page.props as { googleAuth?: OAuthAuthFlash };
return props.googleAuth ?? {};
}, [page.props]);
const facebookAuth = useMemo<OAuthAuthFlash>(() => {
const props = page.props as { facebookAuth?: OAuthAuthFlash };
return props.facebookAuth ?? {};
}, [page.props]);
const { isAuthenticated, authUser, setAuthUser, nextStep, selectedPackage } = useCheckoutWizard();
const [mode, setMode] = useState<'login' | 'register'>('register');
const [isRedirectingToGoogle, setIsRedirectingToGoogle] = useState(false);
const [isRedirectingToFacebook, setIsRedirectingToFacebook] = useState(false);
const [showGoogleHelper, setShowGoogleHelper] = useState(false);
const showGoogleControls = mode === 'register';
const showOauthControls = mode === 'register';
const authErrorTitle = facebookAuth?.error
? t('checkout.auth_step.facebook_error_title')
: t('checkout.auth_step.google_error_title');
useEffect(() => {
if (googleAuth?.status === 'signin') {
toast.success(t('checkout.auth_step.google_success_toast'));
onClearGoogleProfile?.();
onClearPrefill?.();
}
}, [googleAuth?.status, onClearGoogleProfile, t]);
}, [googleAuth?.status, onClearPrefill, t]);
useEffect(() => {
if (facebookAuth?.status === 'signin') {
toast.success(t('checkout.auth_step.facebook_success_toast'));
onClearPrefill?.();
}
}, [facebookAuth?.status, onClearPrefill, t]);
useEffect(() => {
if (googleAuth?.error) {
@@ -61,6 +90,12 @@ export const AuthStep: React.FC<AuthStepProps> = ({ privacyHtml, googleProfile,
}
}, [googleAuth?.error]);
useEffect(() => {
if (facebookAuth?.error) {
toast.error(facebookAuth.error);
}
}, [facebookAuth?.error]);
useEffect(() => {
if (mode !== 'login') {
return;
@@ -82,7 +117,7 @@ export const AuthStep: React.FC<AuthStepProps> = ({ privacyHtml, googleProfile,
name: payload.name ?? undefined,
pending_purchase: Boolean(payload.pending_purchase),
});
onClearGoogleProfile?.();
onClearPrefill?.();
nextStep();
};
@@ -97,7 +132,7 @@ export const AuthStep: React.FC<AuthStepProps> = ({ privacyHtml, googleProfile,
});
}
onClearGoogleProfile?.();
onClearPrefill?.();
nextStep();
};
@@ -115,6 +150,20 @@ export const AuthStep: React.FC<AuthStepProps> = ({ privacyHtml, googleProfile,
window.location.href = `/checkout/auth/google?${params.toString()}`;
}, [locale, selectedPackage, t]);
const handleFacebookLogin = useCallback(() => {
if (!selectedPackage) {
toast.error(t('checkout.auth_step.facebook_missing_package'));
return;
}
setIsRedirectingToFacebook(true);
const params = new URLSearchParams({
package_id: String(selectedPackage.id),
locale,
});
window.location.href = `/checkout/auth/facebook?${params.toString()}`;
}, [locale, selectedPackage, t]);
if (isAuthenticated && authUser) {
return (
<div className="space-y-6">
@@ -159,37 +208,52 @@ export const AuthStep: React.FC<AuthStepProps> = ({ privacyHtml, googleProfile,
>
{t('checkout.auth_step.switch_to_login')}
</Button>
{showGoogleControls && (
<div className="flex flex-1 justify-start gap-2 sm:flex-none">
{showOauthControls && (
<div className="flex flex-1 flex-wrap items-center gap-2 sm:flex-none">
<div className="flex items-center gap-2">
<Button
variant="outline"
onClick={handleGoogleLogin}
disabled={isRedirectingToGoogle}
className="flex items-center gap-2"
>
{isRedirectingToGoogle ? (
<LoaderCircle className="h-4 w-4 animate-spin" />
) : (
<GoogleIcon className="h-4 w-4" />
)}
{t('checkout.auth_step.continue_with_google')}
</Button>
<CollapsibleTrigger asChild>
<button
type="button"
className={cn(
"inline-flex items-center gap-1 rounded-full border border-muted-foreground/30 px-3 py-1 text-xs font-medium text-muted-foreground transition hover:border-muted-foreground/60 hover:text-foreground",
showGoogleHelper && "bg-muted/60 text-foreground"
)}
>
{t('checkout.auth_step.google_helper_badge')}
<ChevronDown className={cn("h-3 w-3 transition-transform", showGoogleHelper && "rotate-180")} />
</button>
</CollapsibleTrigger>
</div>
<Button
variant="outline"
onClick={handleGoogleLogin}
disabled={isRedirectingToGoogle}
onClick={handleFacebookLogin}
disabled={isRedirectingToFacebook}
className="flex items-center gap-2"
>
{isRedirectingToGoogle ? (
{isRedirectingToFacebook ? (
<LoaderCircle className="h-4 w-4 animate-spin" />
) : (
<GoogleIcon className="h-4 w-4" />
<FacebookIcon className="h-4 w-4" />
)}
{t('checkout.auth_step.continue_with_google')}
{t('checkout.auth_step.continue_with_facebook')}
</Button>
<CollapsibleTrigger asChild>
<button
type="button"
className={cn(
"inline-flex items-center gap-1 rounded-full border border-muted-foreground/30 px-3 py-1 text-xs font-medium text-muted-foreground transition hover:border-muted-foreground/60 hover:text-foreground",
showGoogleHelper && "bg-muted/60 text-foreground"
)}
>
{t('checkout.auth_step.google_helper_badge')}
<ChevronDown className={cn("h-3 w-3 transition-transform", showGoogleHelper && "rotate-180")} />
</button>
</CollapsibleTrigger>
</div>
)}
</div>
{showGoogleControls && (
{showOauthControls && (
<CollapsibleContent>
<Alert className="border-dashed border-muted/60 bg-muted/20 text-xs sm:text-sm">
<AlertDescription>{t('checkout.auth_step.google_helper')}</AlertDescription>
@@ -198,10 +262,10 @@ export const AuthStep: React.FC<AuthStepProps> = ({ privacyHtml, googleProfile,
)}
</Collapsible>
{googleAuth?.error && (
{(googleAuth?.error || facebookAuth?.error) && (
<Alert variant="destructive">
<AlertTitle>{t('checkout.auth_step.google_error_title')}</AlertTitle>
<AlertDescription>{googleAuth.error}</AlertDescription>
<AlertTitle>{authErrorTitle}</AlertTitle>
<AlertDescription>{facebookAuth?.error ?? googleAuth?.error}</AlertDescription>
</Alert>
)}
@@ -213,8 +277,8 @@ export const AuthStep: React.FC<AuthStepProps> = ({ privacyHtml, googleProfile,
privacyHtml={privacyHtml}
locale={locale}
onSuccess={handleRegisterSuccess}
prefill={googleProfile}
onClearGoogleProfile={onClearGoogleProfile}
prefill={prefill}
onClearPrefill={onClearPrefill}
/>
)
) : (

View File

@@ -1,6 +1,6 @@
export type CheckoutStepId = 'package' | 'auth' | 'payment' | 'confirmation';
export interface GoogleProfilePrefill {
export interface OAuthProfilePrefill {
email?: string;
name?: string;
given_name?: string;

View File

@@ -61,6 +61,8 @@
"oauth_divider": "oder",
"google_cta": "Mit Google anmelden",
"google_helper": "Nutze dein Google-Konto, um dich sicher bei der Eventverwaltung anzumelden.",
"facebook_cta": "Mit Facebook anmelden",
"facebook_helper": "Nutze dein Facebook-Konto, um dich sicher bei der Eventverwaltung anzumelden.",
"no_account": "Noch keinen Zugang?",
"sign_up": "Jetzt registrieren"
},

View File

@@ -61,6 +61,8 @@
"oauth_divider": "or",
"google_cta": "Continue with Google",
"google_helper": "Use your Google account to access the event dashboard securely.",
"facebook_cta": "Continue with Facebook",
"facebook_helper": "Use your Facebook account to access the event dashboard securely.",
"no_account": "Don't have access yet?",
"sign_up": "Create an account"
},

View File

@@ -3,6 +3,7 @@
use App\Http\Controllers\Auth\AuthenticatedSessionController;
use App\Http\Controllers\Auth\RegisteredUserController;
use App\Http\Controllers\CheckoutController;
use App\Http\Controllers\CheckoutFacebookController;
use App\Http\Controllers\CheckoutGoogleController;
use App\Http\Controllers\DashboardController;
use App\Http\Controllers\LegalPageController;
@@ -17,6 +18,7 @@ use App\Http\Controllers\ProfileDataExportController;
use App\Http\Controllers\SuperAdmin\DataExportController as SuperAdminDataExportController;
use App\Http\Controllers\Tenant\EventPhotoArchiveController;
use App\Http\Controllers\TenantAdminAuthController;
use App\Http\Controllers\TenantAdminFacebookController;
use App\Http\Controllers\TenantAdminGoogleController;
use App\Http\Controllers\WithdrawalController;
use App\Models\Package;
@@ -331,6 +333,10 @@ Route::prefix('event-admin')->group(function () {
->name('tenant.admin.google.redirect');
Route::get('/auth/google/callback', [TenantAdminGoogleController::class, 'callback'])
->name('tenant.admin.google.callback');
Route::get('/auth/facebook', [TenantAdminFacebookController::class, 'redirect'])
->name('tenant.admin.facebook.redirect');
Route::get('/auth/facebook/callback', [TenantAdminFacebookController::class, 'callback'])
->name('tenant.admin.facebook.callback');
// Protected routes (auth check inside controller)
Route::get('/logout', $authAdmin)->name('tenant.admin.logout');
@@ -383,6 +389,8 @@ Route::post('/checkout/login', [CheckoutController::class, 'login'])->name('chec
Route::post('/checkout/register', [CheckoutController::class, 'register'])->name('checkout.register');
Route::get('/checkout/auth/google', [CheckoutGoogleController::class, 'redirect'])->name('checkout.google.redirect');
Route::get('/checkout/auth/google/callback', [CheckoutGoogleController::class, 'callback'])->name('checkout.google.callback');
Route::get('/checkout/auth/facebook', [CheckoutFacebookController::class, 'redirect'])->name('checkout.facebook.redirect');
Route::get('/checkout/auth/facebook/callback', [CheckoutFacebookController::class, 'callback'])->name('checkout.facebook.callback');
Route::post('/checkout/track-abandoned', [CheckoutController::class, 'trackAbandonedCheckout'])->name('checkout.track-abandoned');
Route::post('/set-locale', [LocaleController::class, 'set'])->name('set-locale');

View File

@@ -0,0 +1,130 @@
<?php
namespace Tests\Feature\Auth;
use App\Models\Tenant;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Auth;
use Laravel\Socialite\Facades\Socialite;
use Laravel\Socialite\Two\User as SocialiteUser;
use Mockery;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Tests\TestCase;
class TenantAdminFacebookControllerTest extends TestCase
{
use RefreshDatabase;
protected function tearDown(): void
{
Mockery::close();
parent::tearDown();
}
public function test_redirect_stores_return_to_and_issues_facebook_redirect(): void
{
$driver = Mockery::mock();
Socialite::shouldReceive('driver')->once()->with('facebook')->andReturn($driver);
$driver->shouldReceive('scopes')->once()->with(['email'])->andReturnSelf();
$driver->shouldReceive('fields')->once()->with(['name', 'email', 'first_name', 'last_name'])->andReturnSelf();
$driver->shouldReceive('redirect')->once()->andReturn(new RedirectResponse('https://facebook.com/auth'));
$encodedReturn = rtrim(strtr(base64_encode(url('/test')), '+/', '-_'), '=');
$response = $this->get('/event-admin/auth/facebook?return_to='.$encodedReturn);
$response->assertRedirect('https://facebook.com/auth');
$this->assertSame($encodedReturn, session('tenant_oauth_return_to'));
}
public function test_callback_logs_in_tenant_admin_and_redirects_to_encoded_target(): void
{
$tenant = Tenant::factory()->create();
$user = User::factory()->create([
'tenant_id' => $tenant->id,
'role' => 'tenant_admin',
]);
$socialiteUser = tap(new SocialiteUser)->map([
'id' => 'facebook-id-123',
'name' => 'Facebook Tenant Admin',
'email' => $user->email,
]);
$driver = Mockery::mock();
Socialite::shouldReceive('driver')->once()->with('facebook')->andReturn($driver);
$driver->shouldReceive('user')->once()->andReturn($socialiteUser);
$targetUrl = url('/event-admin/dashboard?foo=bar');
$encodedReturn = rtrim(strtr(base64_encode($targetUrl), '+/', '-_'), '=');
$this->withSession([
'tenant_oauth_return_to' => $encodedReturn,
]);
$response = $this->get('/event-admin/auth/facebook/callback');
$response->assertRedirect($targetUrl);
$this->assertAuthenticatedAs($user);
}
public function test_callback_ignores_intended_and_uses_admin_fallback(): void
{
$tenant = Tenant::factory()->create();
$user = User::factory()->create([
'tenant_id' => $tenant->id,
'role' => 'tenant_admin',
]);
$socialiteUser = tap(new SocialiteUser)->map([
'id' => 'facebook-id-456',
'name' => 'Facebook Tenant Admin',
'email' => $user->email,
]);
$driver = Mockery::mock();
Socialite::shouldReceive('driver')->once()->with('facebook')->andReturn($driver);
$driver->shouldReceive('user')->once()->andReturn($socialiteUser);
$this->withSession([
'url.intended' => '/packages',
]);
$response = $this->get('/event-admin/auth/facebook/callback');
$response->assertRedirect('/event-admin/dashboard');
$this->assertAuthenticatedAs($user);
}
public function test_callback_redirects_back_when_user_not_found(): void
{
$socialiteUser = tap(new SocialiteUser)->map([
'id' => 'missing-user',
'name' => 'Unknown User',
'email' => 'unknown@example.com',
]);
$driver = Mockery::mock();
Socialite::shouldReceive('driver')->once()->with('facebook')->andReturn($driver);
$driver->shouldReceive('user')->once()->andReturn($socialiteUser);
$response = $this->get('/event-admin/auth/facebook/callback');
$response->assertRedirect();
$this->assertStringContainsString('error=facebook_no_match', $response->headers->get('Location'));
$this->assertFalse(Auth::check());
}
public function test_callback_handles_socialite_failure(): void
{
$driver = Mockery::mock();
Socialite::shouldReceive('driver')->once()->with('facebook')->andReturn($driver);
$driver->shouldReceive('user')->once()->andThrow(new \RuntimeException('boom'));
$response = $this->get('/event-admin/auth/facebook/callback');
$response->assertRedirect();
$this->assertStringContainsString('error=facebook_failed', $response->headers->get('Location'));
}
}

View File

@@ -0,0 +1,112 @@
<?php
namespace Tests\Feature;
use App\Models\Package;
use App\Models\User;
use App\Support\CheckoutRoutes;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Laravel\Socialite\Contracts\Factory as SocialiteFactory;
use Laravel\Socialite\Contracts\Provider as SocialiteProvider;
use Laravel\Socialite\Contracts\User as SocialiteUserContract;
use Mockery;
use Tests\TestCase;
class CheckoutFacebookControllerTest extends TestCase
{
use RefreshDatabase;
protected function tearDown(): void
{
Mockery::close();
parent::tearDown();
}
public function test_redirect_persists_package_context_and_delegates_to_facebook(): void
{
$package = Package::factory()->create();
$provider = Mockery::mock(SocialiteProvider::class);
$provider->shouldReceive('scopes')->andReturnSelf();
$provider->shouldReceive('fields')->andReturnSelf();
$provider->shouldReceive('redirect')->once()->andReturn(redirect('/facebook/auth'));
$this->mock(SocialiteFactory::class, function ($mock) use ($provider) {
$mock->shouldReceive('driver')->with('facebook')->andReturn($provider);
});
$response = $this->get('/checkout/auth/facebook?package_id='.$package->id.'&locale=de');
$response->assertRedirect('/facebook/auth');
$this->assertSame($package->id, session('checkout_facebook_payload.package_id'));
}
public function test_callback_logs_in_existing_user_and_attaches_tenant(): void
{
$package = Package::factory()->create(['price' => 0]);
$existingUser = User::factory()->create([
'email' => 'checkout-facebook@example.com',
'pending_purchase' => false,
]);
$facebookUser = Mockery::mock(SocialiteUserContract::class);
$facebookUser->shouldReceive('getEmail')->andReturn('checkout-facebook@example.com');
$facebookUser->shouldReceive('getName')->andReturn('Checkout Facebook');
$facebookUser->shouldReceive('getAvatar')->andReturn(null);
$facebookUser->shouldReceive('getRaw')->andReturn([]);
$provider = Mockery::mock(SocialiteProvider::class);
$provider->shouldReceive('user')->andReturn($facebookUser);
$this->mock(SocialiteFactory::class, function ($mock) use ($provider) {
$mock->shouldReceive('driver')->with('facebook')->andReturn($provider);
});
$response = $this
->withSession([
'checkout_facebook_payload' => ['package_id' => $package->id, 'locale' => 'de'],
])
->get('/checkout/auth/facebook/callback');
$response->assertRedirect(CheckoutRoutes::wizardUrl($package->id, 'de'));
$this->assertAuthenticatedAs($existingUser);
$user = auth()->user();
$this->assertSame('checkout-facebook@example.com', $user->email);
$this->assertTrue($user->pending_purchase);
$this->assertNotNull($user->tenant);
$this->assertDatabaseHas('tenant_packages', [
'tenant_id' => $user->tenant_id,
'package_id' => $package->id,
]);
}
public function test_callback_with_missing_email_flashes_error(): void
{
$package = Package::factory()->create();
$facebookUser = Mockery::mock(SocialiteUserContract::class);
$facebookUser->shouldReceive('getEmail')->andReturn(null);
$facebookUser->shouldReceive('getName')->andReturn('No Email');
$facebookUser->shouldReceive('getAvatar')->andReturn(null);
$facebookUser->shouldReceive('getRaw')->andReturn([]);
$provider = Mockery::mock(SocialiteProvider::class);
$provider->shouldReceive('user')->andReturn($facebookUser);
$this->mock(SocialiteFactory::class, function ($mock) use ($provider) {
$mock->shouldReceive('driver')->with('facebook')->andReturn($provider);
});
$response = $this
->withSession([
'checkout_facebook_payload' => ['package_id' => $package->id, 'locale' => 'en'],
])
->get('/checkout/auth/facebook/callback');
$response->assertRedirect(CheckoutRoutes::wizardUrl($package->id, 'en'));
$response->assertSessionHas('checkout_facebook_error');
$this->assertGuest();
}
}