* refactor: migrate UnconfirmedBookingBadge from features to apps/web Move UnconfirmedBookingBadge.tsx from packages/features/bookings/ to apps/web/modules/bookings/components/ as part of the architectural refactor to remove trpc client imports from the features layer. Also removes unused preserveBookingsQueryParams function from Navigation.tsx. Co-Authored-By: [email protected] <[email protected]> * refactor: move shell navigation and badges to apps/web Move shell navigation components and trpc-using badges from packages/features to apps/web/modules to fix circular dependency: - Move navigation folder to apps/web/modules/shell/navigation/ - Move TeamInviteBadge.tsx to apps/web/modules/shell/ - Create Shell wrapper in apps/web that provides MobileNavigationContainer - Update all Shell imports in apps/web to use the new wrapper - Remove MobileNavigationContainer default from features Shell.tsx - Fix pre-existing lint warnings in touched files This establishes the pattern for migrating React components that use trpc hooks from the features layer to the web app layer, ensuring proper dependency direction: apps/web imports from packages/features, never the reverse. Co-Authored-By: [email protected] <[email protected]> * fix: move SideBar.tsx to apps/web to fix build error SideBar.tsx was importing Navigation from the moved navigation folder, causing a build error. Moving SideBar.tsx to apps/web and updating the features Shell to not have a default SidebarContainer fixes this. The web Shell wrapper now provides both the default SidebarContainer and MobileNavigationContainer, maintaining the injection pattern. Co-Authored-By: [email protected] <[email protected]> * revert * revert * revert * wip * wip * wip * wip * wip * wip * not used anywhere * wip * wip * wip * wip * fix * fix * wip * wip * wip * wip * wip * fix * fix * fix * fix * migrate * migrate admin-adpi * wip * feat: migrate organization settings components from packages/features to apps/web/modules - Migrate profile.tsx, appearance.tsx, general.tsx, privacy.tsx, guest-notifications.tsx, delegationCredential.tsx, other-team-members-view.tsx, other-team-profile-view.tsx - Migrate attributes directory (AttributesForm.tsx, DeleteAttributeModal.tsx, ListSkeleton.tsx, attributes-create-view.tsx, attributes-edit-view.tsx, attributes-list-view.tsx) - Migrate admin directory (AdminOrgEditPage.tsx, AdminOrgPage.tsx, WorkspacePlatformPage.tsx) - Update all page imports to use new paths from ~/settings/organizations/ - Update relative imports in migrated files to use @calcom/features paths - Fix lint warnings in migrated files Co-Authored-By: [email protected] <[email protected]> * fix: update test import path after migration Co-Authored-By: [email protected] <[email protected]> * fix: remove unnecessary test-setup import (already in vitest config) Co-Authored-By: [email protected] <[email protected]> * wip * refactor: delete original files after migration to apps/web/modules Co-Authored-By: [email protected] <[email protected]> * wip * wip * wip * wip * wip * wip * wip * wip * wip * wip * wip * wip * wip * fix * fix * fix * fix * wip * refactor more * wip * wip * wip * wip * wip * wip * wip * wip * wip * wip * mv * update import paths * wip * wip * fix * fix * fix * fix * fix * fix * fix * mv * mv * mv * fix * wip * wip * fix * fix * fix * fix: make test mocks resilient to vi.resetAllMocks() Co-Authored-By: [email protected] <[email protected]> * fix: fix AttributeForm test failures Co-Authored-By: [email protected] <[email protected]> * fix * fix * refactor: move ee files to apps/web/modules/ee/ folder - Move teams, workflows, and organizations folders to apps/web/modules/ee/ - Add LICENSE file to apps/web/modules/ee/ - Update all import paths from ~/teams/ to ~/ee/teams/ - Update all import paths from ~/settings/organizations/ to ~/ee/organizations/ - Remove duplicate MemberInvitationModal copy.tsx file Co-Authored-By: [email protected] <[email protected]> * fix: move useHasPaidPlan and dependent files to apps/web/modules - Move useHasPaidPlan.ts from packages/features/billing/hooks to apps/web/modules/billing/hooks - Move intercom files from packages/features/ee/support to apps/web/modules/ee/support - Move ContactMenuItem.tsx and dependencies (freshchat, helpscout, zendesk) to apps/web/modules/ee/support - Move ViewRecordingsDialog.tsx and RecordingListSkeleton to apps/web/modules/ee/video - Move CalVideoSettings.tsx to apps/web/modules/eventtypes/components/locations - Move CreateOrEditOutOfOfficeModal.tsx to apps/web/modules/settings/outOfOffice - Refactor UpgradeTeamsBadge to accept props and create wrapper in apps/web/modules/billing - Update all callers to use new file locations - Add eslint-disable comments for pre-existing lint warnings This fixes the tRPC server build failure caused by circular dependency where the server build was traversing into packages/features and pulling in React hooks that depend on @calcom/trpc/react types. Co-Authored-By: [email protected] <[email protected]> * fix: correct UpgradeTeamsBadge import path to use package export Co-Authored-By: [email protected] <[email protected]> * wip * wip * wip * wip * wip * wip * wip * wip * wip * wip * wip * wip * wip * wip * wip * fix * fix * fix * fix * fix * fix * fix * fix: pass plan state through SelectProps to UpgradeTeamsBadge - Add upgradeTeamsBadgeProps field to ExtendedOption type in Select component - Update OptionComponent to spread upgradeTeamsBadgeProps to UpgradeTeamsBadge - Update getOptions.ts to accept PlanState object and include upgradeTeamsBadgeProps - Update WorkflowStepContainer.tsx to pass planState to getWorkflowTriggerOptions/getWorkflowTemplateOptions - Update WorkflowDetailsPage.tsx to pass upgradeTeamsBadgeProps in transformed action options - Update AddActionDialog.tsx interface and mapping to include upgradeTeamsBadgeProps - Add eslint-disable comments for pre-existing React Hook dependency warnings This fixes the UpgradeTeamsBadge refactoring issue where the badge was always showing 'upgrade' text instead of the correct text based on plan state (trial_mode, inactive_team_plan, etc.) Co-Authored-By: [email protected] <[email protected]> * fix: update import paths to use /ee/ folder for workflows and organizations Co-Authored-By: [email protected] <[email protected]> * fix: update workflow component imports to use /ee/ folder Co-Authored-By: [email protected] <[email protected]> * fix: add missing types.ts for LocationInput.tsx Co-Authored-By: [email protected] <[email protected]> * fix: extract BookingRedirectForm type to shared location Co-Authored-By: [email protected] <[email protected]> * fix * wip * wip * fix: update BookingRedirectForm import to use local types file Co-Authored-By: [email protected] <[email protected]> * wip * fix * fix --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
344 lines
10 KiB
TypeScript
344 lines
10 KiB
TypeScript
import { CalComAPIService } from "../services/calcom";
|
|
import {
|
|
createCalComOAuthService,
|
|
OAuthTokens,
|
|
CalComOAuthService,
|
|
} from "../services/oauthService";
|
|
import { WebAuthService } from "../services/webAuth";
|
|
import { secureStorage } from "../utils/storage";
|
|
import React, { createContext, useContext, useState, useEffect, ReactNode } from "react";
|
|
|
|
interface AuthContextType {
|
|
isAuthenticated: boolean;
|
|
accessToken: string | null;
|
|
refreshToken: string | null;
|
|
userInfo: any;
|
|
isWebSession: boolean;
|
|
loginFromWebSession: (userInfo: any) => Promise<void>;
|
|
loginWithOAuth: () => Promise<void>;
|
|
logout: () => Promise<void>;
|
|
loading: boolean;
|
|
}
|
|
|
|
const AuthContext = createContext<AuthContextType | undefined>(undefined);
|
|
|
|
const ACCESS_TOKEN_KEY = "cal_access_token";
|
|
const REFRESH_TOKEN_KEY = "cal_refresh_token";
|
|
const OAUTH_TOKENS_KEY = "cal_oauth_tokens";
|
|
const AUTH_TYPE_KEY = "cal_auth_type";
|
|
|
|
type AuthType = "oauth" | "web_session";
|
|
|
|
interface AuthProviderProps {
|
|
children: ReactNode;
|
|
}
|
|
|
|
// Use the shared secure storage adapter
|
|
const storage = secureStorage;
|
|
|
|
const getErrorMessage = (error: unknown) =>
|
|
error instanceof Error ? error.message : String(error);
|
|
const getErrorStack = (error: unknown) => (error instanceof Error ? error.stack : undefined);
|
|
|
|
export function AuthProvider({ children }: AuthProviderProps) {
|
|
const [isAuthenticated, setIsAuthenticated] = useState(false);
|
|
const [accessToken, setAccessToken] = useState<string | null>(null);
|
|
const [refreshToken, setRefreshToken] = useState<string | null>(null);
|
|
const [userInfo, setUserInfo] = useState<any>(null);
|
|
const [isWebSession, setIsWebSession] = useState(false);
|
|
const [loading, setLoading] = useState(true);
|
|
const [oauthService] = useState(() => {
|
|
try {
|
|
return createCalComOAuthService();
|
|
} catch (error) {
|
|
console.warn("Failed to initialize OAuth service:", error);
|
|
return null;
|
|
}
|
|
});
|
|
|
|
// Setup refresh token function for OAuth
|
|
const setupRefreshTokenFunction = (service: CalComOAuthService) => {
|
|
CalComAPIService.setRefreshTokenFunction(async (refreshToken: string) => {
|
|
const newTokens = await service.refreshAccessToken(refreshToken);
|
|
return {
|
|
accessToken: newTokens.accessToken,
|
|
refreshToken: newTokens.refreshToken,
|
|
};
|
|
});
|
|
};
|
|
|
|
// Common post-login setup: configure API service and fetch user profile
|
|
const setupAfterLogin = async (token: string, refreshToken?: string) => {
|
|
CalComAPIService.setAccessToken(token, refreshToken);
|
|
|
|
try {
|
|
const profile = await CalComAPIService.getUserProfile();
|
|
// Store user info for use in the app (e.g., to display "You" in bookings)
|
|
if (profile) {
|
|
setUserInfo({
|
|
email: profile.email,
|
|
name: profile.name,
|
|
id: profile.id,
|
|
username: profile.username,
|
|
});
|
|
}
|
|
} catch (profileError) {
|
|
console.error("Failed to fetch user profile:", profileError);
|
|
// Don't fail login if profile fetch fails
|
|
}
|
|
};
|
|
|
|
const saveOAuthTokens = async (tokens: OAuthTokens) => {
|
|
await storage.set(OAUTH_TOKENS_KEY, JSON.stringify(tokens));
|
|
await storage.set(AUTH_TYPE_KEY, "oauth");
|
|
|
|
if (oauthService) {
|
|
try {
|
|
await oauthService.syncTokensToExtension(tokens);
|
|
} catch (error) {
|
|
console.warn("Failed to sync tokens to extension:", error);
|
|
}
|
|
}
|
|
};
|
|
|
|
const clearAuth = async () => {
|
|
await storage.removeAll([ACCESS_TOKEN_KEY, REFRESH_TOKEN_KEY, OAUTH_TOKENS_KEY, AUTH_TYPE_KEY]);
|
|
|
|
if (oauthService) {
|
|
try {
|
|
await oauthService.clearTokensFromExtension();
|
|
} catch (error) {
|
|
console.warn("Failed to clear tokens from extension:", error);
|
|
}
|
|
}
|
|
};
|
|
|
|
// Reset all auth state
|
|
const resetAuthState = () => {
|
|
setAccessToken(null);
|
|
setRefreshToken(null);
|
|
setUserInfo(null);
|
|
setIsAuthenticated(false);
|
|
setIsWebSession(false);
|
|
CalComAPIService.clearAuth();
|
|
CalComAPIService.clearUserProfile();
|
|
};
|
|
|
|
useEffect(() => {
|
|
checkAuthState();
|
|
|
|
// Set up token refresh callback
|
|
const handleTokenRefresh = async (newAccessToken: string, newRefreshToken?: string) => {
|
|
try {
|
|
const tokens: OAuthTokens = {
|
|
accessToken: newAccessToken,
|
|
refreshToken: newRefreshToken || refreshToken || undefined,
|
|
tokenType: "Bearer",
|
|
};
|
|
|
|
await saveOAuthTokens(tokens);
|
|
setAccessToken(newAccessToken);
|
|
if (newRefreshToken) {
|
|
setRefreshToken(newRefreshToken);
|
|
}
|
|
|
|
CalComAPIService.setAccessToken(
|
|
newAccessToken,
|
|
newRefreshToken || refreshToken || undefined
|
|
);
|
|
} catch (error) {
|
|
const message = getErrorMessage(error);
|
|
console.error("Failed to handle token refresh", message);
|
|
if (__DEV__) {
|
|
console.debug("[AuthContext] token refresh handler failed", {
|
|
message,
|
|
stack: getErrorStack(error),
|
|
});
|
|
}
|
|
await logout();
|
|
}
|
|
};
|
|
|
|
CalComAPIService.setTokenRefreshCallback(handleTokenRefresh);
|
|
|
|
return () => {
|
|
CalComAPIService.setTokenRefreshCallback(() => Promise.resolve());
|
|
};
|
|
}, [refreshToken]);
|
|
|
|
// Handle OAuth authentication
|
|
const handleOAuthAuth = async (storedTokens: OAuthTokens) => {
|
|
if (!oauthService) return;
|
|
|
|
// Refresh token if expired
|
|
let tokens = storedTokens;
|
|
let tokensWereRefreshed = false;
|
|
if (oauthService.isTokenExpired(storedTokens) && storedTokens.refreshToken) {
|
|
try {
|
|
console.log("Access token expired, refreshing...");
|
|
tokens = await oauthService.refreshAccessToken(storedTokens.refreshToken);
|
|
await saveOAuthTokens(tokens);
|
|
tokensWereRefreshed = true;
|
|
} catch (refreshError) {
|
|
console.error("Failed to refresh token:", refreshError);
|
|
await clearAuth();
|
|
return;
|
|
}
|
|
}
|
|
|
|
// Set state
|
|
setAccessToken(tokens.accessToken);
|
|
setRefreshToken(tokens.refreshToken || null);
|
|
setIsAuthenticated(true);
|
|
setIsWebSession(false);
|
|
|
|
// Setup API service and refresh function
|
|
await setupAfterLogin(tokens.accessToken, tokens.refreshToken);
|
|
if (tokens.refreshToken) {
|
|
setupRefreshTokenFunction(oauthService);
|
|
}
|
|
|
|
if (!tokensWereRefreshed) {
|
|
try {
|
|
await oauthService.syncTokensToExtension(tokens);
|
|
} catch (error) {
|
|
console.warn("Failed to sync tokens to extension on init:", error);
|
|
}
|
|
}
|
|
};
|
|
|
|
// Handle web session authentication
|
|
const handleWebSessionAuth = () => {
|
|
setIsWebSession(true);
|
|
};
|
|
|
|
const checkAuthState = async () => {
|
|
try {
|
|
const authType = (await storage.get(AUTH_TYPE_KEY)) as AuthType | null;
|
|
const storedOAuthTokens = await storage.get(OAUTH_TOKENS_KEY);
|
|
const storedTokens = storedOAuthTokens ? JSON.parse(storedOAuthTokens) : null;
|
|
|
|
if (authType === "oauth" && storedTokens && oauthService) {
|
|
await handleOAuthAuth(storedTokens);
|
|
} else if (authType === "web_session") {
|
|
handleWebSessionAuth();
|
|
}
|
|
} catch (error) {
|
|
const message = getErrorMessage(error);
|
|
console.error("Failed to check auth state", message);
|
|
if (__DEV__) {
|
|
console.debug("[AuthContext] checkAuthState failed", {
|
|
message,
|
|
stack: getErrorStack(error),
|
|
});
|
|
}
|
|
} finally {
|
|
setLoading(false);
|
|
}
|
|
};
|
|
|
|
const loginFromWebSession = async (sessionUserInfo: any) => {
|
|
try {
|
|
setUserInfo(sessionUserInfo);
|
|
setIsAuthenticated(true);
|
|
setIsWebSession(true);
|
|
await storage.set(AUTH_TYPE_KEY, "web_session");
|
|
|
|
// Try to get tokens from web session
|
|
const tokens = await WebAuthService.getTokensFromWebSession();
|
|
if (tokens.accessToken) {
|
|
setAccessToken(tokens.accessToken);
|
|
setRefreshToken(tokens.refreshToken || null);
|
|
await setupAfterLogin(tokens.accessToken, tokens.refreshToken);
|
|
}
|
|
} catch (error) {
|
|
const message = getErrorMessage(error);
|
|
console.error("Failed to login from web session", message);
|
|
if (__DEV__) {
|
|
console.debug("[AuthContext] loginFromWebSession failed", {
|
|
message,
|
|
stack: getErrorStack(error),
|
|
});
|
|
}
|
|
throw error;
|
|
}
|
|
};
|
|
|
|
const loginWithOAuth = async (): Promise<void> => {
|
|
if (!oauthService) {
|
|
throw new Error("OAuth service not available. Please check your configuration.");
|
|
}
|
|
|
|
try {
|
|
setLoading(true);
|
|
|
|
const tokens = await oauthService.startAuthorizationFlow();
|
|
|
|
// Save tokens
|
|
await saveOAuthTokens(tokens);
|
|
|
|
// Update state
|
|
setAccessToken(tokens.accessToken);
|
|
setRefreshToken(tokens.refreshToken || null);
|
|
setIsAuthenticated(true);
|
|
setIsWebSession(false);
|
|
|
|
// Setup API service and refresh function
|
|
await setupAfterLogin(tokens.accessToken, tokens.refreshToken);
|
|
if (tokens.refreshToken) {
|
|
setupRefreshTokenFunction(oauthService);
|
|
}
|
|
|
|
// Clear PKCE parameters
|
|
oauthService.clearPKCEParams();
|
|
} catch (error) {
|
|
const message = getErrorMessage(error);
|
|
console.error("OAuth login failed", message);
|
|
if (__DEV__) {
|
|
console.debug("[AuthContext] loginWithOAuth failed", {
|
|
message,
|
|
stack: getErrorStack(error),
|
|
});
|
|
}
|
|
throw error;
|
|
} finally {
|
|
setLoading(false);
|
|
}
|
|
};
|
|
|
|
const logout = async () => {
|
|
try {
|
|
await clearAuth();
|
|
resetAuthState();
|
|
} catch (error) {
|
|
const message = getErrorMessage(error);
|
|
console.error("Failed to logout", message);
|
|
if (__DEV__) {
|
|
console.debug("[AuthContext] logout failed", { message, stack: getErrorStack(error) });
|
|
}
|
|
}
|
|
};
|
|
|
|
const value: AuthContextType = {
|
|
isAuthenticated,
|
|
accessToken,
|
|
refreshToken,
|
|
userInfo,
|
|
isWebSession,
|
|
loginFromWebSession,
|
|
loginWithOAuth,
|
|
logout,
|
|
loading,
|
|
};
|
|
|
|
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
|
|
}
|
|
|
|
export function useAuth(): AuthContextType {
|
|
const context = useContext(AuthContext);
|
|
if (context === undefined) {
|
|
throw new Error("useAuth must be used within an AuthProvider");
|
|
}
|
|
return context;
|
|
}
|