@propelauth/nextjs 0.0.118 → 0.0.120

Sign up to get free protection for your applications and to get access to all the features.
@@ -67,8 +67,9 @@ function toLoginMethod(snake_case) {
67
67
 
68
68
  // src/user.ts
69
69
  var UserFromToken = class {
70
- constructor(userId, email, orgIdToOrgMemberInfo, firstName, lastName, username, legacyUserId, impersonatorUserId, properties, loginMethod) {
70
+ constructor(userId, email, orgIdToOrgMemberInfo, firstName, lastName, username, legacyUserId, impersonatorUserId, properties, activeOrgId, loginMethod) {
71
71
  this.userId = userId;
72
+ this.activeOrgId = activeOrgId;
72
73
  this.orgIdToOrgMemberInfo = orgIdToOrgMemberInfo;
73
74
  this.email = email;
74
75
  this.firstName = firstName;
@@ -79,6 +80,15 @@ var UserFromToken = class {
79
80
  this.properties = properties;
80
81
  this.loginMethod = loginMethod;
81
82
  }
83
+ getActiveOrg() {
84
+ if (!this.activeOrgId || !this.orgIdToOrgMemberInfo) {
85
+ return void 0;
86
+ }
87
+ return this.orgIdToOrgMemberInfo[this.activeOrgId];
88
+ }
89
+ getActiveOrgId() {
90
+ return this.activeOrgId;
91
+ }
82
92
  getOrg(orgId) {
83
93
  if (!this.orgIdToOrgMemberInfo) {
84
94
  return void 0;
@@ -123,9 +133,35 @@ var UserFromToken = class {
123
133
  obj.legacyUserId,
124
134
  obj.impersonatorUserId,
125
135
  obj.properties,
136
+ obj.activeOrgId,
126
137
  obj.loginMethod
127
138
  );
128
139
  }
140
+ static fromJwtPayload(payload) {
141
+ let activeOrgId;
142
+ let orgIdToOrgMemberInfo;
143
+ if (payload.org_member_info) {
144
+ activeOrgId = payload.org_member_info.org_id;
145
+ orgIdToOrgMemberInfo = toOrgIdToOrgMemberInfo({ [activeOrgId]: payload.org_member_info });
146
+ } else {
147
+ activeOrgId = void 0;
148
+ orgIdToOrgMemberInfo = toOrgIdToOrgMemberInfo(payload.org_id_to_org_member_info);
149
+ }
150
+ const loginMethod = toLoginMethod(payload.login_method);
151
+ return new UserFromToken(
152
+ payload.user_id,
153
+ payload.email,
154
+ orgIdToOrgMemberInfo,
155
+ payload.first_name,
156
+ payload.last_name,
157
+ payload.username,
158
+ payload.legacy_user_id,
159
+ payload.impersonatorUserId,
160
+ payload.properties,
161
+ activeOrgId,
162
+ loginMethod
163
+ );
164
+ }
129
165
  };
130
166
  var OrgMemberInfo = class {
131
167
  constructor(orgId, orgName, orgMetadata, urlSafeOrgName, userAssignedRole, userInheritedRolesPlusCurrentRole, userPermissions) {
@@ -174,18 +210,7 @@ var OrgMemberInfo = class {
174
210
  }
175
211
  };
176
212
  function toUser(snake_case) {
177
- return new UserFromToken(
178
- snake_case.user_id,
179
- snake_case.email,
180
- toOrgIdToOrgMemberInfo(snake_case.org_id_to_org_member_info),
181
- snake_case.first_name,
182
- snake_case.last_name,
183
- snake_case.username,
184
- snake_case.legacy_user_id,
185
- snake_case.impersonatorUserId,
186
- snake_case.properties,
187
- toLoginMethod(snake_case.login_method)
188
- );
213
+ return UserFromToken.fromJwtPayload(snake_case);
189
214
  }
190
215
  function toOrgIdToOrgMemberInfo(snake_case) {
191
216
  if (snake_case === void 0) {
@@ -219,6 +244,7 @@ var ACCESS_TOKEN_COOKIE_NAME = "__pa_at";
219
244
  var REFRESH_TOKEN_COOKIE_NAME = "__pa_rt";
220
245
  var STATE_COOKIE_NAME = "__pa_state";
221
246
  var CUSTOM_HEADER_FOR_ACCESS_TOKEN = "x-propelauth-access-token";
247
+ var CUSTOM_HEADER_FOR_URL = "x-propelauth-current-url";
222
248
  var RETURN_TO_PATH_COOKIE_NAME = "__pa_return_to_path";
223
249
  var COOKIE_OPTIONS = {
224
250
  httpOnly: true,
@@ -257,12 +283,17 @@ function getVerifierKey() {
257
283
  }
258
284
  return verifierKey.replace(/\\n/g, "\n");
259
285
  }
260
- function refreshTokenWithAccessAndRefreshToken(refreshToken) {
286
+ function refreshTokenWithAccessAndRefreshToken(refreshToken, activeOrgId) {
261
287
  return __async(this, null, function* () {
262
288
  const body = {
263
289
  refresh_token: refreshToken
264
290
  };
265
- const url = `${getAuthUrlOrigin()}/api/backend/v1/refresh_token`;
291
+ const queryParams = new URLSearchParams();
292
+ if (activeOrgId) {
293
+ queryParams.set("with_active_org_support", "true");
294
+ queryParams.set("active_org_id", activeOrgId);
295
+ }
296
+ const url = `${getAuthUrlOrigin()}/api/backend/v1/refresh_token?${queryParams.toString()}`;
266
297
  const response = yield fetch(url, {
267
298
  method: "POST",
268
299
  body: JSON.stringify(body),
@@ -274,10 +305,7 @@ function refreshTokenWithAccessAndRefreshToken(refreshToken) {
274
305
  if (response.ok) {
275
306
  const data = yield response.json();
276
307
  const newRefreshToken = data.refresh_token;
277
- const {
278
- access_token: accessToken,
279
- expires_at_seconds: expiresAtSeconds
280
- } = data.access_token;
308
+ const { access_token: accessToken, expires_at_seconds: expiresAtSeconds } = data.access_token;
281
309
  return {
282
310
  refreshToken: newRefreshToken,
283
311
  accessToken,
@@ -338,22 +366,24 @@ function validateAccessToken(accessToken) {
338
366
  });
339
367
  }
340
368
 
369
+ // src/shared.ts
370
+ var ACTIVE_ORG_ID_COOKIE_NAME = "__pa_org_id";
371
+
341
372
  // src/server/app-router.ts
342
- function getUserOrRedirect() {
373
+ function getUserOrRedirect(redirectOptions) {
343
374
  return __async(this, null, function* () {
344
375
  const user = yield getUser();
345
376
  if (user) {
346
377
  return user;
347
378
  } else {
348
- redirect(LOGIN_PATH);
379
+ redirectToLogin(redirectOptions);
349
380
  throw new Error("Redirecting to login");
350
381
  }
351
382
  });
352
383
  }
353
384
  function getUser() {
354
385
  return __async(this, null, function* () {
355
- var _a;
356
- const accessToken = headers().get(CUSTOM_HEADER_FOR_ACCESS_TOKEN) || ((_a = cookies().get(ACCESS_TOKEN_COOKIE_NAME)) == null ? void 0 : _a.value);
386
+ const accessToken = getAccessToken();
357
387
  if (accessToken) {
358
388
  const user = yield validateAccessTokenOrUndefined(accessToken);
359
389
  if (user) {
@@ -364,50 +394,57 @@ function getUser() {
364
394
  });
365
395
  }
366
396
  function getAccessToken() {
367
- return __async(this, null, function* () {
368
- var _a;
369
- return headers().get(CUSTOM_HEADER_FOR_ACCESS_TOKEN) || ((_a = cookies().get(ACCESS_TOKEN_COOKIE_NAME)) == null ? void 0 : _a.value);
370
- });
397
+ var _a;
398
+ return headers().get(CUSTOM_HEADER_FOR_ACCESS_TOKEN) || ((_a = cookies().get(ACCESS_TOKEN_COOKIE_NAME)) == null ? void 0 : _a.value);
371
399
  }
372
400
  function authMiddleware(req) {
373
401
  return __async(this, null, function* () {
374
- var _a, _b;
402
+ var _a, _b, _c;
375
403
  if (req.headers.has(CUSTOM_HEADER_FOR_ACCESS_TOKEN)) {
376
404
  throw new Error(`${CUSTOM_HEADER_FOR_ACCESS_TOKEN} is set which is for internal use only`);
405
+ } else if (req.headers.has(CUSTOM_HEADER_FOR_URL)) {
406
+ throw new Error(`${CUSTOM_HEADER_FOR_URL} is set which is for internal use only`);
377
407
  } else if (req.nextUrl.pathname === CALLBACK_PATH || req.nextUrl.pathname === LOGOUT_PATH || req.nextUrl.pathname === USERINFO_PATH) {
378
- return NextResponse.next();
408
+ return getNextResponse(req);
379
409
  }
380
410
  const accessToken = (_a = req.cookies.get(ACCESS_TOKEN_COOKIE_NAME)) == null ? void 0 : _a.value;
381
411
  const refreshToken = (_b = req.cookies.get(REFRESH_TOKEN_COOKIE_NAME)) == null ? void 0 : _b.value;
412
+ const activeOrgId = (_c = req.cookies.get(ACTIVE_ORG_ID_COOKIE_NAME)) == null ? void 0 : _c.value;
382
413
  if (accessToken) {
383
414
  const user = yield validateAccessTokenOrUndefined(accessToken);
384
415
  if (user) {
385
- return NextResponse.next();
416
+ return getNextResponse(req);
386
417
  }
387
418
  }
388
419
  if (refreshToken) {
389
- const response = yield refreshTokenWithAccessAndRefreshToken(refreshToken);
420
+ const response = yield refreshTokenWithAccessAndRefreshToken(refreshToken, activeOrgId);
390
421
  if (response.error === "unexpected") {
391
422
  throw new Error("Unexpected error while refreshing access token");
392
423
  } else if (response.error === "unauthorized") {
393
- const response2 = NextResponse.next();
424
+ const response2 = getNextResponse(req);
394
425
  response2.cookies.delete(ACCESS_TOKEN_COOKIE_NAME);
395
426
  response2.cookies.delete(REFRESH_TOKEN_COOKIE_NAME);
396
427
  return response2;
397
428
  } else {
398
- const headers2 = new Headers(req.headers);
399
- headers2.append(CUSTOM_HEADER_FOR_ACCESS_TOKEN, response.accessToken);
400
- const nextResponse = NextResponse.next({
401
- request: {
402
- headers: headers2
403
- }
404
- });
429
+ const nextResponse = getNextResponse(req, response.accessToken);
405
430
  nextResponse.cookies.set(ACCESS_TOKEN_COOKIE_NAME, response.accessToken, COOKIE_OPTIONS);
406
431
  nextResponse.cookies.set(REFRESH_TOKEN_COOKIE_NAME, response.refreshToken, COOKIE_OPTIONS);
407
432
  return nextResponse;
408
433
  }
409
434
  }
410
- return NextResponse.next();
435
+ return getNextResponse(req);
436
+ });
437
+ }
438
+ function getNextResponse(request, newAccessToken) {
439
+ const headers2 = new Headers(request.headers);
440
+ headers2.set(CUSTOM_HEADER_FOR_URL, request.nextUrl.toString());
441
+ if (newAccessToken) {
442
+ headers2.set(CUSTOM_HEADER_FOR_ACCESS_TOKEN, newAccessToken);
443
+ }
444
+ return NextResponse.next({
445
+ request: {
446
+ headers: headers2
447
+ }
411
448
  });
412
449
  }
413
450
  function getRouteHandlers(args) {
@@ -447,7 +484,7 @@ function getRouteHandlers(args) {
447
484
  }
448
485
  function callbackGetHandler(req) {
449
486
  return __async(this, null, function* () {
450
- var _a, _b;
487
+ var _a, _b, _c;
451
488
  const oauthState = (_a = req.cookies.get(STATE_COOKIE_NAME)) == null ? void 0 : _a.value;
452
489
  if (!oauthState || oauthState.length !== 64) {
453
490
  return new Response(null, { status: 302, headers: { Location: LOGIN_PATH } });
@@ -483,6 +520,49 @@ function getRouteHandlers(args) {
483
520
  console.error("postLoginRedirectPathFn returned undefined");
484
521
  return new Response("Unexpected error", { status: 500 });
485
522
  }
523
+ const currentActiveOrgId = (_c = req.cookies.get(ACTIVE_ORG_ID_COOKIE_NAME)) == null ? void 0 : _c.value;
524
+ const user = yield validateAccessToken(accessToken);
525
+ const isUserInCurrentActiveOrg = !!currentActiveOrgId && !!user.getOrg(currentActiveOrgId);
526
+ let activeOrgId = void 0;
527
+ if (isUserInCurrentActiveOrg) {
528
+ activeOrgId = currentActiveOrgId;
529
+ } else if (args == null ? void 0 : args.getDefaultActiveOrgId) {
530
+ activeOrgId = args.getDefaultActiveOrgId(req, user);
531
+ }
532
+ if (activeOrgId) {
533
+ const response2 = yield refreshTokenWithAccessAndRefreshToken(data.refresh_token, activeOrgId);
534
+ if (response2.error === "unexpected") {
535
+ throw new Error("Unexpected error while setting active org");
536
+ } else if (response2.error === "unauthorized") {
537
+ console.error(
538
+ "Unauthorized error while setting active org. Your user may not have access to this org"
539
+ );
540
+ return new Response("Unauthorized", { status: 401 });
541
+ } else {
542
+ const headers3 = new Headers();
543
+ headers3.append("Location", returnToPath);
544
+ headers3.append(
545
+ "Set-Cookie",
546
+ `${ACCESS_TOKEN_COOKIE_NAME}=${response2.accessToken}; Path=/; HttpOnly; Secure; SameSite=Lax`
547
+ );
548
+ headers3.append(
549
+ "Set-Cookie",
550
+ `${REFRESH_TOKEN_COOKIE_NAME}=${response2.refreshToken}; Path=/; HttpOnly; Secure; SameSite=Lax`
551
+ );
552
+ headers3.append(
553
+ "Set-Cookie",
554
+ `${ACTIVE_ORG_ID_COOKIE_NAME}=${activeOrgId}; Path=/; HttpOnly; Secure; SameSite=Lax`
555
+ );
556
+ headers3.append(
557
+ "Set-Cookie",
558
+ `${RETURN_TO_PATH_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`
559
+ );
560
+ return new Response(null, {
561
+ status: 302,
562
+ headers: headers3
563
+ });
564
+ }
565
+ }
486
566
  const headers2 = new Headers();
487
567
  headers2.append("Location", returnToPath);
488
568
  headers2.append(
@@ -493,6 +573,10 @@ function getRouteHandlers(args) {
493
573
  "Set-Cookie",
494
574
  `${REFRESH_TOKEN_COOKIE_NAME}=${data.refresh_token}; Path=/; HttpOnly; Secure; SameSite=Lax`
495
575
  );
576
+ headers2.append(
577
+ "Set-Cookie",
578
+ `${ACTIVE_ORG_ID_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`
579
+ );
496
580
  headers2.append(
497
581
  "Set-Cookie",
498
582
  `${RETURN_TO_PATH_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`
@@ -513,10 +597,11 @@ function getRouteHandlers(args) {
513
597
  }
514
598
  function userinfoGetHandler(req) {
515
599
  return __async(this, null, function* () {
516
- var _a;
600
+ var _a, _b;
517
601
  const oldRefreshToken = (_a = req.cookies.get(REFRESH_TOKEN_COOKIE_NAME)) == null ? void 0 : _a.value;
602
+ const activeOrgId = (_b = req.cookies.get(ACTIVE_ORG_ID_COOKIE_NAME)) == null ? void 0 : _b.value;
518
603
  if (oldRefreshToken) {
519
- const refreshResponse = yield refreshTokenWithAccessAndRefreshToken(oldRefreshToken);
604
+ const refreshResponse = yield refreshTokenWithAccessAndRefreshToken(oldRefreshToken, activeOrgId);
520
605
  if (refreshResponse.error === "unexpected") {
521
606
  throw new Error("Unexpected error while refreshing access token");
522
607
  } else if (refreshResponse.error === "unauthorized") {
@@ -529,6 +614,10 @@ function getRouteHandlers(args) {
529
614
  "Set-Cookie",
530
615
  `${REFRESH_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`
531
616
  );
617
+ headers3.append(
618
+ "Set-Cookie",
619
+ `${ACTIVE_ORG_ID_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`
620
+ );
532
621
  return new Response("Unauthorized", { status: 401, headers: headers3 });
533
622
  }
534
623
  const refreshToken = refreshResponse.refreshToken;
@@ -547,7 +636,8 @@ function getRouteHandlers(args) {
547
636
  const jsonResponse = {
548
637
  userinfo: data,
549
638
  accessToken,
550
- impersonatorUserId: userFromToken.impersonatorUserId
639
+ impersonatorUserId: userFromToken.impersonatorUserId,
640
+ activeOrgId
551
641
  };
552
642
  const headers3 = new Headers();
553
643
  headers3.append(
@@ -573,6 +663,10 @@ function getRouteHandlers(args) {
573
663
  "Set-Cookie",
574
664
  `${REFRESH_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`
575
665
  );
666
+ headers3.append(
667
+ "Set-Cookie",
668
+ `${ACTIVE_ORG_ID_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`
669
+ );
576
670
  return new Response(null, {
577
671
  status: 401,
578
672
  headers: headers3
@@ -584,12 +678,13 @@ function getRouteHandlers(args) {
584
678
  const headers2 = new Headers();
585
679
  headers2.append("Set-Cookie", `${ACCESS_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`);
586
680
  headers2.append("Set-Cookie", `${REFRESH_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`);
681
+ headers2.append("Set-Cookie", `${ACTIVE_ORG_ID_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`);
587
682
  return new Response(null, { status: 401 });
588
683
  });
589
684
  }
590
685
  function logoutGetHandler(req) {
591
686
  return __async(this, null, function* () {
592
- var _a;
687
+ var _a, _b;
593
688
  const path = (args == null ? void 0 : args.postLoginRedirectPathFn) ? args.postLoginRedirectPathFn(req) : "/";
594
689
  if (!path) {
595
690
  console.error("postLoginPathFn returned undefined");
@@ -607,12 +702,17 @@ function getRouteHandlers(args) {
607
702
  "Set-Cookie",
608
703
  `${REFRESH_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`
609
704
  );
705
+ headers2.append(
706
+ "Set-Cookie",
707
+ `${ACTIVE_ORG_ID_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`
708
+ );
610
709
  return new Response(null, {
611
710
  status: 302,
612
711
  headers: headers2
613
712
  });
614
713
  }
615
- const refreshResponse = yield refreshTokenWithAccessAndRefreshToken(refreshToken);
714
+ const activeOrgId = (_b = req.cookies.get(ACTIVE_ORG_ID_COOKIE_NAME)) == null ? void 0 : _b.value;
715
+ const refreshResponse = yield refreshTokenWithAccessAndRefreshToken(refreshToken, activeOrgId);
616
716
  if (refreshResponse.error === "unexpected") {
617
717
  console.error("Unexpected error while refreshing access token");
618
718
  return new Response("Unexpected error", { status: 500 });
@@ -627,6 +727,10 @@ function getRouteHandlers(args) {
627
727
  "Set-Cookie",
628
728
  `${REFRESH_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`
629
729
  );
730
+ headers2.append(
731
+ "Set-Cookie",
732
+ `${ACTIVE_ORG_ID_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`
733
+ );
630
734
  return new Response(null, {
631
735
  status: 302,
632
736
  headers: headers2
@@ -655,6 +759,10 @@ function getRouteHandlers(args) {
655
759
  "Set-Cookie",
656
760
  `${REFRESH_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`
657
761
  );
762
+ headers3.append(
763
+ "Set-Cookie",
764
+ `${ACTIVE_ORG_ID_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`
765
+ );
658
766
  return new Response(null, { status: 200, headers: headers3 });
659
767
  }
660
768
  const authUrlOrigin = getAuthUrlOrigin();
@@ -679,9 +787,78 @@ function getRouteHandlers(args) {
679
787
  const headers2 = new Headers();
680
788
  headers2.append("Set-Cookie", `${ACCESS_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`);
681
789
  headers2.append("Set-Cookie", `${REFRESH_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`);
790
+ headers2.append("Set-Cookie", `${ACTIVE_ORG_ID_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`);
682
791
  return new Response(null, { status: 200, headers: headers2 });
683
792
  });
684
793
  }
794
+ function setActiveOrgHandler(req) {
795
+ return __async(this, null, function* () {
796
+ var _a;
797
+ const oldRefreshToken = (_a = req.cookies.get(REFRESH_TOKEN_COOKIE_NAME)) == null ? void 0 : _a.value;
798
+ const activeOrgId = req.nextUrl.searchParams.get("active_org_id");
799
+ if (!oldRefreshToken) {
800
+ const headers2 = new Headers();
801
+ headers2.append(
802
+ "Set-Cookie",
803
+ `${ACTIVE_ORG_ID_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`
804
+ );
805
+ return new Response(null, { status: 401, headers: headers2 });
806
+ }
807
+ if (!activeOrgId) {
808
+ return new Response(null, { status: 400 });
809
+ }
810
+ const refreshResponse = yield refreshTokenWithAccessAndRefreshToken(oldRefreshToken, activeOrgId);
811
+ if (refreshResponse.error === "unexpected") {
812
+ throw new Error("Unexpected error while setting active org id");
813
+ } else if (refreshResponse.error === "unauthorized") {
814
+ return new Response("Unauthorized", { status: 401 });
815
+ }
816
+ const refreshToken = refreshResponse.refreshToken;
817
+ const accessToken = refreshResponse.accessToken;
818
+ const authUrlOrigin = getAuthUrlOrigin();
819
+ const path = `${authUrlOrigin}/propelauth/oauth/userinfo`;
820
+ const response = yield fetch(path, {
821
+ headers: {
822
+ "Content-Type": "application/json",
823
+ Authorization: "Bearer " + accessToken
824
+ }
825
+ });
826
+ if (response.ok) {
827
+ const userFromToken = yield validateAccessToken(accessToken);
828
+ const data = yield response.json();
829
+ const jsonResponse = {
830
+ userinfo: data,
831
+ accessToken,
832
+ impersonatorUserId: userFromToken.impersonatorUserId,
833
+ activeOrgId
834
+ };
835
+ const headers2 = new Headers();
836
+ headers2.append(
837
+ "Set-Cookie",
838
+ `${ACCESS_TOKEN_COOKIE_NAME}=${accessToken}; Path=/; HttpOnly; Secure; SameSite=Lax`
839
+ );
840
+ headers2.append(
841
+ "Set-Cookie",
842
+ `${REFRESH_TOKEN_COOKIE_NAME}=${refreshToken}; Path=/; HttpOnly; Secure; SameSite=Lax`
843
+ );
844
+ headers2.append(
845
+ "Set-Cookie",
846
+ `${ACTIVE_ORG_ID_COOKIE_NAME}=${activeOrgId}; Path=/; HttpOnly; Secure; SameSite=Lax`
847
+ );
848
+ headers2.append("Content-Type", "application/json");
849
+ return new Response(JSON.stringify(jsonResponse), {
850
+ status: 200,
851
+ headers: headers2
852
+ });
853
+ } else if (response.status === 401) {
854
+ return new Response(null, {
855
+ status: 401
856
+ });
857
+ } else {
858
+ return new Response(null, { status: 500 });
859
+ }
860
+ });
861
+ }
685
862
  function getRouteHandler(req, { params }) {
686
863
  if (params.slug === "login") {
687
864
  return loginGetHandler(req);
@@ -700,6 +877,8 @@ function getRouteHandlers(args) {
700
877
  function postRouteHandler(req, { params }) {
701
878
  if (params.slug === "logout") {
702
879
  return logoutPostHandler(req);
880
+ } else if (params.slug === "set-active-org") {
881
+ return setActiveOrgHandler(req);
703
882
  } else {
704
883
  return new Response("", { status: 404 });
705
884
  }
@@ -713,11 +892,51 @@ function randomState() {
713
892
  const randomBytes = crypto.getRandomValues(new Uint8Array(32));
714
893
  return Array.from(randomBytes).map((b) => b.toString(16).padStart(2, "0")).join("");
715
894
  }
895
+ function redirectToLogin(redirectOptions) {
896
+ if (!redirectOptions) {
897
+ redirect(LOGIN_PATH);
898
+ } else if (redirectOptions.returnToPath) {
899
+ const loginPath = LOGIN_PATH + "?return_to_path=" + encodeURI(redirectOptions.returnToPath);
900
+ redirect(loginPath);
901
+ } else if (redirectOptions.returnToCurrentPath) {
902
+ const encodedPath = getUrlEncodedRedirectPathForCurrentUrl();
903
+ if (encodedPath) {
904
+ const loginPath = LOGIN_PATH + "?return_to_path=" + encodedPath;
905
+ redirect(loginPath);
906
+ } else {
907
+ console.warn("Could not get current URL to redirect to");
908
+ redirect(LOGIN_PATH);
909
+ }
910
+ }
911
+ }
912
+ function getUrlEncodedRedirectPathForCurrentUrl() {
913
+ const url = getCurrentUrl();
914
+ if (!url) {
915
+ return void 0;
916
+ }
917
+ try {
918
+ const urlObj = new URL(url);
919
+ return encodeURIComponent(urlObj.pathname + urlObj.search);
920
+ } catch (e) {
921
+ console.warn("Current URL is not a valid URL");
922
+ return void 0;
923
+ }
924
+ }
925
+ function getCurrentUrl() {
926
+ const url = headers().get(CUSTOM_HEADER_FOR_URL);
927
+ if (!url) {
928
+ console.warn("Attempting to redirect to the current URL, but we could not find the current URL in the headers. Is the middleware set up?");
929
+ return void 0;
930
+ } else {
931
+ return url;
932
+ }
933
+ }
716
934
  export {
717
935
  ConfigurationException,
718
936
  UnauthorizedException,
719
937
  authMiddleware,
720
938
  getAccessToken,
939
+ getCurrentUrl,
721
940
  getRouteHandlers,
722
941
  getUser,
723
942
  getUserOrRedirect