Skip to content

Commit 09e0c68

Browse files
authored
Add logic to auto authorize role with usage of redirectAuthenticatedTo (#4257)
* add logic to auto handle role with usage of `redirectAuthenticatedTo` * Create hot-knives-vanish.md * fix `globalThis.__BLITZ_GET_RSC_CONTEXT` being overriden * pnpm lock fix
1 parent fb232d1 commit 09e0c68

File tree

4 files changed

+194
-214
lines changed

4 files changed

+194
-214
lines changed

.changeset/hot-knives-vanish.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
---
2+
"@blitzjs/auth": patch
3+
"blitz": patch
4+
---
5+
6+
Automatically authorize role with usage of `redirectAuthenticatedTo` in `useAuthenticatedBlitzContext` utility

packages/blitz-auth/src/server/auth-plugin.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -125,7 +125,9 @@ export const AuthServerPlugin = createServerPlugin((options: AuthPluginOptions)
125125
}
126126
return blitzSessionMiddleware
127127
}
128-
globalThis.__BLITZ_GET_RSC_CONTEXT = getBlitzContext
128+
if (!globalThis.__BLITZ_GET_RSC_CONTEXT) {
129+
globalThis.__BLITZ_GET_RSC_CONTEXT = getBlitzContext
130+
}
129131
return {
130132
requestMiddlewares: [authPluginSessionMiddleware()],
131133
exports: () => ({

packages/blitz-auth/src/server/auth-sessions.ts

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -243,8 +243,17 @@ export async function useAuthenticatedBlitzContext({
243243
? redirectAuthenticatedTo
244244
: formatWithValidation(redirectAuthenticatedTo)
245245
debug("[useAuthenticatedBlitzContext] Redirecting to", redirectUrl)
246-
log.info("Authentication Redirect: " + customChalk.dim("(Authenticated)"), redirectUrl)
247-
redirect(redirectUrl)
246+
if (role) {
247+
try {
248+
ctx.session.$authorize(role)
249+
} catch (e) {
250+
log.info("Authentication Redirect: " + customChalk.dim(`Role ${role}`), redirectTo)
251+
redirect(redirectUrl)
252+
}
253+
} else {
254+
log.info("Authentication Redirect: " + customChalk.dim("(Authenticated)"), redirectUrl)
255+
redirect(redirectUrl)
256+
}
248257
}
249258
if (redirectTo && role) {
250259
debug("[useAuthenticatedBlitzContext] redirectTo and role are both defined.")

0 commit comments

Comments
 (0)