Skip to content

Beautiful Open-Source Form Builder

Enhance OAuth context management and UTM data handling

JhumanJ02fd053449e0
diff --git a/api/app/Http/Controllers/Auth/OAuthController.php b/api/app/Http/Controllers/Auth/OAuthController.php
index 11180d0ae..1513e4506 100644
--- a/api/app/Http/Controllers/Auth/OAuthController.php
+++ b/api/app/Http/Controllers/Auth/OAuthController.php
@@ -46,6 +46,7 @@ class OAuthController extends Controller
$request->validate([
'intent' => 'required|in:auth,integration',
'invite_token' => 'sometimes|string',
+ 'utm_data' => 'sometimes|array',
]);
$result = $this->flowOrchestrator->processWidgetCallback($service, $request);
diff --git a/api/app/Service/OAuth/OAuthContextService.php b/api/app/Service/OAuth/OAuthContextService.php
index 60ae4c8b1..9d9418c5a 100644
--- a/api/app/Service/OAuth/OAuthContextService.php
+++ b/api/app/Service/OAuth/OAuthContextService.php
@@ -4,24 +4,64 @@ namespace App\Service\OAuth;
use Illuminate\Support\Facades\Cache;
+/**
+ * OAuthContextService
+ *
+ * Manages OAuth flow context and metadata across authentication attempts.
+ * Handles storage and retrieval of temporary data needed during OAuth callbacks:
+ * - State tokens (for security in redirect-based flows)
+ * - UTM tracking data (for user acquisition attribution)
+ * - Invite tokens (for workspace invitations)
+ * - Intent flags (auth vs integration)
+ *
+ * Uses cache for temporary storage with 5-minute TTL to prevent stale data.
+ * Supports both redirect-based OAuth flows (with state tokens) and widget-based flows.
+ */
class OAuthContextService
{
private const CACHE_TTL_MINUTES = 5;
+ private const REDIRECT_CONTEXT_PREFIX = 'oauth-context:state:';
+ private const WIDGET_CONTEXT_PREFIX = 'oauth-context:widget:';
/**
* Store OAuth context with a unique state token
+ * Used for redirect-based OAuth flows (Google OAuth, GitHub, etc.)
+ *
+ * @param array $context {
+ * @type string $intent 'auth' or 'integration'
+ * @type array|null $utm_data UTM parameters for tracking
+ * @type string|null $invited_email Email address for invite validation
+ * @type string|null $invite_token Token for workspace invitations
+ * @type string|null $intention User's intention/purpose
+ * @type bool $autoClose Whether popup should auto-close
+ * }
+ * @return string State token for OAuth callback
*/
public function storeContext(array $context): string
{
// Generate a unique state token for this OAuth flow
$stateToken = bin2hex(random_bytes(16));
- $key = "oauth-context:state:" . $stateToken;
+ $key = self::REDIRECT_CONTEXT_PREFIX . $stateToken;
Cache::put($key, $context, now()->addMinutes(self::CACHE_TTL_MINUTES));
return $stateToken;
}
+ /**
+ * Store widget context with session-based key
+ * Used for widget-based OAuth flows (Google One Tap, etc.)
+ *
+ * @param array $context OAuth context data
+ * @return string Session ID key for retrieval
+ */
+ public function storeWidgetContext(array $context): string
+ {
+ $key = self::WIDGET_CONTEXT_PREFIX . session()->getId();
+ Cache::put($key, $context, now()->addMinutes(self::CACHE_TTL_MINUTES));
+ return $key;
+ }
+
/**
* Get context from cache using state token
*/
@@ -33,7 +73,16 @@ class OAuthContextService
return null;
}
- $key = "oauth-context:state:" . $stateToken;
+ $key = self::REDIRECT_CONTEXT_PREFIX . $stateToken;
+ return Cache::get($key);
+ }
+
+ /**
+ * Get widget context from cache using session ID
+ */
+ public function getWidgetContext(): ?array
+ {
+ $key = self::WIDGET_CONTEXT_PREFIX . session()->getId();
return Cache::get($key);
}
@@ -45,11 +94,20 @@ class OAuthContextService
$stateToken = $stateToken ?? request()->input('state');
if ($stateToken) {
- $key = "oauth-context:state:" . $stateToken;
+ $key = self::REDIRECT_CONTEXT_PREFIX . $stateToken;
Cache::forget($key);
}
}
+ /**
+ * Clear widget context after use
+ */
+ public function clearWidgetContext(): void
+ {
+ $key = self::WIDGET_CONTEXT_PREFIX . session()->getId();
+ Cache::forget($key);
+ }
+
/**
* Determine intent from stored context
*/
@@ -82,6 +140,7 @@ class OAuthContextService
/**
* Get UTM data from context
+ * Retrieves tracking data (source, medium, campaign, etc.) for user attribution
*/
public function getUtmData(): ?array
{
diff --git a/api/app/Service/OAuth/OAuthFlowOrchestrator.php b/api/app/Service/OAuth/OAuthFlowOrchestrator.php
index 7ec2bdce1..8f153a893 100644
--- a/api/app/Service/OAuth/OAuthFlowOrchestrator.php
+++ b/api/app/Service/OAuth/OAuthFlowOrchestrator.php
@@ -9,6 +9,23 @@ use App\Service\OAuth\OAuthProviderService as OAuthProviderServiceClass;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
+/**
+ * OAuthFlowOrchestrator
+ *
+ * Orchestrates the OAuth authentication and integration flows.
+ * Handles:
+ * - OAuth redirect initiation with state token generation
+ * - OAuth callback processing (authorization code exchange)
+ * - Widget-based OAuth flows (Google One Tap)
+ * - Intent routing (auth vs integration)
+ * - Error handling and validation
+ *
+ * Delegates specific responsibilities to specialized services:
+ * - OAuthContextService: Context/metadata storage
+ * - OAuthUserDataService: User data extraction
+ * - OAuthUserService: User creation/lookup
+ * - OAuthInviteService: Invite validation
+ */
class OAuthFlowOrchestrator
{
use ManagesJWT;
@@ -28,6 +45,7 @@ class OAuthFlowOrchestrator
/**
* Process OAuth redirect request
+ * Stores context with UTM data and generates state token for security
*/
public function processRedirect(string $provider, array $params): array
{
@@ -81,6 +99,7 @@ class OAuthFlowOrchestrator
/**
* Process OAuth callback
+ * Retrieves context from state token and creates/authenticates user
*/
public function processCallback(string $provider, array $params): array
{
@@ -113,6 +132,8 @@ class OAuthFlowOrchestrator
/**
* Process widget-based OAuth callback
+ * Handles widget flows (Google One Tap) that don't use state tokens
+ * Extracts and stores context for user creation
*/
public function processWidgetCallback(string $service, Request $request): array
{
@@ -136,6 +157,15 @@ class OAuthFlowOrchestrator
// Get user data from widget
$userData = $this->userDataService->extractFromWidget($providerService, $request);
+ // Store widget context for later retrieval during user creation
+ $context = [
+ 'intent' => $intent,
+ 'utm_data' => $request->input('utm_data'),
+ 'invite_token' => $inviteToken,
+ 'invited_email' => $invitedEmail,
+ ];
+ $this->contextService->storeWidgetContext($context);
+
return $this->handleIntent($intent, $providerService, $userData, $inviteToken, $invitedEmail);
}
@@ -178,12 +208,15 @@ class OAuthFlowOrchestrator
// Generic email validation (no provider-specific logic)
$this->inviteService->validateEmailRestrictions($userData['email'], $invitedEmail);
- // Find or create user with invite context
+ // Find or create user
$user = $this->oauthUserService->findOrCreateUser($userData, $providerService, $inviteToken);
// Create/update OAuth provider record
$this->oauthProviderService->createOrUpdateProvider($user, $providerService, $userData);
+ // Clear widget context if it exists
+ $this->contextService->clearWidgetContext();
+
// Return JWT token for authentication
$response = $this->sendLoginResponse($user);
return $response->getData(true);
diff --git a/api/app/Service/OAuth/OAuthInviteService.php b/api/app/Service/OAuth/OAuthInviteService.php
index aebf108e0..596383778 100644
--- a/api/app/Service/OAuth/OAuthInviteService.php
+++ b/api/app/Service/OAuth/OAuthInviteService.php
@@ -6,6 +6,20 @@ use App\Models\UserInvite;
use App\Integrations\OAuth\Drivers\Contracts\OAuthDriver;
use App\Integrations\OAuth\Drivers\Contracts\SupportsEmailRestrictions;
+/**
+ * OAuthInviteService
+ *
+ * Manages OAuth authentication with workspace invitations.
+ * Responsibilities:
+ * - Validating invitation tokens
+ * - Checking token expiration
+ * - Extracting invited email addresses
+ * - Configuring OAuth drivers with email restrictions
+ * - Enforcing email address restrictions during authentication
+ *
+ * Ensures that users registering via OAuth invitations authenticate
+ * with the email address that was invited, preventing unauthorized access.
+ */
class OAuthInviteService
{
/**
diff --git a/api/app/Service/OAuth/OAuthUserDataService.php b/api/app/Service/OAuth/OAuthUserDataService.php
index f2e20ae87..fdc2551f7 100644
--- a/api/app/Service/OAuth/OAuthUserDataService.php
+++ b/api/app/Service/OAuth/OAuthUserDataService.php
@@ -7,6 +7,19 @@ use App\Integrations\OAuth\OAuthProviderService;
use App\Integrations\OAuth\Drivers\Contracts\WidgetOAuthDriver;
use Illuminate\Http\Request;
+/**
+ * OAuthUserDataService
+ *
+ * Extracts and normalizes user data from OAuth providers.
+ * Handles:
+ * - Redirect-based OAuth flows (authorization code grant)
+ * - Widget-based OAuth flows (Google One Tap)
+ * - User data validation and normalization
+ * - Missing field detection
+ *
+ * Normalizes data from different OAuth providers into a consistent format
+ * for downstream processing by OAuthUserService.
+ */
class OAuthUserDataService
{
/**
diff --git a/api/app/Service/OAuth/OAuthUserService.php b/api/app/Service/OAuth/OAuthUserService.php
index f6d180dbd..1e88a7e43 100644
--- a/api/app/Service/OAuth/OAuthUserService.php
+++ b/api/app/Service/OAuth/OAuthUserService.php
@@ -5,11 +5,38 @@ namespace App\Service\OAuth;
use App\Integrations\OAuth\OAuthProviderService;
use App\Models\User;
use App\Service\WorkspaceInviteService;
-use Illuminate\Support\Facades\Cache;
use Illuminate\Http\Exceptions\HttpResponseException;
+/**
+ * OAuthUserService
+ *
+ * Handles OAuth user creation and lookup.
+ * Responsibilities:
+ * - Finding existing users by email and OAuth provider
+ * - Creating new user accounts from OAuth data
+ * - Assigning users to workspaces (default or invited)
+ * - Retrieving and storing UTM tracking data
+ * - Preventing duplicate account creation and account takeover
+ *
+ * Retrieves UTM data from OAuthContextService for consistent tracking
+ * across both redirect-based and widget-based OAuth flows.
+ */
class OAuthUserService
{
+ public function __construct(
+ private OAuthContextService $contextService
+ ) {
+ }
+
+ /**
+ * Find existing user or create new one from OAuth data
+ *
+ * @param array $userData OAuth user data (name, email, provider_user_id, etc.)
+ * @param OAuthProviderService $providerService The OAuth provider (Google, GitHub, etc.)
+ * @param string|null $inviteToken Workspace invitation token if applicable
+ * @return User Created or existing user with new_user flag if newly created
+ * @throws HttpResponseException If email already exists under different provider
+ */
public function findOrCreateUser(array $userData, OAuthProviderService $providerService, ?string $inviteToken = null): User
{
$email = strtolower($userData['email']);
@@ -43,9 +70,8 @@ class OAuthUserService
abort(422, 'User registration is not allowed.');
}
- // Get UTM data from context
- $context = Cache::get("oauth-context:auth:" . session()->getId(), []);
- $utmData = $context['utm_data'] ?? null;
+ // Get UTM data from context service (works for both redirect and widget flows)
+ $utmData = $this->contextService->getUtmData() ?? $this->contextService->getWidgetContext()['utm_data'] ?? null;
$user = User::create([
'name' => $userData['name'],
diff --git a/client/components/vendor/GoogleOneTap.vue b/client/components/vendor/GoogleOneTap.vue
index f43284719..d6536318d 100644
--- a/client/components/vendor/GoogleOneTap.vue
+++ b/client/components/vendor/GoogleOneTap.vue
@@ -139,7 +139,8 @@ const handleCredentialResponse = (response) => {
const route = useRoute()
const inviteToken = route.query.invite_token
- // Prepare request data
+ // Prepare request data with UTM data
+ const { $utm } = useNuxtApp()
const requestData = {
credential: response.credential,
intent: 'auth'
@@ -150,6 +151,11 @@ const handleCredentialResponse = (response) => {
requestData.invite_token = inviteToken
}
+ // Add UTM data if available
+ if ($utm?.value) {
+ requestData.utm_data = $utm.value
+ }
+
// Send JWT to backend widget callback
widgetCallbackMutation.mutateAsync({
service: 'google_one_tap',