Skip to content

feat(auth): refactor ConfigurationError class and enhance project configuration in auth flow #524

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 8 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions apps/kitchensink-react/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@ import {AppRoutes} from './AppRoutes'
const theme = buildTheme({})

const sanityConfigs: SanityConfig[] = [
{
projectId: 'project-id',
dataset: 'data-set',
},
{
projectId: 'ppsg7ml5',
dataset: 'test',
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/_exports/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export {
type LoggedOutAuthState,
type LoggingInAuthState,
} from '../auth/authStore'
export {observeOrganizationVerificationState} from '../auth/getOrganizationVerificationState'
export {ConfigurationError} from '../auth/ConfigurationError'
export {handleAuthCallback} from '../auth/handleAuthCallback'
export {logout} from '../auth/logout'
export type {ClientStoreState as ClientState} from '../client/clientStore'
Expand Down
85 changes: 82 additions & 3 deletions packages/core/src/auth/authStore.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
import {type ClientConfig, createClient, type SanityClient} from '@sanity/client'
import {type CurrentUser} from '@sanity/types'
import {type Subscription} from 'rxjs'
import {combineLatest, filter, map, type Subscription, switchMap} from 'rxjs'

import {type AuthConfig, type AuthProvider} from '../config/authConfig'
import {bindActionGlobally} from '../store/createActionBinder'
import {type SanityInstance} from '../store/createSanityInstance'
import {createStateSourceAction} from '../store/createStateSourceAction'
import {defineStore} from '../store/defineStore'
import {defineStore, type StoreContext} from '../store/defineStore'
import {DEFAULT_API_VERSION, REQUEST_TAG_PREFIX} from './authConstants'
import {AuthStateType} from './authStateType'
import {ConfigurationError} from './ConfigurationError'
import {refreshStampedToken} from './refreshStampedToken'
import {checkForCookieAuth, getStudioTokenFromLocalStorage} from './studioModeAuth'
import {subscribeToStateAndFetchCurrentUser} from './subscribeToStateAndFetchCurrentUser'
Expand Down Expand Up @@ -89,6 +92,7 @@ export interface AuthStoreState {
authMethod: AuthMethodOptions
}
dashboardContext?: DashboardContext
error?: unknown
}

export const authStore = defineStore<AuthStoreState>({
Expand Down Expand Up @@ -211,6 +215,7 @@ export const authStore = defineStore<AuthStoreState>({
initialize(context) {
const subscriptions: Subscription[] = []
subscriptions.push(subscribeToStateAndFetchCurrentUser(context))
subscriptions.push(listenToProjectIdsAndDashboard(context))

if (context.state.get().options?.storageArea) {
subscriptions.push(subscribeToStorageEventsAndSetToken(context))
Expand All @@ -229,6 +234,77 @@ export const authStore = defineStore<AuthStoreState>({
},
})

function getProjectIdsFromInstanceAndParents(instance: SanityInstance | undefined): string[] {
if (!instance) return []

const projectIds: string[] = []
if (instance.config?.projectId) {
projectIds.push(instance.config.projectId)
}

const parentProjectIds = getProjectIdsFromInstanceAndParents(instance.getParent())
return projectIds.concat(parentProjectIds)
}

const listenToProjectIdsAndDashboard = ({instance, state}: StoreContext<AuthStoreState>) => {
const {
options: {clientFactory, apiHost},
} = state.get()

const projectIds = getProjectIdsFromInstanceAndParents(instance)

const token$ = state.observable.pipe(
map((i) => i.authState.type === AuthStateType.LOGGED_IN && i.authState.token),
filter((i) => typeof i === 'string'),
)

const client$ = token$.pipe(
map((token) =>
clientFactory({
apiVersion: DEFAULT_API_VERSION,
requestTagPrefix: REQUEST_TAG_PREFIX,
useProjectHostname: false,
useCdn: false,
token,
...(apiHost && {apiHost}),
}),
),
)

const orgId$ = state.observable.pipe(
map((i) => i.dashboardContext?.orgId),
filter(Boolean),
)

const organizationIdsFromProjects$ = combineLatest(
projectIds.map((projectId) =>
client$.pipe(
switchMap((client) => client.observable.projects.getById(projectId)),
map((i) => ({projectId: i.id, organizationId: i.organizationId})),
),
),
)

return combineLatest([orgId$, organizationIdsFromProjects$])
.pipe(
map(([orgId, orgIdsFromProjects]) => {
for (const {organizationId, projectId} of orgIdsFromProjects) {
if (orgId !== organizationId) {
throw new ConfigurationError(
new Error(
`Project ${projectId} is not part of organization ${orgId}. ` +
`The project belongs to organization ${organizationId} instead.`,
),
)
}
}
}),
)
.subscribe({
error: (error) => state.set('setError', {authState: {error, type: AuthStateType.ERROR}}),
})
}

/**
* @public
*/
Expand Down Expand Up @@ -270,7 +346,10 @@ export const getLoginUrlState = bindActionGlobally(
*/
export const getAuthState = bindActionGlobally(
authStore,
createStateSourceAction(({state: {authState}}) => authState),
createStateSourceAction(({state: {authState}}) => {
if (authState.type === AuthStateType.ERROR) throw authState.error
return authState
}),
)

/**
Expand Down
197 changes: 0 additions & 197 deletions packages/core/src/auth/getOrganizationVerificationState.test.ts

This file was deleted.

Loading
Loading