@@ -14,9 +14,48 @@ import { getStandardCookieOptions } from "../utils/cookies/getStandardCookieOpti
1414import { isPublicPathMatch } from "../utils/isPublicPathMatch" ;
1515import { TWENTY_NINE_DAYS } from "src/utils/constants" ;
1616
17+ /**
18+ * Handles invitation code redirect logic.
19+ * Redirects to the register page with the invitation code, or to login on error.
20+ */
21+ const handleInvitationCodeRedirect = (
22+ invitationCode : string ,
23+ registerPage : string ,
24+ loginRedirectUrl : string ,
25+ redirectURLBase : string | undefined ,
26+ ) : NextResponse => {
27+ try {
28+ const params = new URLSearchParams ( ) ;
29+ params . set ( "invitation_code" , invitationCode ) ;
30+ params . set ( "is_invitation" , "true" ) ;
31+
32+ const registerWithInviteRedirectUrl = `${ registerPage } ?${ params . toString ( ) } ` ;
33+
34+ return NextResponse . redirect (
35+ new URL (
36+ registerWithInviteRedirectUrl ,
37+ redirectURLBase || config . redirectURL ,
38+ ) ,
39+ ) ;
40+ } catch ( error ) {
41+ if ( config . isDebugMode ) {
42+ console . error (
43+ "authMiddleware: error redirecting to register with invitation code" ,
44+ error ,
45+ ) ;
46+ }
47+ return NextResponse . redirect (
48+ new URL ( loginRedirectUrl , redirectURLBase || config . redirectURL ) ,
49+ ) ;
50+ }
51+ } ;
52+
1753const handleMiddleware = async ( req , options , onSuccess ) => {
1854 const { pathname, search } = req . nextUrl ;
1955
56+ const params = new URLSearchParams ( search ) ;
57+ const invitationCode = params . get ( "invitation_code" ) ;
58+ const hasInvitationCode = ! ! invitationCode ?. trim ( ) ;
2059 const isReturnToCurrentPage = options ?. isReturnToCurrentPage ;
2160 const orgCode : string | undefined = options ?. orgCode ;
2261 const loginPage = options ?. loginPage || `${ config . apiPath } /${ routes . login } ` ;
@@ -39,7 +78,6 @@ const handleMiddleware = async (req, options, onSuccess) => {
3978 publicPaths = options . publicPaths ;
4079 }
4180 }
42-
4381 const loginRedirectUrlParams = new URLSearchParams ( ) ;
4482
4583 if ( orgCode ) {
@@ -55,6 +93,15 @@ const handleMiddleware = async (req, options, onSuccess) => {
5593 ? `${ loginPage } ?${ queryString } `
5694 : loginPage ;
5795
96+ if ( hasInvitationCode ) {
97+ return handleInvitationCodeRedirect (
98+ invitationCode ,
99+ registerPage ,
100+ loginRedirectUrl ,
101+ options ?. redirectURLBase ,
102+ ) ;
103+ }
104+
58105 // Use extracted utility for public path matching
59106 // eslint-disable-next-line @typescript-eslint/no-var-requires
60107 const isPublicPath = isPublicPathMatch (
0 commit comments