@propelauth/nextjs 0.0.110 → 0.0.112-beta.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -42,8 +42,9 @@ import { NextResponse } from "next/server.js";
42
42
 
43
43
  // src/user.ts
44
44
  var UserFromToken = class {
45
- constructor(userId, email, orgIdToOrgMemberInfo, firstName, lastName, username, legacyUserId, impersonatorUserId, properties) {
45
+ constructor(userId, email, orgIdToOrgMemberInfo, firstName, lastName, username, legacyUserId, impersonatorUserId, properties, activeOrgId) {
46
46
  this.userId = userId;
47
+ this.activeOrgId = activeOrgId;
47
48
  this.orgIdToOrgMemberInfo = orgIdToOrgMemberInfo;
48
49
  this.email = email;
49
50
  this.firstName = firstName;
@@ -53,6 +54,15 @@ var UserFromToken = class {
53
54
  this.impersonatorUserId = impersonatorUserId;
54
55
  this.properties = properties;
55
56
  }
57
+ getActiveOrg() {
58
+ if (!this.activeOrgId || !this.orgIdToOrgMemberInfo) {
59
+ return void 0;
60
+ }
61
+ return this.orgIdToOrgMemberInfo[this.activeOrgId];
62
+ }
63
+ getActiveOrgId() {
64
+ return this.activeOrgId;
65
+ }
56
66
  getOrg(orgId) {
57
67
  if (!this.orgIdToOrgMemberInfo) {
58
68
  return void 0;
@@ -85,9 +95,7 @@ var UserFromToken = class {
85
95
  const obj = JSON.parse(json);
86
96
  const orgIdToOrgMemberInfo = {};
87
97
  for (const orgId in obj.orgIdToOrgMemberInfo) {
88
- orgIdToOrgMemberInfo[orgId] = OrgMemberInfo.fromJSON(
89
- JSON.stringify(obj.orgIdToOrgMemberInfo[orgId])
90
- );
98
+ orgIdToOrgMemberInfo[orgId] = OrgMemberInfo.fromJSON(JSON.stringify(obj.orgIdToOrgMemberInfo[orgId]));
91
99
  }
92
100
  return new UserFromToken(
93
101
  obj.userId,
@@ -101,6 +109,29 @@ var UserFromToken = class {
101
109
  obj.properties
102
110
  );
103
111
  }
112
+ static fromJwtPayload(payload) {
113
+ let activeOrgId;
114
+ let orgIdToOrgMemberInfo;
115
+ if (payload.org_member_info) {
116
+ activeOrgId = payload.org_member_info.org_id;
117
+ orgIdToOrgMemberInfo = toOrgIdToOrgMemberInfo({ [activeOrgId]: payload.org_member_info });
118
+ } else {
119
+ activeOrgId = void 0;
120
+ orgIdToOrgMemberInfo = toOrgIdToOrgMemberInfo(payload.org_id_to_org_member_info);
121
+ }
122
+ return new UserFromToken(
123
+ payload.user_id,
124
+ payload.email,
125
+ orgIdToOrgMemberInfo,
126
+ payload.first_name,
127
+ payload.last_name,
128
+ payload.username,
129
+ payload.legacy_user_id,
130
+ payload.impersonatorUserId,
131
+ payload.properties,
132
+ activeOrgId
133
+ );
134
+ }
104
135
  };
105
136
  var OrgMemberInfo = class {
106
137
  constructor(orgId, orgName, orgMetadata, urlSafeOrgName, userAssignedRole, userInheritedRolesPlusCurrentRole, userPermissions) {
@@ -149,17 +180,7 @@ var OrgMemberInfo = class {
149
180
  }
150
181
  };
151
182
  function toUser(snake_case) {
152
- return new UserFromToken(
153
- snake_case.user_id,
154
- snake_case.email,
155
- toOrgIdToOrgMemberInfo(snake_case.org_id_to_org_member_info),
156
- snake_case.first_name,
157
- snake_case.last_name,
158
- snake_case.username,
159
- snake_case.legacy_user_id,
160
- snake_case.impersonatorUserId,
161
- snake_case.properties
162
- );
183
+ return UserFromToken.fromJwtPayload(snake_case);
163
184
  }
164
185
  function toOrgIdToOrgMemberInfo(snake_case) {
165
186
  if (snake_case === void 0) {
@@ -231,12 +252,17 @@ function getVerifierKey() {
231
252
  }
232
253
  return verifierKey.replace(/\\n/g, "\n");
233
254
  }
234
- function refreshTokenWithAccessAndRefreshToken(refreshToken) {
255
+ function refreshTokenWithAccessAndRefreshToken(refreshToken, activeOrgId) {
235
256
  return __async(this, null, function* () {
236
257
  const body = {
237
258
  refresh_token: refreshToken
238
259
  };
239
- const url = `${getAuthUrlOrigin()}/api/backend/v1/refresh_token`;
260
+ const queryParams = new URLSearchParams();
261
+ if (activeOrgId) {
262
+ queryParams.set("with_active_org_support", "true");
263
+ queryParams.set("active_org_id", activeOrgId);
264
+ }
265
+ const url = `${getAuthUrlOrigin()}/api/backend/v1/refresh_token?${queryParams.toString()}`;
240
266
  const response = yield fetch(url, {
241
267
  method: "POST",
242
268
  body: JSON.stringify(body),
@@ -248,10 +274,7 @@ function refreshTokenWithAccessAndRefreshToken(refreshToken) {
248
274
  if (response.ok) {
249
275
  const data = yield response.json();
250
276
  const newRefreshToken = data.refresh_token;
251
- const {
252
- access_token: accessToken,
253
- expires_at_seconds: expiresAtSeconds
254
- } = data.access_token;
277
+ const { access_token: accessToken, expires_at_seconds: expiresAtSeconds } = data.access_token;
255
278
  return {
256
279
  refreshToken: newRefreshToken,
257
280
  accessToken,
@@ -312,6 +335,9 @@ function validateAccessToken(accessToken) {
312
335
  });
313
336
  }
314
337
 
338
+ // src/shared.ts
339
+ var ACTIVE_ORG_ID_COOKIE_NAME = "__pa_org_id";
340
+
315
341
  // src/server/app-router.ts
316
342
  function getUserOrRedirect() {
317
343
  return __async(this, null, function* () {
@@ -326,8 +352,7 @@ function getUserOrRedirect() {
326
352
  }
327
353
  function getUser() {
328
354
  return __async(this, null, function* () {
329
- var _a;
330
- const accessToken = headers().get(CUSTOM_HEADER_FOR_ACCESS_TOKEN) || ((_a = cookies().get(ACCESS_TOKEN_COOKIE_NAME)) == null ? void 0 : _a.value);
355
+ const accessToken = getAccessToken();
331
356
  if (accessToken) {
332
357
  const user = yield validateAccessTokenOrUndefined(accessToken);
333
358
  if (user) {
@@ -338,14 +363,12 @@ function getUser() {
338
363
  });
339
364
  }
340
365
  function getAccessToken() {
341
- return __async(this, null, function* () {
342
- var _a;
343
- return headers().get(CUSTOM_HEADER_FOR_ACCESS_TOKEN) || ((_a = cookies().get(ACCESS_TOKEN_COOKIE_NAME)) == null ? void 0 : _a.value);
344
- });
366
+ var _a;
367
+ return headers().get(CUSTOM_HEADER_FOR_ACCESS_TOKEN) || ((_a = cookies().get(ACCESS_TOKEN_COOKIE_NAME)) == null ? void 0 : _a.value);
345
368
  }
346
369
  function authMiddleware(req) {
347
370
  return __async(this, null, function* () {
348
- var _a, _b;
371
+ var _a, _b, _c;
349
372
  if (req.headers.has(CUSTOM_HEADER_FOR_ACCESS_TOKEN)) {
350
373
  throw new Error(`${CUSTOM_HEADER_FOR_ACCESS_TOKEN} is set which is for internal use only`);
351
374
  } else if (req.nextUrl.pathname === CALLBACK_PATH || req.nextUrl.pathname === LOGOUT_PATH || req.nextUrl.pathname === USERINFO_PATH) {
@@ -353,6 +376,7 @@ function authMiddleware(req) {
353
376
  }
354
377
  const accessToken = (_a = req.cookies.get(ACCESS_TOKEN_COOKIE_NAME)) == null ? void 0 : _a.value;
355
378
  const refreshToken = (_b = req.cookies.get(REFRESH_TOKEN_COOKIE_NAME)) == null ? void 0 : _b.value;
379
+ const activeOrgId = (_c = req.cookies.get(ACTIVE_ORG_ID_COOKIE_NAME)) == null ? void 0 : _c.value;
356
380
  if (accessToken) {
357
381
  const user = yield validateAccessTokenOrUndefined(accessToken);
358
382
  if (user) {
@@ -360,7 +384,7 @@ function authMiddleware(req) {
360
384
  }
361
385
  }
362
386
  if (refreshToken) {
363
- const response = yield refreshTokenWithAccessAndRefreshToken(refreshToken);
387
+ const response = yield refreshTokenWithAccessAndRefreshToken(refreshToken, activeOrgId);
364
388
  if (response.error === "unexpected") {
365
389
  throw new Error("Unexpected error while refreshing access token");
366
390
  } else if (response.error === "unauthorized") {
@@ -385,9 +409,6 @@ function authMiddleware(req) {
385
409
  });
386
410
  }
387
411
  function getRouteHandlers(args) {
388
- const authUrlOrigin = getAuthUrlOrigin();
389
- const redirectUri = getRedirectUri();
390
- const integrationApiKey = getIntegrationApiKey();
391
412
  function loginGetHandler(req) {
392
413
  return signupOrLoginHandler(req, false);
393
414
  }
@@ -397,6 +418,7 @@ function getRouteHandlers(args) {
397
418
  function signupOrLoginHandler(req, isSignup) {
398
419
  const returnToPath = req.nextUrl.searchParams.get("return_to_path");
399
420
  const state = randomState();
421
+ const redirectUri = getRedirectUri();
400
422
  const authorizeUrlSearchParams = new URLSearchParams({
401
423
  redirect_uri: redirectUri,
402
424
  state,
@@ -408,7 +430,10 @@ function getRouteHandlers(args) {
408
430
  headers2.append("Set-Cookie", `${STATE_COOKIE_NAME}=${state}; Path=/; HttpOnly; Secure; SameSite=Lax`);
409
431
  if (returnToPath) {
410
432
  if (returnToPath.startsWith("/")) {
411
- headers2.append("Set-Cookie", `${RETURN_TO_PATH_COOKIE_NAME}=${returnToPath}; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=600`);
433
+ headers2.append(
434
+ "Set-Cookie",
435
+ `${RETURN_TO_PATH_COOKIE_NAME}=${returnToPath}; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=600`
436
+ );
412
437
  } else {
413
438
  console.warn("return_to_path must start with /");
414
439
  }
@@ -420,7 +445,7 @@ function getRouteHandlers(args) {
420
445
  }
421
446
  function callbackGetHandler(req) {
422
447
  return __async(this, null, function* () {
423
- var _a, _b;
448
+ var _a, _b, _c;
424
449
  const oauthState = (_a = req.cookies.get(STATE_COOKIE_NAME)) == null ? void 0 : _a.value;
425
450
  if (!oauthState || oauthState.length !== 64) {
426
451
  return new Response(null, { status: 302, headers: { Location: LOGIN_PATH } });
@@ -431,6 +456,9 @@ function getRouteHandlers(args) {
431
456
  if (state !== oauthState) {
432
457
  return new Response(null, { status: 302, headers: { Location: LOGIN_PATH } });
433
458
  }
459
+ const authUrlOrigin = getAuthUrlOrigin();
460
+ const redirectUri = getRedirectUri();
461
+ const integrationApiKey = getIntegrationApiKey();
434
462
  const oauth_token_body = {
435
463
  redirect_uri: redirectUri,
436
464
  code
@@ -453,17 +481,75 @@ function getRouteHandlers(args) {
453
481
  console.error("postLoginRedirectPathFn returned undefined");
454
482
  return new Response("Unexpected error", { status: 500 });
455
483
  }
484
+ const currentActiveOrgId = (_c = req.cookies.get(ACTIVE_ORG_ID_COOKIE_NAME)) == null ? void 0 : _c.value;
485
+ const user = yield validateAccessToken(accessToken);
486
+ const isUserInCurrentActiveOrg = !!currentActiveOrgId && !!user.getOrg(currentActiveOrgId);
487
+ let activeOrgId = void 0;
488
+ if (isUserInCurrentActiveOrg) {
489
+ activeOrgId = currentActiveOrgId;
490
+ } else if (args == null ? void 0 : args.getDefaultActiveOrgId) {
491
+ activeOrgId = args.getDefaultActiveOrgId(user);
492
+ }
493
+ if (activeOrgId) {
494
+ const response2 = yield refreshTokenWithAccessAndRefreshToken(data.refresh_token, activeOrgId);
495
+ if (response2.error === "unexpected") {
496
+ throw new Error("Unexpected error while setting active org");
497
+ } else if (response2.error === "unauthorized") {
498
+ console.error(
499
+ "Unauthorized error while setting active org. Your user may not have access to this org"
500
+ );
501
+ return new Response("Unauthorized", { status: 401 });
502
+ } else {
503
+ const headers3 = new Headers();
504
+ headers3.append("Location", returnToPath);
505
+ headers3.append(
506
+ "Set-Cookie",
507
+ `${ACCESS_TOKEN_COOKIE_NAME}=${response2.accessToken}; Path=/; HttpOnly; Secure; SameSite=Lax`
508
+ );
509
+ headers3.append(
510
+ "Set-Cookie",
511
+ `${REFRESH_TOKEN_COOKIE_NAME}=${response2.refreshToken}; Path=/; HttpOnly; Secure; SameSite=Lax`
512
+ );
513
+ headers3.append(
514
+ "Set-Cookie",
515
+ `${ACTIVE_ORG_ID_COOKIE_NAME}=${activeOrgId}; Path=/; HttpOnly; Secure; SameSite=Lax`
516
+ );
517
+ headers3.append(
518
+ "Set-Cookie",
519
+ `${RETURN_TO_PATH_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`
520
+ );
521
+ return new Response(null, {
522
+ status: 302,
523
+ headers: headers3
524
+ });
525
+ }
526
+ }
456
527
  const headers2 = new Headers();
457
528
  headers2.append("Location", returnToPath);
458
- headers2.append("Set-Cookie", `${ACCESS_TOKEN_COOKIE_NAME}=${accessToken}; Path=/; HttpOnly; Secure; SameSite=Lax`);
459
- headers2.append("Set-Cookie", `${REFRESH_TOKEN_COOKIE_NAME}=${data.refresh_token}; Path=/; HttpOnly; Secure; SameSite=Lax`);
460
- headers2.append("Set-Cookie", `${RETURN_TO_PATH_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`);
529
+ headers2.append(
530
+ "Set-Cookie",
531
+ `${ACCESS_TOKEN_COOKIE_NAME}=${accessToken}; Path=/; HttpOnly; Secure; SameSite=Lax`
532
+ );
533
+ headers2.append(
534
+ "Set-Cookie",
535
+ `${REFRESH_TOKEN_COOKIE_NAME}=${data.refresh_token}; Path=/; HttpOnly; Secure; SameSite=Lax`
536
+ );
537
+ headers2.append(
538
+ "Set-Cookie",
539
+ `${ACTIVE_ORG_ID_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`
540
+ );
541
+ headers2.append(
542
+ "Set-Cookie",
543
+ `${RETURN_TO_PATH_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`
544
+ );
461
545
  return new Response(null, {
462
546
  status: 302,
463
547
  headers: headers2
464
548
  });
465
549
  } else if (response.status === 401) {
466
- console.error("Couldn't finish the login process for this user. This is most likely caused by an incorrect PROPELAUTH_API_KEY.");
550
+ console.error(
551
+ "Couldn't finish the login process for this user. This is most likely caused by an incorrect PROPELAUTH_API_KEY."
552
+ );
467
553
  return new Response("Unexpected error", { status: 500 });
468
554
  } else {
469
555
  return new Response("Unexpected error", { status: 500 });
@@ -472,25 +558,37 @@ function getRouteHandlers(args) {
472
558
  }
473
559
  function userinfoGetHandler(req) {
474
560
  return __async(this, null, function* () {
475
- var _a;
561
+ var _a, _b;
476
562
  const oldRefreshToken = (_a = req.cookies.get(REFRESH_TOKEN_COOKIE_NAME)) == null ? void 0 : _a.value;
563
+ const activeOrgId = (_b = req.cookies.get(ACTIVE_ORG_ID_COOKIE_NAME)) == null ? void 0 : _b.value;
477
564
  if (oldRefreshToken) {
478
- const refreshResponse = yield refreshTokenWithAccessAndRefreshToken(oldRefreshToken);
565
+ const refreshResponse = yield refreshTokenWithAccessAndRefreshToken(oldRefreshToken, activeOrgId);
479
566
  if (refreshResponse.error === "unexpected") {
480
567
  throw new Error("Unexpected error while refreshing access token");
481
568
  } else if (refreshResponse.error === "unauthorized") {
482
569
  const headers3 = new Headers();
483
- headers3.append("Set-Cookie", `${ACCESS_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`);
484
- headers3.append("Set-Cookie", `${REFRESH_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`);
570
+ headers3.append(
571
+ "Set-Cookie",
572
+ `${ACCESS_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`
573
+ );
574
+ headers3.append(
575
+ "Set-Cookie",
576
+ `${REFRESH_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`
577
+ );
578
+ headers3.append(
579
+ "Set-Cookie",
580
+ `${ACTIVE_ORG_ID_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`
581
+ );
485
582
  return new Response("Unauthorized", { status: 401, headers: headers3 });
486
583
  }
487
584
  const refreshToken = refreshResponse.refreshToken;
488
585
  const accessToken = refreshResponse.accessToken;
586
+ const authUrlOrigin = getAuthUrlOrigin();
489
587
  const path = `${authUrlOrigin}/propelauth/oauth/userinfo`;
490
588
  const response = yield fetch(path, {
491
589
  headers: {
492
590
  "Content-Type": "application/json",
493
- "Authorization": "Bearer " + accessToken
591
+ Authorization: "Bearer " + accessToken
494
592
  }
495
593
  });
496
594
  if (response.ok) {
@@ -499,11 +597,18 @@ function getRouteHandlers(args) {
499
597
  const jsonResponse = {
500
598
  userinfo: data,
501
599
  accessToken,
502
- impersonatorUserId: userFromToken.impersonatorUserId
600
+ impersonatorUserId: userFromToken.impersonatorUserId,
601
+ activeOrgId
503
602
  };
504
603
  const headers3 = new Headers();
505
- headers3.append("Set-Cookie", `${ACCESS_TOKEN_COOKIE_NAME}=${accessToken}; Path=/; HttpOnly; Secure; SameSite=Lax`);
506
- headers3.append("Set-Cookie", `${REFRESH_TOKEN_COOKIE_NAME}=${refreshToken}; Path=/; HttpOnly; Secure; SameSite=Lax`);
604
+ headers3.append(
605
+ "Set-Cookie",
606
+ `${ACCESS_TOKEN_COOKIE_NAME}=${accessToken}; Path=/; HttpOnly; Secure; SameSite=Lax`
607
+ );
608
+ headers3.append(
609
+ "Set-Cookie",
610
+ `${REFRESH_TOKEN_COOKIE_NAME}=${refreshToken}; Path=/; HttpOnly; Secure; SameSite=Lax`
611
+ );
507
612
  headers3.append("Content-Type", "application/json");
508
613
  return new Response(JSON.stringify(jsonResponse), {
509
614
  status: 200,
@@ -511,8 +616,18 @@ function getRouteHandlers(args) {
511
616
  });
512
617
  } else if (response.status === 401) {
513
618
  const headers3 = new Headers();
514
- headers3.append("Set-Cookie", `${ACCESS_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`);
515
- headers3.append("Set-Cookie", `${REFRESH_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`);
619
+ headers3.append(
620
+ "Set-Cookie",
621
+ `${ACCESS_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`
622
+ );
623
+ headers3.append(
624
+ "Set-Cookie",
625
+ `${REFRESH_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`
626
+ );
627
+ headers3.append(
628
+ "Set-Cookie",
629
+ `${ACTIVE_ORG_ID_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`
630
+ );
516
631
  return new Response(null, {
517
632
  status: 401,
518
633
  headers: headers3
@@ -524,12 +639,13 @@ function getRouteHandlers(args) {
524
639
  const headers2 = new Headers();
525
640
  headers2.append("Set-Cookie", `${ACCESS_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`);
526
641
  headers2.append("Set-Cookie", `${REFRESH_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`);
642
+ headers2.append("Set-Cookie", `${ACTIVE_ORG_ID_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`);
527
643
  return new Response(null, { status: 401 });
528
644
  });
529
645
  }
530
646
  function logoutGetHandler(req) {
531
647
  return __async(this, null, function* () {
532
- var _a;
648
+ var _a, _b;
533
649
  const path = (args == null ? void 0 : args.postLoginRedirectPathFn) ? args.postLoginRedirectPathFn(req) : "/";
534
650
  if (!path) {
535
651
  console.error("postLoginPathFn returned undefined");
@@ -539,22 +655,43 @@ function getRouteHandlers(args) {
539
655
  if (!refreshToken) {
540
656
  const headers2 = new Headers();
541
657
  headers2.append("Location", path);
542
- headers2.append("Set-Cookie", `${ACCESS_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`);
543
- headers2.append("Set-Cookie", `${REFRESH_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`);
658
+ headers2.append(
659
+ "Set-Cookie",
660
+ `${ACCESS_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`
661
+ );
662
+ headers2.append(
663
+ "Set-Cookie",
664
+ `${REFRESH_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`
665
+ );
666
+ headers2.append(
667
+ "Set-Cookie",
668
+ `${ACTIVE_ORG_ID_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`
669
+ );
544
670
  return new Response(null, {
545
671
  status: 302,
546
672
  headers: headers2
547
673
  });
548
674
  }
549
- const refreshResponse = yield refreshTokenWithAccessAndRefreshToken(refreshToken);
675
+ const activeOrgId = (_b = req.cookies.get(ACTIVE_ORG_ID_COOKIE_NAME)) == null ? void 0 : _b.value;
676
+ const refreshResponse = yield refreshTokenWithAccessAndRefreshToken(refreshToken, activeOrgId);
550
677
  if (refreshResponse.error === "unexpected") {
551
678
  console.error("Unexpected error while refreshing access token");
552
679
  return new Response("Unexpected error", { status: 500 });
553
680
  } else if (refreshResponse.error === "unauthorized") {
554
681
  const headers2 = new Headers();
555
682
  headers2.append("Location", path);
556
- headers2.append("Set-Cookie", `${ACCESS_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`);
557
- headers2.append("Set-Cookie", `${REFRESH_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`);
683
+ headers2.append(
684
+ "Set-Cookie",
685
+ `${ACCESS_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`
686
+ );
687
+ headers2.append(
688
+ "Set-Cookie",
689
+ `${REFRESH_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`
690
+ );
691
+ headers2.append(
692
+ "Set-Cookie",
693
+ `${ACTIVE_ORG_ID_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`
694
+ );
558
695
  return new Response(null, {
559
696
  status: 302,
560
697
  headers: headers2
@@ -575,10 +712,22 @@ function getRouteHandlers(args) {
575
712
  const refreshToken = (_a = req.cookies.get(REFRESH_TOKEN_COOKIE_NAME)) == null ? void 0 : _a.value;
576
713
  if (!refreshToken) {
577
714
  const headers3 = new Headers();
578
- headers3.append("Set-Cookie", `${ACCESS_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`);
579
- headers3.append("Set-Cookie", `${REFRESH_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`);
715
+ headers3.append(
716
+ "Set-Cookie",
717
+ `${ACCESS_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`
718
+ );
719
+ headers3.append(
720
+ "Set-Cookie",
721
+ `${REFRESH_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`
722
+ );
723
+ headers3.append(
724
+ "Set-Cookie",
725
+ `${ACTIVE_ORG_ID_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`
726
+ );
580
727
  return new Response(null, { status: 200, headers: headers3 });
581
728
  }
729
+ const authUrlOrigin = getAuthUrlOrigin();
730
+ const integrationApiKey = getIntegrationApiKey();
582
731
  const logoutBody = { refresh_token: refreshToken };
583
732
  const url = `${authUrlOrigin}/api/backend/v1/logout`;
584
733
  const response = yield fetch(url, {
@@ -599,9 +748,78 @@ function getRouteHandlers(args) {
599
748
  const headers2 = new Headers();
600
749
  headers2.append("Set-Cookie", `${ACCESS_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`);
601
750
  headers2.append("Set-Cookie", `${REFRESH_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`);
751
+ headers2.append("Set-Cookie", `${ACTIVE_ORG_ID_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`);
602
752
  return new Response(null, { status: 200, headers: headers2 });
603
753
  });
604
754
  }
755
+ function setActiveOrgHandler(req) {
756
+ return __async(this, null, function* () {
757
+ var _a;
758
+ const oldRefreshToken = (_a = req.cookies.get(REFRESH_TOKEN_COOKIE_NAME)) == null ? void 0 : _a.value;
759
+ const activeOrgId = req.nextUrl.searchParams.get("active_org_id");
760
+ if (!oldRefreshToken) {
761
+ const headers2 = new Headers();
762
+ headers2.append(
763
+ "Set-Cookie",
764
+ `${ACTIVE_ORG_ID_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`
765
+ );
766
+ return new Response(null, { status: 401, headers: headers2 });
767
+ }
768
+ if (!activeOrgId) {
769
+ return new Response(null, { status: 400 });
770
+ }
771
+ const refreshResponse = yield refreshTokenWithAccessAndRefreshToken(oldRefreshToken, activeOrgId);
772
+ if (refreshResponse.error === "unexpected") {
773
+ throw new Error("Unexpected error while setting active org id");
774
+ } else if (refreshResponse.error === "unauthorized") {
775
+ return new Response("Unauthorized", { status: 401 });
776
+ }
777
+ const refreshToken = refreshResponse.refreshToken;
778
+ const accessToken = refreshResponse.accessToken;
779
+ const authUrlOrigin = getAuthUrlOrigin();
780
+ const path = `${authUrlOrigin}/propelauth/oauth/userinfo`;
781
+ const response = yield fetch(path, {
782
+ headers: {
783
+ "Content-Type": "application/json",
784
+ Authorization: "Bearer " + accessToken
785
+ }
786
+ });
787
+ if (response.ok) {
788
+ const userFromToken = yield validateAccessToken(accessToken);
789
+ const data = yield response.json();
790
+ const jsonResponse = {
791
+ userinfo: data,
792
+ accessToken,
793
+ impersonatorUserId: userFromToken.impersonatorUserId,
794
+ activeOrgId
795
+ };
796
+ const headers2 = new Headers();
797
+ headers2.append(
798
+ "Set-Cookie",
799
+ `${ACCESS_TOKEN_COOKIE_NAME}=${accessToken}; Path=/; HttpOnly; Secure; SameSite=Lax`
800
+ );
801
+ headers2.append(
802
+ "Set-Cookie",
803
+ `${REFRESH_TOKEN_COOKIE_NAME}=${refreshToken}; Path=/; HttpOnly; Secure; SameSite=Lax`
804
+ );
805
+ headers2.append(
806
+ "Set-Cookie",
807
+ `${ACTIVE_ORG_ID_COOKIE_NAME}=${activeOrgId}; Path=/; HttpOnly; Secure; SameSite=Lax`
808
+ );
809
+ headers2.append("Content-Type", "application/json");
810
+ return new Response(JSON.stringify(jsonResponse), {
811
+ status: 200,
812
+ headers: headers2
813
+ });
814
+ } else if (response.status === 401) {
815
+ return new Response(null, {
816
+ status: 401
817
+ });
818
+ } else {
819
+ return new Response(null, { status: 500 });
820
+ }
821
+ });
822
+ }
605
823
  function getRouteHandler(req, { params }) {
606
824
  if (params.slug === "login") {
607
825
  return loginGetHandler(req);
@@ -620,6 +838,8 @@ function getRouteHandlers(args) {
620
838
  function postRouteHandler(req, { params }) {
621
839
  if (params.slug === "logout") {
622
840
  return logoutPostHandler(req);
841
+ } else if (params.slug === "set-active-org") {
842
+ return setActiveOrgHandler(req);
623
843
  } else {
624
844
  return new Response("", { status: 404 });
625
845
  }