1
1
import { kindeAuthClient } from '$lib/KindeSDK.js' ;
2
2
import { kindeConfiguration } from '$lib/index.js' ;
3
+ import { sessionStorage } from '$lib/sessionStorage/sessionStorage.js' ;
3
4
import { parseSearchParamsToObject } from '$lib/utils/index.js' ;
4
5
import type { SessionManager } from '@kinde-oss/kinde-typescript-sdk' ;
5
6
import { error , redirect , type RequestEvent } from '@sveltejs/kit' ;
6
7
import { version } from '$app/environment' ;
7
8
9
+ const KEY_POST_LOGIN_REDIRECT_URL = 'post-login-redirect-url' ;
10
+
8
11
export async function handleAuth ( {
9
12
request,
10
13
params,
@@ -14,6 +17,7 @@ export async function handleAuth({
14
17
let url : URL | null = null ;
15
18
switch ( params . kindeAuth ) {
16
19
case 'login' :
20
+ storePostLoginRedirectUrl ( options ) ;
17
21
url = await kindeAuthClient . login ( request as unknown as SessionManager , options ) ;
18
22
break ;
19
23
case 'health' :
@@ -43,6 +47,7 @@ export async function handleAuth({
43
47
}
44
48
) ;
45
49
case 'register' :
50
+ storePostLoginRedirectUrl ( options ) ;
46
51
url = await kindeAuthClient . register ( request as unknown as SessionManager , options ) ;
47
52
break ;
48
53
case 'create_org' :
@@ -53,6 +58,7 @@ export async function handleAuth({
53
58
request as unknown as SessionManager ,
54
59
new URL ( request . url )
55
60
) ;
61
+ redirectToPostLoginUrl ( ) ;
56
62
throw redirect ( 302 , kindeConfiguration . loginRedirectURL ?? '/' ) ;
57
63
case 'logout' :
58
64
url = await kindeAuthClient . logout ( request as unknown as SessionManager ) ;
@@ -62,3 +68,25 @@ export async function handleAuth({
62
68
}
63
69
throw redirect ( 302 , url . toString ( ) ) ;
64
70
}
71
+
72
+ const storePostLoginRedirectUrl = ( options : Record < string , string | number > ) => {
73
+ if ( options . post_login_redirect_url && typeof options . post_login_redirect_url == 'string' ) {
74
+ sessionStorage . setSessionItem ( KEY_POST_LOGIN_REDIRECT_URL , options . post_login_redirect_url ) ;
75
+ }
76
+ } ;
77
+
78
+ const isAbsoluteUrl = ( url : string ) =>
79
+ url . indexOf ( 'http://' ) === 0 || url . indexOf ( 'https://' ) === 0 ;
80
+
81
+ const redirectToPostLoginUrl = ( ) => {
82
+ if ( sessionStorage . getSessionItem ( KEY_POST_LOGIN_REDIRECT_URL ) ) {
83
+ const post_login_redirect_url = sessionStorage . getSessionItem ( KEY_POST_LOGIN_REDIRECT_URL ) ;
84
+ sessionStorage . removeSessionItem ( KEY_POST_LOGIN_REDIRECT_URL ) ;
85
+
86
+ if ( isAbsoluteUrl ( post_login_redirect_url ) ) {
87
+ throw redirect ( 302 , new URL ( post_login_redirect_url ) ) ;
88
+ } else {
89
+ throw redirect ( 302 , new URL ( post_login_redirect_url , kindeConfiguration . appBase ) ) ;
90
+ }
91
+ }
92
+ } ;
0 commit comments