-
-
Notifications
You must be signed in to change notification settings - Fork 440
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(core): guard session with sign-in mode
- Loading branch information
Showing
2 changed files
with
52 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
48 changes: 48 additions & 0 deletions
48
packages/core/src/routes/session/middleware/koa-guard-session-action.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
import { SignInMode } from '@logto/schemas'; | ||
import { adminConsoleApplicationId } from '@logto/schemas/lib/seeds'; | ||
import { MiddlewareType } from 'koa'; | ||
import { Provider, errors } from 'oidc-provider'; | ||
|
||
import RequestError from '@/errors/RequestError'; | ||
import { findDefaultSignInExperience } from '@/queries/sign-in-experience'; | ||
import assertThat from '@/utils/assert-that'; | ||
|
||
export default function KoaGuardSessionAction<StateT, ContextT, ResponseBodyT>( | ||
provider: Provider, | ||
forType: 'sign-in' | 'register' | ||
): MiddlewareType<StateT, ContextT, ResponseBodyT> { | ||
const forbiddenError = new RequestError({ code: 'auth.forbidden', status: 403 }); | ||
|
||
return async (ctx, next) => { | ||
const interaction = await provider | ||
.interactionDetails(ctx.req, ctx.res) | ||
.catch((error: unknown) => { | ||
// Should not block if interaction is not found | ||
if (error instanceof errors.SessionNotFound) { | ||
return null; | ||
} | ||
|
||
throw error; | ||
}); | ||
|
||
/** | ||
* We don't guard admin console in API for now since logically there's no need. | ||
* Update to honor the config if we're implementing per-app SIE. | ||
*/ | ||
if (interaction?.params.client_id === adminConsoleApplicationId) { | ||
return next(); | ||
} | ||
|
||
const { signInMode } = await findDefaultSignInExperience(); | ||
|
||
if (forType === 'sign-in') { | ||
assertThat(signInMode !== SignInMode.Register, forbiddenError); | ||
} | ||
|
||
if (forType === 'register') { | ||
assertThat(signInMode !== SignInMode.SignIn, forbiddenError); | ||
} | ||
|
||
return next(); | ||
}; | ||
} |