@propelauth/nextjs 0.0.71 → 0.0.77
Sign up to get free protection for your applications and to get access to all the features.
- package/README.md +50 -8
- package/dist/client/index.d.ts +52 -9
- package/dist/client/index.js +183 -64
- package/dist/client/index.js.map +1 -1
- package/dist/client/index.mjs +169 -51
- package/dist/client/index.mjs.map +1 -1
- package/dist/server/app-router/index.d.ts +6 -5
- package/dist/server/app-router/index.js +27 -20
- package/dist/server/app-router/index.js.map +1 -1
- package/dist/server/app-router/index.mjs +26 -20
- package/dist/server/app-router/index.mjs.map +1 -1
- package/dist/server/index.d.ts +60 -5
- package/dist/server/index.js +26 -6
- package/dist/server/index.js.map +1 -1
- package/dist/server/index.mjs +24 -5
- package/dist/server/index.mjs.map +1 -1
- package/dist/server/pages/index.d.ts +6 -5
- package/dist/server/pages/index.js +41 -4
- package/dist/server/pages/index.js.map +1 -1
- package/dist/server/pages/index.mjs +40 -4
- package/dist/server/pages/index.mjs.map +1 -1
- package/package.json +4 -3
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"sources":["../../src/user.ts","../../src/client/AuthProvider.tsx","../../src/client/utils.ts","../../src/client/useUser.tsx","../../src/client/useHostedPageUrls.tsx","../../src/client/useLogoutFunction.ts","../../src/client/useRedirectFunctions.tsx","../../src/client/useRefreshAuth.ts"],"sourcesContent":["export class User {\n public userId: string\n public orgIdToOrgMemberInfo?: OrgIdToOrgMemberInfo\n\n // Metadata about the user\n public email: string\n public firstName?: string\n public lastName?: string\n public username?: string\n\n // If you used our migration APIs to migrate this user from a different system,\n // this is their original ID from that system.\n public legacyUserId?: string\n public impersonatorUserId?: string\n\n constructor(\n userId: string,\n email: string,\n orgIdToOrgMemberInfo?: OrgIdToOrgMemberInfo,\n firstName?: string,\n lastName?: string,\n username?: string,\n legacyUserId?: string,\n impersonatorUserId?: string\n ) {\n this.userId = userId\n this.orgIdToOrgMemberInfo = orgIdToOrgMemberInfo\n\n this.email = email\n this.firstName = firstName\n this.lastName = lastName\n this.username = username\n\n this.legacyUserId = legacyUserId\n this.impersonatorUserId = impersonatorUserId\n }\n\n public getOrg(orgId: string): OrgMemberInfo | undefined {\n if (!this.orgIdToOrgMemberInfo) {\n return undefined\n }\n\n return this.orgIdToOrgMemberInfo[orgId]\n }\n\n public getOrgByName(orgName: string): OrgMemberInfo | undefined {\n if (!this.orgIdToOrgMemberInfo) {\n return undefined\n }\n\n const urlSafeOrgName = orgName.toLowerCase().replace(/ /g, \"-\")\n for (const orgId in this.orgIdToOrgMemberInfo) {\n const orgMemberInfo = this.orgIdToOrgMemberInfo[orgId]\n if (orgMemberInfo.urlSafeOrgName === urlSafeOrgName) {\n return orgMemberInfo\n }\n }\n\n return undefined\n }\n\n public getOrgs(): OrgMemberInfo[] {\n if (!this.orgIdToOrgMemberInfo) {\n return []\n }\n\n return Object.values(this.orgIdToOrgMemberInfo)\n }\n\n public isImpersonating(): boolean {\n return !!this.impersonatorUserId\n }\n\n public static fromJSON(json: string): User {\n const obj = JSON.parse(json)\n const orgIdToOrgMemberInfo: OrgIdToOrgMemberInfo = {}\n for (const orgId in obj.orgIdToOrgMemberInfo) {\n orgIdToOrgMemberInfo[orgId] = OrgMemberInfo.fromJSON(\n JSON.stringify(obj.orgIdToOrgMemberInfo[orgId])\n )\n }\n return new User(\n obj.userId,\n obj.email,\n orgIdToOrgMemberInfo,\n obj.firstName,\n obj.lastName,\n obj.username,\n obj.legacyUserId,\n obj.impersonatorUserId\n )\n }\n}\n\nexport type OrgIdToOrgMemberInfo = {\n [orgId: string]: OrgMemberInfo\n}\n\nexport class OrgMemberInfo {\n public orgId: string\n public orgName: string\n public orgMetadata: { [key: string]: any }\n public urlSafeOrgName: string\n\n private userAssignedRole: string\n private userInheritedRolesPlusCurrentRole: string[]\n private userPermissions: string[]\n\n constructor(\n orgId: string,\n orgName: string,\n orgMetadata: { [key: string]: any },\n urlSafeOrgName: string,\n userAssignedRole: string,\n userInheritedRolesPlusCurrentRole: string[],\n userPermissions: string[]\n ) {\n this.orgId = orgId\n this.orgName = orgName\n this.orgMetadata = orgMetadata\n this.urlSafeOrgName = urlSafeOrgName\n\n this.userAssignedRole = userAssignedRole\n this.userInheritedRolesPlusCurrentRole = userInheritedRolesPlusCurrentRole\n this.userPermissions = userPermissions\n }\n\n // validation methods\n\n public isRole(role: string): boolean {\n return this.userAssignedRole === role\n }\n\n public isAtLeastRole(role: string): boolean {\n return this.userInheritedRolesPlusCurrentRole.includes(role)\n }\n\n public hasPermission(permission: string): boolean {\n return this.userPermissions.includes(permission)\n }\n\n public hasAllPermissions(permissions: string[]): boolean {\n return permissions.every((permission) => this.hasPermission(permission))\n }\n\n public static fromJSON(json: string): OrgMemberInfo {\n const obj = JSON.parse(json)\n return new OrgMemberInfo(\n obj.orgId,\n obj.orgName,\n obj.orgMetadata,\n obj.urlSafeOrgName,\n obj.userAssignedRole,\n obj.userInheritedRolesPlusCurrentRole,\n obj.userPermissions\n )\n }\n\n // getters for the private fields\n\n get assignedRole(): string {\n return this.userAssignedRole\n }\n\n get inheritedRolesPlusCurrentRole(): string[] {\n return this.userInheritedRolesPlusCurrentRole\n }\n\n get permissions(): string[] {\n return this.userPermissions\n }\n}\n\n// These Internal types exist since the server returns snake case, but typescript/javascript\n// convention is camelCase.\nexport type InternalOrgMemberInfo = {\n org_id: string\n org_name: string\n org_metadata: { [key: string]: any }\n url_safe_org_name: string\n user_role: string\n inherited_user_roles_plus_current_role: string[]\n user_permissions: string[]\n}\nexport type InternalUser = {\n user_id: string\n org_id_to_org_member_info?: { [org_id: string]: InternalOrgMemberInfo }\n\n email: string\n first_name?: string\n last_name?: string\n username?: string\n\n // If you used our migration APIs to migrate this user from a different system, this is their original ID from that system.\n legacy_user_id?: string\n impersonatorUserId?: string\n}\n\nexport function toUser(snake_case: InternalUser): User {\n return new User(\n snake_case.user_id,\n snake_case.email,\n toOrgIdToOrgMemberInfo(snake_case.org_id_to_org_member_info),\n snake_case.first_name,\n snake_case.last_name,\n snake_case.username,\n snake_case.legacy_user_id,\n snake_case.impersonatorUserId\n )\n}\n\nexport function toOrgIdToOrgMemberInfo(snake_case?: {\n [org_id: string]: InternalOrgMemberInfo\n}): OrgIdToOrgMemberInfo | undefined {\n if (snake_case === undefined) {\n return undefined\n }\n const camelCase: OrgIdToOrgMemberInfo = {}\n\n for (const key of Object.keys(snake_case)) {\n const snakeCaseValue = snake_case[key]\n if (snakeCaseValue) {\n camelCase[key] = new OrgMemberInfo(\n snakeCaseValue.org_id,\n snakeCaseValue.org_name,\n snakeCaseValue.org_metadata,\n snakeCaseValue.url_safe_org_name,\n snakeCaseValue.user_role,\n snakeCaseValue.inherited_user_roles_plus_current_role,\n snakeCaseValue.user_permissions\n )\n }\n }\n\n return camelCase\n}\n","'use client'\n\nimport React, {useCallback, useEffect, useReducer} from \"react\"\nimport {User} from \"../user\"\nimport {doesLocalStorageMatch, hasWindow, isEqual, saveUserToLocalStorage, USER_INFO_KEY} from \"./utils\";\nimport {useRouter} from \"next/navigation\";\n\ninterface InternalAuthState {\n loading: boolean\n user?: User\n\n logout: () => Promise<void>\n\n redirectToLoginPage: () => void\n redirectToSignupPage: () => void\n redirectToAccountPage: () => void\n redirectToOrgPage: (orgId?: string) => void\n redirectToCreateOrgPage: () => void\n redirectToSetupSAMLPage: (orgId: string) => void\n\n getSignupPageUrl(): string\n\n getLoginPageUrl(): string\n\n getAccountPageUrl(): string\n\n getOrgPageUrl(orgId?: string): string\n\n getCreateOrgPageUrl(): string\n\n getSetupSAMLPageUrl(orgId: string): string\n\n refreshAuthInfo: () => Promise<User | undefined>\n}\n\nexport type AuthProviderProps = {\n authUrl: string\n children?: React.ReactNode\n}\n\nexport const AuthContext = React.createContext<InternalAuthState | undefined>(undefined)\n\ntype AuthState = {\n loading: boolean\n user?: User\n\n // There's no good way to trigger server components to reload outside of router.refresh()\n // This is our workaround until the app router has something better\n authChangeDetected: boolean\n}\n\nconst initialAuthState = {\n loading: true,\n user: undefined,\n authChangeDetected: false,\n}\n\ntype AuthStateAction = {\n user?: User\n}\n\nfunction authStateReducer(_state: AuthState, action: AuthStateAction): AuthState {\n const authChangeDetected = !_state.loading && !isEqual(action.user, _state.user)\n\n if (!action.user) {\n return {\n loading: false,\n user: undefined,\n authChangeDetected,\n }\n } else if (_state.loading) {\n return {\n loading: false,\n user: action.user,\n authChangeDetected,\n }\n } else {\n return {\n loading: false,\n user: action.user,\n authChangeDetected\n }\n }\n}\n\nexport const AuthProvider = (props: AuthProviderProps) => {\n const [authState, dispatchInner] = useReducer(authStateReducer, initialAuthState)\n const router = useRouter()\n\n const dispatch = useCallback((action: AuthStateAction) => {\n dispatchInner(action)\n saveUserToLocalStorage(action.user)\n }, [dispatchInner])\n\n // This is because we don't have a good way to trigger server components to reload outside of router.refresh()\n // Once server actions isn't alpha, we can hopefully use that instead\n useEffect(() => {\n if (authState.authChangeDetected) {\n router.refresh()\n }\n }, [authState.authChangeDetected, router])\n\n // Trigger an initial refresh\n useEffect(() => {\n let didCancel = false\n\n async function refreshAuthInfo() {\n const {user} = await apiGetUserInfo()\n if (!didCancel) {\n dispatch({user})\n }\n }\n\n refreshAuthInfo()\n return () => {\n didCancel = true\n }\n }, [])\n\n\n // Periodically refresh the token\n useEffect(() => {\n let didCancel = false\n\n async function refreshToken() {\n const {user} = await apiGetUserInfo()\n if (!didCancel) {\n dispatch({user})\n }\n }\n\n async function onStorageEvent(event: StorageEvent) {\n if (event.key === USER_INFO_KEY && !doesLocalStorageMatch(event.newValue, authState.user)) {\n await refreshToken()\n }\n }\n\n // TODO: Retry logic if the request fails\n const interval = setInterval(refreshToken, 5 * 60 * 1000)\n\n if (hasWindow()) {\n window.addEventListener(\"storage\", onStorageEvent)\n window.addEventListener(\"online\", refreshToken)\n window.addEventListener(\"focus\", refreshToken)\n }\n\n return () => {\n didCancel = true\n clearInterval(interval)\n if (hasWindow()) {\n window.removeEventListener(\"storage\", onStorageEvent)\n window.removeEventListener(\"online\", refreshToken)\n window.removeEventListener(\"focus\", refreshToken)\n }\n }\n }, [dispatch, authState.user])\n\n\n const logout = useCallback(async () => {\n await fetch(\"/api/auth/logout\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n credentials: \"include\",\n })\n dispatch({user: undefined})\n }, [dispatch])\n\n const getLoginPageUrl = () => \"/api/auth/login\"\n const getSignupPageUrl = () => \"/api/auth/signup\"\n const getAccountPageUrl = useCallback(() => {\n return `${props.authUrl}/account`\n }, [props.authUrl])\n const getOrgPageUrl = useCallback(\n (orgId?: string) => {\n if (orgId) {\n return `${props.authUrl}/org?id=${orgId}`\n } else {\n return `${props.authUrl}/org`\n }\n },\n [props.authUrl]\n )\n const getCreateOrgPageUrl = useCallback(() => {\n return `${props.authUrl}/create_org`\n }, [props.authUrl])\n\n const getSetupSAMLPageUrl = useCallback(\n (orgId: string) => {\n return `${props.authUrl}/saml?id=${orgId}`\n },\n [props.authUrl]\n )\n\n const redirectTo = (url: string) => {\n window.location.href = url\n }\n\n const redirectToLoginPage = () => redirectTo(getLoginPageUrl())\n const redirectToSignupPage = () => redirectTo(getSignupPageUrl())\n const redirectToAccountPage = () => redirectTo(getAccountPageUrl())\n const redirectToOrgPage = (orgId?: string) => redirectTo(getOrgPageUrl(orgId))\n const redirectToCreateOrgPage = () => redirectTo(getCreateOrgPageUrl())\n const redirectToSetupSAMLPage = (orgId: string) => redirectTo(getSetupSAMLPageUrl(orgId))\n\n const refreshAuthInfo = async () => {\n const {user} = await apiGetUserInfo()\n dispatch({user})\n return user\n }\n\n const value = {\n loading: authState.loading,\n user: authState.user,\n logout,\n redirectToLoginPage,\n redirectToSignupPage,\n redirectToAccountPage,\n redirectToOrgPage,\n redirectToCreateOrgPage,\n redirectToSetupSAMLPage,\n getLoginPageUrl,\n getSignupPageUrl,\n getAccountPageUrl,\n getOrgPageUrl,\n getCreateOrgPageUrl,\n getSetupSAMLPageUrl,\n refreshAuthInfo,\n }\n return <AuthContext.Provider value={value}>{props.children}</AuthContext.Provider>\n}\n\ntype UserInfoResponse = { user?: User }\n\nasync function apiGetUserInfo(): Promise<UserInfoResponse> {\n try {\n const userInfoResponse = await fetch(\"/api/auth/userinfo\", {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n credentials: \"include\",\n })\n\n if (userInfoResponse.ok) {\n const userJson = await userInfoResponse.text()\n const user = User.fromJSON(userJson)\n return {user}\n } else if (userInfoResponse.status === 401) {\n return {user: undefined}\n } else {\n console.log(\"Failed to refresh token\", userInfoResponse)\n }\n } catch (e) {\n console.log(\"Failed to refresh token\", e)\n }\n throw new Error(\"Failed to refresh token\")\n}\n","import {User} from \"../user\";\n\nexport const USER_INFO_KEY = \"__PROPEL_AUTH_USER_INFO\"\n\nexport function hasWindow(): boolean {\n return typeof window !== \"undefined\"\n}\n\nexport function saveUserToLocalStorage(user: User | undefined) {\n if (user) {\n localStorage.setItem(USER_INFO_KEY, JSON.stringify(user))\n } else {\n localStorage.setItem(USER_INFO_KEY, \"{}\")\n }\n}\n\nexport function doesLocalStorageMatch(newValue: string | null, user: User | undefined): boolean {\n if (!newValue) {\n return false\n } else if (!user) {\n return newValue === \"{}\"\n }\n\n const parsed = JSON.parse(newValue)\n if (!parsed) {\n return false\n }\n\n return isEqual(parsed, user)\n}\n\n\nexport function isEqual(a: any, b: any): boolean {\n if (typeof a !== typeof b) {\n return false\n }\n\n if (Array.isArray(a) !== Array.isArray(b)) {\n return false\n }\n\n if (Array.isArray(a)) {\n const aArray = a as any[]\n const bArray = b as any[]\n if (aArray.length !== bArray.length) {\n return false\n }\n\n for (let i = 0; i < aArray.length; i++) {\n if (!isEqual(aArray[i], bArray[i])) {\n return false\n }\n }\n\n return true\n }\n\n if (typeof a === \"object\") {\n const aKeys = Object.keys(a)\n const bKeys = Object.keys(b)\n if (aKeys.length !== bKeys.length) {\n return false\n }\n\n for (const key of aKeys) {\n if (!isEqual(a[key], b[key])) {\n return false\n }\n }\n\n return true\n } else {\n return a === b\n }\n}","'use client'\n\nimport {useContext} from \"react\"\nimport {User} from \"../user\"\nimport {AuthContext} from \"./AuthProvider\"\n\nexport type UseUserLoading = {\n loading: true\n isLoggedIn: never\n user: never\n}\n\nexport type UseUserLoggedIn = {\n loading: false\n isLoggedIn: true\n user: User\n}\n\nexport type UseUserNotLoggedIn = {\n loading: false\n isLoggedIn: false\n user: undefined\n}\n\nexport type UseUser = UseUserLoading | UseUserLoggedIn | UseUserNotLoggedIn\n\nexport function useUser(): UseUser {\n const context = useContext(AuthContext)\n if (context === undefined) {\n throw new Error(\"useUser must be used within an AuthProvider\")\n }\n\n const {loading, user} = context\n if (loading) {\n return {\n loading: true,\n isLoggedIn: undefined as never,\n user: undefined as never,\n }\n } else if (user) {\n return {\n loading: false,\n isLoggedIn: true,\n user,\n }\n } else {\n return {\n loading: false,\n isLoggedIn: false,\n user: undefined,\n }\n }\n}","import { useContext } from \"react\"\nimport { AuthContext } from \"./AuthProvider\"\n\nexport function useHostedPageUrls() {\n const context = useContext(AuthContext)\n if (context === undefined) {\n throw new Error(\"useHostedPageUrls must be used within an AuthProvider\")\n }\n const {\n getLoginPageUrl,\n getSignupPageUrl,\n getAccountPageUrl,\n getOrgPageUrl,\n getCreateOrgPageUrl,\n getSetupSAMLPageUrl,\n } = context\n return {\n getLoginPageUrl,\n getSignupPageUrl,\n getAccountPageUrl,\n getOrgPageUrl,\n getCreateOrgPageUrl,\n getSetupSAMLPageUrl,\n }\n}\n","import { useContext } from \"react\"\nimport { AuthContext } from \"./AuthProvider\"\n\nexport function useLogoutFunction() {\n const context = useContext(AuthContext)\n if (context === undefined) {\n throw new Error(\"useLogoutFunction must be used within an AuthProvider\")\n }\n const { logout } = context\n return logout\n}\n","import React, { useContext, useEffect } from \"react\"\nimport { AuthContext } from \"./AuthProvider\"\n\nexport function useRedirectFunctions() {\n const context = useContext(AuthContext)\n if (context === undefined) {\n throw new Error(\"useRedirectFunctions must be used within an AuthProvider\")\n }\n const {\n redirectToAccountPage,\n redirectToSignupPage,\n redirectToLoginPage,\n redirectToOrgPage,\n redirectToCreateOrgPage,\n } = context\n return {\n redirectToSignupPage,\n redirectToLoginPage,\n redirectToAccountPage,\n redirectToOrgPage,\n redirectToCreateOrgPage,\n }\n}\n\nexport interface RedirectProps {\n children?: React.ReactNode\n}\n\nexport function RedirectToSignup({ children }: RedirectProps) {\n const { redirectToSignupPage } = useRedirectFunctions()\n\n useEffect(() => {\n redirectToSignupPage()\n }, [])\n\n return <>{children}</>\n}\n\nexport function RedirectToLogin({ children }: RedirectProps) {\n const { redirectToLoginPage } = useRedirectFunctions()\n useEffect(() => {\n redirectToLoginPage()\n }, [])\n return <>{children}</>\n}\n","import { useContext } from \"react\"\nimport { AuthContext } from \"./AuthProvider\"\n\nexport function useRefreshAuth() {\n const context = useContext(AuthContext)\n if (context === undefined) {\n throw new Error(\"useRefreshAuth must be used within an AuthProvider\")\n }\n const { refreshAuthInfo } = context\n return refreshAuthInfo\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAAO,IAAM,OAAN,MAAW;AAAA,EAed,YACI,QACA,OACA,sBACA,WACA,UACA,UACA,cACA,oBACF;AACE,SAAK,SAAS;AACd,SAAK,uBAAuB;AAE5B,SAAK,QAAQ;AACb,SAAK,YAAY;AACjB,SAAK,WAAW;AAChB,SAAK,WAAW;AAEhB,SAAK,eAAe;AACpB,SAAK,qBAAqB;AAAA,EAC9B;AAAA,EAEO,OAAO,OAA0C;AACpD,QAAI,CAAC,KAAK,sBAAsB;AAC5B,aAAO;AAAA,IACX;AAEA,WAAO,KAAK,qBAAqB,KAAK;AAAA,EAC1C;AAAA,EAEO,aAAa,SAA4C;AAC5D,QAAI,CAAC,KAAK,sBAAsB;AAC5B,aAAO;AAAA,IACX;AAEA,UAAM,iBAAiB,QAAQ,YAAY,EAAE,QAAQ,MAAM,GAAG;AAC9D,eAAW,SAAS,KAAK,sBAAsB;AAC3C,YAAM,gBAAgB,KAAK,qBAAqB,KAAK;AACrD,UAAI,cAAc,mBAAmB,gBAAgB;AACjD,eAAO;AAAA,MACX;AAAA,IACJ;AAEA,WAAO;AAAA,EACX;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AAAA,EACzB,GAAG,CAAC,CAAC;AAEL,SAAO,gBAAAC,OAAA,cAAAA,OAAA,gBAAG,QAAS;AACvB;AAEO,SAAS,gBAAgB,EAAE,SAAS,GAAkB;AACzD,QAAM,EAAE,oBAAoB,IAAI,qBAAqB;AACrD,EAAAD,WAAU,MAAM;AACZ,wBAAoB;AAAA,EACxB,GAAG,CAAC,CAAC;AACL,SAAO,gBAAAC,OAAA,cAAAA,OAAA,gBAAG,QAAS;AACvB;;;AC5CA,SAAS,cAAAC,mBAAkB;AAGpB,SAAS,iBAAiB;AAC7B,QAAM,UAAUC,YAAW,WAAW;AACtC,MAAI,YAAY,QAAW;AACvB,UAAM,IAAI,MAAM,oDAAoD;AAAA,EACxE;AACA,QAAM,EAAE,gBAAgB,IAAI;AAC5B,SAAO;AACX;","names":["refreshAuthInfo","useContext","useContext","useContext","useContext","React","useContext","useEffect","useContext","useEffect","React","useContext","useContext"]}
|
1
|
+
{"version":3,"sources":["../../src/user.ts","../../src/client/AuthProvider.tsx","../../src/client/utils.ts","../../src/client/useUser.tsx","../../src/client/useHostedPageUrls.tsx","../../src/client/useLogoutFunction.ts","../../src/client/useRedirectFunctions.tsx","../../src/client/useRefreshAuth.ts"],"sourcesContent":["export class UserFromToken {\n public userId: string\n public orgIdToOrgMemberInfo?: OrgIdToOrgMemberInfo\n\n // Metadata about the user\n public email: string\n public firstName?: string\n public lastName?: string\n public username?: string\n\n // If you used our migration APIs to migrate this user from a different system,\n // this is their original ID from that system.\n public legacyUserId?: string\n public impersonatorUserId?: string\n\n constructor(\n userId: string,\n email: string,\n orgIdToOrgMemberInfo?: OrgIdToOrgMemberInfo,\n firstName?: string,\n lastName?: string,\n username?: string,\n legacyUserId?: string,\n impersonatorUserId?: string\n ) {\n this.userId = userId\n this.orgIdToOrgMemberInfo = orgIdToOrgMemberInfo\n\n this.email = email\n this.firstName = firstName\n this.lastName = lastName\n this.username = username\n\n this.legacyUserId = legacyUserId\n this.impersonatorUserId = impersonatorUserId\n }\n\n public getOrg(orgId: string): OrgMemberInfo | undefined {\n if (!this.orgIdToOrgMemberInfo) {\n return undefined\n }\n\n return this.orgIdToOrgMemberInfo[orgId]\n }\n\n public getOrgByName(orgName: string): OrgMemberInfo | undefined {\n if (!this.orgIdToOrgMemberInfo) {\n return undefined\n }\n\n const urlSafeOrgName = orgName.toLowerCase().replace(/ /g, \"-\")\n for (const orgId in this.orgIdToOrgMemberInfo) {\n const orgMemberInfo = this.orgIdToOrgMemberInfo[orgId]\n if (orgMemberInfo.urlSafeOrgName === urlSafeOrgName) {\n return orgMemberInfo\n }\n }\n\n return undefined\n }\n\n public getOrgs(): OrgMemberInfo[] {\n if (!this.orgIdToOrgMemberInfo) {\n return []\n }\n\n return Object.values(this.orgIdToOrgMemberInfo)\n }\n\n public isImpersonating(): boolean {\n return !!this.impersonatorUserId\n }\n\n public static fromJSON(json: string): UserFromToken {\n const obj = JSON.parse(json)\n const orgIdToOrgMemberInfo: OrgIdToOrgMemberInfo = {}\n for (const orgId in obj.orgIdToOrgMemberInfo) {\n orgIdToOrgMemberInfo[orgId] = OrgMemberInfo.fromJSON(\n JSON.stringify(obj.orgIdToOrgMemberInfo[orgId])\n )\n }\n return new UserFromToken(\n obj.userId,\n obj.email,\n orgIdToOrgMemberInfo,\n obj.firstName,\n obj.lastName,\n obj.username,\n obj.legacyUserId,\n obj.impersonatorUserId\n )\n }\n}\n\nexport type OrgIdToOrgMemberInfo = {\n [orgId: string]: OrgMemberInfo\n}\n\nexport class OrgMemberInfo {\n public orgId: string\n public orgName: string\n public orgMetadata: { [key: string]: any }\n public urlSafeOrgName: string\n\n private userAssignedRole: string\n private userInheritedRolesPlusCurrentRole: string[]\n private userPermissions: string[]\n\n constructor(\n orgId: string,\n orgName: string,\n orgMetadata: { [key: string]: any },\n urlSafeOrgName: string,\n userAssignedRole: string,\n userInheritedRolesPlusCurrentRole: string[],\n userPermissions: string[]\n ) {\n this.orgId = orgId\n this.orgName = orgName\n this.orgMetadata = orgMetadata\n this.urlSafeOrgName = urlSafeOrgName\n\n this.userAssignedRole = userAssignedRole\n this.userInheritedRolesPlusCurrentRole = userInheritedRolesPlusCurrentRole\n this.userPermissions = userPermissions\n }\n\n // validation methods\n\n public isRole(role: string): boolean {\n return this.userAssignedRole === role\n }\n\n public isAtLeastRole(role: string): boolean {\n return this.userInheritedRolesPlusCurrentRole.includes(role)\n }\n\n public hasPermission(permission: string): boolean {\n return this.userPermissions.includes(permission)\n }\n\n public hasAllPermissions(permissions: string[]): boolean {\n return permissions.every((permission) => this.hasPermission(permission))\n }\n\n public static fromJSON(json: string): OrgMemberInfo {\n const obj = JSON.parse(json)\n return new OrgMemberInfo(\n obj.orgId,\n obj.orgName,\n obj.orgMetadata,\n obj.urlSafeOrgName,\n obj.userAssignedRole,\n obj.userInheritedRolesPlusCurrentRole,\n obj.userPermissions\n )\n }\n\n // getters for the private fields\n\n get assignedRole(): string {\n return this.userAssignedRole\n }\n\n get inheritedRolesPlusCurrentRole(): string[] {\n return this.userInheritedRolesPlusCurrentRole\n }\n\n get permissions(): string[] {\n return this.userPermissions\n }\n}\n\n// These Internal types exist since the server returns snake case, but typescript/javascript\n// convention is camelCase.\nexport type InternalOrgMemberInfo = {\n org_id: string\n org_name: string\n org_metadata: { [key: string]: any }\n url_safe_org_name: string\n user_role: string\n inherited_user_roles_plus_current_role: string[]\n user_permissions: string[]\n}\nexport type InternalUser = {\n user_id: string\n org_id_to_org_member_info?: { [org_id: string]: InternalOrgMemberInfo }\n\n email: string\n first_name?: string\n last_name?: string\n username?: string\n\n // If you used our migration APIs to migrate this user from a different system, this is their original ID from that system.\n legacy_user_id?: string\n impersonatorUserId?: string\n}\n\nexport function toUser(snake_case: InternalUser): UserFromToken {\n return new UserFromToken(\n snake_case.user_id,\n snake_case.email,\n toOrgIdToOrgMemberInfo(snake_case.org_id_to_org_member_info),\n snake_case.first_name,\n snake_case.last_name,\n snake_case.username,\n snake_case.legacy_user_id,\n snake_case.impersonatorUserId\n )\n}\n\nexport function toOrgIdToOrgMemberInfo(snake_case?: {\n [org_id: string]: InternalOrgMemberInfo\n}): OrgIdToOrgMemberInfo | undefined {\n if (snake_case === undefined) {\n return undefined\n }\n const camelCase: OrgIdToOrgMemberInfo = {}\n\n for (const key of Object.keys(snake_case)) {\n const snakeCaseValue = snake_case[key]\n if (snakeCaseValue) {\n camelCase[key] = new OrgMemberInfo(\n snakeCaseValue.org_id,\n snakeCaseValue.org_name,\n snakeCaseValue.org_metadata,\n snakeCaseValue.url_safe_org_name,\n snakeCaseValue.user_role,\n snakeCaseValue.inherited_user_roles_plus_current_role,\n snakeCaseValue.user_permissions\n )\n }\n }\n\n return camelCase\n}\n","'use client'\n\nimport React, {useCallback, useEffect, useReducer} from \"react\"\nimport {doesLocalStorageMatch, hasWindow, isEqual, saveUserToLocalStorage, USER_INFO_KEY} from \"./utils\";\nimport {useRouter} from \"next/navigation\";\nimport {User} from \"./useUser\";\nimport {toOrgIdToOrgMemberInfo} from \"../user\";\n\ninterface InternalAuthState {\n loading: boolean\n userAndAccessToken: UserAndAccessToken\n\n logout: () => Promise<void>\n\n redirectToLoginPage: () => void\n redirectToSignupPage: () => void\n redirectToAccountPage: () => void\n redirectToOrgPage: (orgId?: string) => void\n redirectToCreateOrgPage: () => void\n redirectToSetupSAMLPage: (orgId: string) => void\n\n getSignupPageUrl(): string\n\n getLoginPageUrl(): string\n\n getAccountPageUrl(): string\n\n getOrgPageUrl(orgId?: string): string\n\n getCreateOrgPageUrl(): string\n\n getSetupSAMLPageUrl(orgId: string): string\n\n refreshAuthInfo: () => Promise<User | undefined>\n}\n\nexport type AuthProviderProps = {\n authUrl: string\n children?: React.ReactNode\n}\n\nexport const AuthContext = React.createContext<InternalAuthState | undefined>(undefined)\n\ntype UserAndAccessToken = {\n user: User\n accessToken: string\n} | {\n user: undefined\n accessToken: undefined\n}\n\ntype AuthState = {\n loading: boolean\n userAndAccessToken: UserAndAccessToken\n\n // There's no good way to trigger server components to reload outside of router.refresh()\n // This is our workaround until the app router has something better\n authChangeDetected: boolean\n}\n\nconst initialAuthState = {\n loading: true,\n userAndAccessToken: {\n user: undefined,\n accessToken: undefined,\n },\n authChangeDetected: false,\n}\n\ntype AuthStateAction = {\n user: User\n accessToken: string\n} | {\n user: undefined\n accessToken: undefined\n}\n\nfunction authStateReducer(_state: AuthState, action: AuthStateAction): AuthState {\n const authChangeDetected = !_state.loading && !isEqual(action.user, _state.userAndAccessToken.user)\n\n if (!action.user) {\n return {\n loading: false,\n userAndAccessToken: {\n user: undefined,\n accessToken: undefined,\n },\n authChangeDetected,\n }\n } else if (_state.loading) {\n return {\n loading: false,\n userAndAccessToken: {\n user: action.user,\n accessToken: action.accessToken,\n },\n authChangeDetected,\n }\n } else {\n return {\n loading: false,\n userAndAccessToken: {\n user: action.user,\n accessToken: action.accessToken,\n },\n authChangeDetected\n }\n }\n}\n\nexport const AuthProvider = (props: AuthProviderProps) => {\n const [authState, dispatchInner] = useReducer(authStateReducer, initialAuthState)\n const router = useRouter()\n\n const dispatch = useCallback((action: AuthStateAction) => {\n dispatchInner(action)\n saveUserToLocalStorage(action.user)\n }, [dispatchInner])\n\n // This is because we don't have a good way to trigger server components to reload outside of router.refresh()\n // Once server actions isn't alpha, we can hopefully use that instead\n useEffect(() => {\n if (authState.authChangeDetected) {\n router.refresh()\n }\n }, [authState.authChangeDetected, router])\n\n // Trigger an initial refresh\n useEffect(() => {\n let didCancel = false\n\n async function refreshAuthInfo() {\n const action = await apiGetUserInfo()\n if (!didCancel) {\n dispatch(action)\n }\n }\n\n refreshAuthInfo()\n return () => {\n didCancel = true\n }\n }, [])\n\n\n // Periodically refresh the token\n useEffect(() => {\n let didCancel = false\n\n async function refreshToken() {\n const action = await apiGetUserInfo()\n if (!didCancel) {\n dispatch(action)\n }\n }\n\n async function onStorageEvent(event: StorageEvent) {\n if (event.key === USER_INFO_KEY && !doesLocalStorageMatch(event.newValue, authState.userAndAccessToken.user)) {\n await refreshToken()\n }\n }\n\n // TODO: Retry logic if the request fails\n const interval = setInterval(refreshToken, 5 * 60 * 1000)\n\n if (hasWindow()) {\n window.addEventListener(\"storage\", onStorageEvent)\n window.addEventListener(\"online\", refreshToken)\n window.addEventListener(\"focus\", refreshToken)\n }\n\n return () => {\n didCancel = true\n clearInterval(interval)\n if (hasWindow()) {\n window.removeEventListener(\"storage\", onStorageEvent)\n window.removeEventListener(\"online\", refreshToken)\n window.removeEventListener(\"focus\", refreshToken)\n }\n }\n }, [dispatch, authState.userAndAccessToken.user])\n\n\n const logout = useCallback(async () => {\n await fetch(\"/api/auth/logout\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n credentials: \"include\",\n })\n dispatch({user: undefined, accessToken: undefined})\n }, [dispatch])\n\n const getLoginPageUrl = () => \"/api/auth/login\"\n const getSignupPageUrl = () => \"/api/auth/signup\"\n const getAccountPageUrl = useCallback(() => {\n return `${props.authUrl}/account`\n }, [props.authUrl])\n const getOrgPageUrl = useCallback(\n (orgId?: string) => {\n if (orgId) {\n return `${props.authUrl}/org?id=${orgId}`\n } else {\n return `${props.authUrl}/org`\n }\n },\n [props.authUrl]\n )\n const getCreateOrgPageUrl = useCallback(() => {\n return `${props.authUrl}/create_org`\n }, [props.authUrl])\n\n const getSetupSAMLPageUrl = useCallback(\n (orgId: string) => {\n return `${props.authUrl}/saml?id=${orgId}`\n },\n [props.authUrl]\n )\n\n const redirectTo = (url: string) => {\n window.location.href = url\n }\n\n const redirectToLoginPage = () => redirectTo(getLoginPageUrl())\n const redirectToSignupPage = () => redirectTo(getSignupPageUrl())\n const redirectToAccountPage = () => redirectTo(getAccountPageUrl())\n const redirectToOrgPage = (orgId?: string) => redirectTo(getOrgPageUrl(orgId))\n const redirectToCreateOrgPage = () => redirectTo(getCreateOrgPageUrl())\n const redirectToSetupSAMLPage = (orgId: string) => redirectTo(getSetupSAMLPageUrl(orgId))\n\n const refreshAuthInfo = async () => {\n const action = await apiGetUserInfo()\n dispatch(action)\n return action.user\n }\n\n const value = {\n loading: authState.loading,\n userAndAccessToken: authState.userAndAccessToken,\n logout,\n redirectToLoginPage,\n redirectToSignupPage,\n redirectToAccountPage,\n redirectToOrgPage,\n redirectToCreateOrgPage,\n redirectToSetupSAMLPage,\n getLoginPageUrl,\n getSignupPageUrl,\n getAccountPageUrl,\n getOrgPageUrl,\n getCreateOrgPageUrl,\n getSetupSAMLPageUrl,\n refreshAuthInfo,\n }\n return <AuthContext.Provider value={value}>{props.children}</AuthContext.Provider>\n}\n\ntype UserInfoResponse = {\n user: User\n accessToken: string\n} | {\n user: undefined\n accessToken: undefined\n}\n\nasync function apiGetUserInfo(): Promise<UserInfoResponse> {\n try {\n const userInfoResponse = await fetch(\"/api/auth/userinfo\", {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n credentials: \"include\",\n })\n\n if (userInfoResponse.ok) {\n const {userinfo, accessToken, impersonatorUserId} = await userInfoResponse.json()\n const user = new User({\n userId: userinfo.user_id,\n email: userinfo.email,\n emailConfirmed: userinfo.email_confirmed,\n hasPassword: userinfo.has_password,\n username: userinfo.username,\n firstName: userinfo.first_name,\n lastName: userinfo.last_name,\n pictureUrl: userinfo.picture_url,\n orgIdToOrgMemberInfo: toOrgIdToOrgMemberInfo(userinfo.org_id_to_org_info),\n mfaEnabled: userinfo.mfa_enabled,\n canCreateOrgs: userinfo.can_create_orgs,\n updatePasswordRequired: userinfo.update_password_required,\n createdAt: userinfo.created_at,\n lastActiveAt: userinfo.last_active_at,\n impersonatorUserId,\n })\n\n return {user, accessToken}\n } else if (userInfoResponse.status === 401) {\n return {user: undefined, accessToken: undefined}\n } else {\n console.log(\"Failed to refresh token\", userInfoResponse)\n }\n } catch (e) {\n console.log(\"Failed to refresh token\", e)\n }\n throw new Error(\"Failed to refresh token\")\n}\n","import {UserFromToken} from \"../user\";\nimport {User} from \"./useUser\";\n\nexport const USER_INFO_KEY = \"__PROPEL_AUTH_USER_INFO\"\n\nexport function hasWindow(): boolean {\n return typeof window !== \"undefined\"\n}\n\nexport function saveUserToLocalStorage(user: User | undefined) {\n if (user) {\n localStorage.setItem(USER_INFO_KEY, JSON.stringify(user))\n } else {\n localStorage.setItem(USER_INFO_KEY, \"{}\")\n }\n}\n\nexport function doesLocalStorageMatch(newValue: string | null, user: UserFromToken | undefined): boolean {\n if (!newValue) {\n return false\n } else if (!user) {\n return newValue === \"{}\"\n }\n\n const parsed = JSON.parse(newValue)\n if (!parsed) {\n return false\n }\n\n return isEqual(parsed, user)\n}\n\n\nexport function isEqual(a: any, b: any): boolean {\n if (typeof a !== typeof b) {\n return false\n }\n\n if (Array.isArray(a) !== Array.isArray(b)) {\n return false\n }\n\n if (Array.isArray(a)) {\n const aArray = a as any[]\n const bArray = b as any[]\n if (aArray.length !== bArray.length) {\n return false\n }\n\n for (let i = 0; i < aArray.length; i++) {\n if (!isEqual(aArray[i], bArray[i])) {\n return false\n }\n }\n\n return true\n }\n\n if (typeof a === \"object\") {\n const aKeys = Object.keys(a)\n const bKeys = Object.keys(b)\n if (aKeys.length !== bKeys.length) {\n return false\n }\n\n for (const key of aKeys) {\n if (!isEqual(a[key], b[key])) {\n return false\n }\n }\n\n return true\n } else {\n return a === b\n }\n}","'use client'\n\nimport {useContext} from \"react\"\nimport {AuthContext} from \"./AuthProvider\"\nimport {OrgIdToOrgMemberInfo, OrgMemberInfo} from \"../user\";\n\nexport class User {\n public userId: string\n public email: string\n public emailConfirmed: boolean\n public hasPassword: boolean\n\n public username?: string\n public firstName?: string\n public lastName?: string\n public pictureUrl?: string\n\n public orgIdToOrgMemberInfo?: OrgIdToOrgMemberInfo\n\n public mfaEnabled: boolean\n public canCreateOrgs: boolean\n public updatePasswordRequired: boolean\n\n public createdAt: number\n public lastActiveAt: number\n\n public legacyUserId?: string\n public impersonatorUserId?: string\n\n constructor({\n userId,\n email,\n emailConfirmed,\n hasPassword,\n username,\n firstName,\n lastName,\n pictureUrl,\n orgIdToOrgMemberInfo,\n mfaEnabled,\n canCreateOrgs,\n updatePasswordRequired,\n createdAt,\n lastActiveAt,\n legacyUserId,\n impersonatorUserId,\n }: {\n userId: string\n email: string\n emailConfirmed: boolean\n hasPassword: boolean\n username?: string\n firstName?: string\n lastName?: string\n pictureUrl?: string\n orgIdToOrgMemberInfo?: OrgIdToOrgMemberInfo\n mfaEnabled: boolean\n canCreateOrgs: boolean\n updatePasswordRequired: boolean\n createdAt: number\n lastActiveAt: number\n legacyUserId?: string\n impersonatorUserId?: string\n }) {\n this.userId = userId\n this.email = email\n this.emailConfirmed = emailConfirmed\n this.hasPassword = hasPassword\n this.username = username\n this.firstName = firstName\n this.lastName = lastName\n this.pictureUrl = pictureUrl\n this.orgIdToOrgMemberInfo = orgIdToOrgMemberInfo\n this.mfaEnabled = mfaEnabled\n this.canCreateOrgs = canCreateOrgs\n this.updatePasswordRequired = updatePasswordRequired\n this.createdAt = createdAt\n this.lastActiveAt = lastActiveAt\n this.legacyUserId = legacyUserId\n this.impersonatorUserId = impersonatorUserId\n }\n\n public getOrg(orgId: string): OrgMemberInfo | undefined {\n return this.orgIdToOrgMemberInfo?.[orgId]\n }\n\n public getOrgByName(orgName: string): OrgMemberInfo | undefined {\n if (!this.orgIdToOrgMemberInfo) {\n return undefined\n }\n\n const urlSafeOrgName = orgName.toLowerCase().replace(/ /g, \"-\")\n for (const orgId in this.orgIdToOrgMemberInfo) {\n const orgMemberInfo = this.orgIdToOrgMemberInfo[orgId]\n if (orgMemberInfo.urlSafeOrgName === urlSafeOrgName) {\n return orgMemberInfo\n }\n }\n\n return undefined\n }\n\n public getOrgs(): OrgMemberInfo[] {\n if (!this.orgIdToOrgMemberInfo) {\n return []\n }\n\n return Object.values(this.orgIdToOrgMemberInfo)\n }\n\n public isImpersonating(): boolean {\n return !!this.impersonatorUserId\n }\n}\n\nexport type UseUserLoading = {\n loading: true\n isLoggedIn: never\n user: never\n accessToken: never\n}\n\nexport type UseUserLoggedIn = {\n loading: false\n isLoggedIn: true\n user: User\n accessToken: string\n}\n\nexport type UseUserNotLoggedIn = {\n loading: false\n isLoggedIn: false\n user: undefined\n accessToken: undefined\n}\n\nexport type UseUser = UseUserLoading | UseUserLoggedIn | UseUserNotLoggedIn\n\nexport function useUser(): UseUser {\n const context = useContext(AuthContext)\n if (context === undefined) {\n throw new Error(\"useUser must be used within an AuthProvider\")\n }\n\n const {loading, userAndAccessToken} = context\n if (loading) {\n return {\n loading: true,\n isLoggedIn: undefined as never,\n user: undefined as never,\n accessToken: undefined as never,\n }\n } else if (userAndAccessToken.user) {\n return {\n loading: false,\n isLoggedIn: true,\n user: userAndAccessToken.user,\n accessToken: userAndAccessToken.accessToken,\n }\n } else {\n return {\n loading: false,\n isLoggedIn: false,\n user: undefined,\n accessToken: undefined,\n }\n }\n}","import { useContext } from \"react\"\nimport { AuthContext } from \"./AuthProvider\"\n\nexport function useHostedPageUrls() {\n const context = useContext(AuthContext)\n if (context === undefined) {\n throw new Error(\"useHostedPageUrls must be used within an AuthProvider\")\n }\n const {\n getLoginPageUrl,\n getSignupPageUrl,\n getAccountPageUrl,\n getOrgPageUrl,\n getCreateOrgPageUrl,\n getSetupSAMLPageUrl,\n } = context\n return {\n getLoginPageUrl,\n getSignupPageUrl,\n getAccountPageUrl,\n getOrgPageUrl,\n getCreateOrgPageUrl,\n getSetupSAMLPageUrl,\n }\n}\n","import { useContext } from \"react\"\nimport { AuthContext } from \"./AuthProvider\"\n\nexport function useLogoutFunction() {\n const context = useContext(AuthContext)\n if (context === undefined) {\n throw new Error(\"useLogoutFunction must be used within an AuthProvider\")\n }\n const { logout } = context\n return logout\n}\n","import React, { useContext, useEffect } from \"react\"\nimport { AuthContext } from \"./AuthProvider\"\n\nexport function useRedirectFunctions() {\n const context = useContext(AuthContext)\n if (context === undefined) {\n throw new Error(\"useRedirectFunctions must be used within an AuthProvider\")\n }\n const {\n redirectToAccountPage,\n redirectToSignupPage,\n redirectToLoginPage,\n redirectToOrgPage,\n redirectToCreateOrgPage,\n } = context\n return {\n redirectToSignupPage,\n redirectToLoginPage,\n redirectToAccountPage,\n redirectToOrgPage,\n redirectToCreateOrgPage,\n }\n}\n\nexport interface RedirectProps {\n children?: React.ReactNode\n}\n\nexport function RedirectToSignup({ children }: RedirectProps) {\n const { redirectToSignupPage } = useRedirectFunctions()\n\n useEffect(() => {\n redirectToSignupPage()\n }, [])\n\n return <>{children}</>\n}\n\nexport function RedirectToLogin({ children }: RedirectProps) {\n const { redirectToLoginPage } = useRedirectFunctions()\n useEffect(() => {\n redirectToLoginPage()\n }, [])\n return <>{children}</>\n}\n","import { useContext } from \"react\"\nimport { AuthContext } from \"./AuthProvider\"\n\nexport function useRefreshAuth() {\n const context = useContext(AuthContext)\n if (context === undefined) {\n throw new Error(\"useRefreshAuth must be used within an AuthProvider\")\n }\n const { refreshAuthInfo } = context\n return refreshAuthInfo\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAAO,IAAM,gBAAN,MAAoB;AAAA,EAevB,YACI,QACA,OACA,sBACA,WACA,UACA,UACA,cACA,oBACF;AACE,SAAK,SAAS;AACd,SAAK,uBAAuB;AAE5B,SAAK,QAAQ;AACb,SAAK,YAAY;AACjB,SAAK,WAAW;AAChB,SAAK,WAAW;AAEhB,SAAK,eAAe;AACpB,SAAK,qBAAqB;AAAA,EAC9B;AAAA,EAEO,OAAO,OAA0C;AACpD,QAAI,CAAC,KAAK,sBAAsB;AAC5B,aAAO;AAAA,IACX;AAEA,WAAO,KAAK,qBAAqB,KAAK;AAAA,EAC1C;AAAA,EAEO,aAAa,SAA4C;AAC5D,QAAI,CAAC,KAAK,sBAAsB;AAC5B,aAAO;AAAA,IACX;AAEA,UAAM,iBAAiB,QAAQ,YAAY,EAAE,QAAQ,MAAM,GAAG;AAC9D,eAAW,SAAS,KAAK,sBAAsB;AAC3C,YAAM,gBAAgB,KAAK,qBAAqB,KAAK;AACrD,UAAI,cAAc,mBAAmB,gBAAgB;AACjD,eAAO;AAAA,MACX;AAAA,IACJ;AAEA,WAAO;AAAA,EACX;AAAA,EAEO,UAA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,CAAC;AACL,SAAO,gBAAAC,OAAA,cAAAA,OAAA,gBAAG,QAAS;AACvB;;;AC5CA,SAAS,cAAAC,mBAAkB;AAGpB,SAAS,iBAAiB;AAC7B,QAAM,UAAUC,YAAW,WAAW;AACtC,MAAI,YAAY,QAAW;AACvB,UAAM,IAAI,MAAM,oDAAoD;AAAA,EACxE;AACA,QAAM,EAAE,gBAAgB,IAAI;AAC5B,SAAO;AACX;","names":["refreshAuthInfo","useContext","useContext","useContext","useContext","React","useContext","useEffect","useContext","useEffect","React","useContext","useContext"]}
|
@@ -11,7 +11,7 @@ declare class ConfigurationException extends Error {
|
|
11
11
|
constructor(message: string);
|
12
12
|
}
|
13
13
|
|
14
|
-
declare class
|
14
|
+
declare class UserFromToken {
|
15
15
|
userId: string;
|
16
16
|
orgIdToOrgMemberInfo?: OrgIdToOrgMemberInfo;
|
17
17
|
email: string;
|
@@ -25,7 +25,7 @@ declare class User {
|
|
25
25
|
getOrgByName(orgName: string): OrgMemberInfo | undefined;
|
26
26
|
getOrgs(): OrgMemberInfo[];
|
27
27
|
isImpersonating(): boolean;
|
28
|
-
static fromJSON(json: string):
|
28
|
+
static fromJSON(json: string): UserFromToken;
|
29
29
|
}
|
30
30
|
type OrgIdToOrgMemberInfo = {
|
31
31
|
[orgId: string]: OrgMemberInfo;
|
@@ -53,8 +53,9 @@ declare class OrgMemberInfo {
|
|
53
53
|
get permissions(): string[];
|
54
54
|
}
|
55
55
|
|
56
|
-
declare function getUserOrRedirect(): Promise<
|
57
|
-
declare function getUser(): Promise<
|
56
|
+
declare function getUserOrRedirect(): Promise<UserFromToken>;
|
57
|
+
declare function getUser(): Promise<UserFromToken | undefined>;
|
58
|
+
declare function getAccessToken(): Promise<string | undefined>;
|
58
59
|
declare function authMiddleware(req: NextRequest): Promise<Response>;
|
59
60
|
type RouteHandlerArgs = {
|
60
61
|
postLoginRedirectPathFn?: (req: NextRequest) => string;
|
@@ -72,4 +73,4 @@ declare function getRouteHandlers(args?: RouteHandlerArgs): {
|
|
72
73
|
}) => Response | Promise<Response>;
|
73
74
|
};
|
74
75
|
|
75
|
-
export { ConfigurationException, RouteHandlerArgs, UnauthorizedException, authMiddleware, getRouteHandlers, getUser, getUserOrRedirect };
|
76
|
+
export { ConfigurationException, RouteHandlerArgs, UnauthorizedException, authMiddleware, getAccessToken, getRouteHandlers, getUser, getUserOrRedirect };
|
@@ -53,6 +53,7 @@ __export(app_router_index_exports, {
|
|
53
53
|
ConfigurationException: () => ConfigurationException,
|
54
54
|
UnauthorizedException: () => UnauthorizedException,
|
55
55
|
authMiddleware: () => authMiddleware,
|
56
|
+
getAccessToken: () => getAccessToken,
|
56
57
|
getRouteHandlers: () => getRouteHandlers,
|
57
58
|
getUser: () => getUser,
|
58
59
|
getUserOrRedirect: () => getUserOrRedirect
|
@@ -75,8 +76,13 @@ var ConfigurationException = class extends Error {
|
|
75
76
|
}
|
76
77
|
};
|
77
78
|
|
79
|
+
// src/server/app-router.ts
|
80
|
+
var import_navigation = require("next/navigation");
|
81
|
+
var import_headers = require("next/headers");
|
82
|
+
var import_server = require("next/server");
|
83
|
+
|
78
84
|
// src/user.ts
|
79
|
-
var
|
85
|
+
var UserFromToken = class {
|
80
86
|
constructor(userId, email, orgIdToOrgMemberInfo, firstName, lastName, username, legacyUserId, impersonatorUserId) {
|
81
87
|
this.userId = userId;
|
82
88
|
this.orgIdToOrgMemberInfo = orgIdToOrgMemberInfo;
|
@@ -123,7 +129,7 @@ var User = class {
|
|
123
129
|
JSON.stringify(obj.orgIdToOrgMemberInfo[orgId])
|
124
130
|
);
|
125
131
|
}
|
126
|
-
return new
|
132
|
+
return new UserFromToken(
|
127
133
|
obj.userId,
|
128
134
|
obj.email,
|
129
135
|
orgIdToOrgMemberInfo,
|
@@ -182,7 +188,7 @@ var OrgMemberInfo = class {
|
|
182
188
|
}
|
183
189
|
};
|
184
190
|
function toUser(snake_case) {
|
185
|
-
return new
|
191
|
+
return new UserFromToken(
|
186
192
|
snake_case.user_id,
|
187
193
|
snake_case.email,
|
188
194
|
toOrgIdToOrgMemberInfo(snake_case.org_id_to_org_member_info),
|
@@ -215,11 +221,6 @@ function toOrgIdToOrgMemberInfo(snake_case) {
|
|
215
221
|
return camelCase;
|
216
222
|
}
|
217
223
|
|
218
|
-
// src/server/app-router.ts
|
219
|
-
var import_navigation = require("next/navigation");
|
220
|
-
var import_headers = require("next/headers");
|
221
|
-
var import_server = require("next/server");
|
222
|
-
|
223
224
|
// src/server/shared.ts
|
224
225
|
var jose = __toESM(require("jose"));
|
225
226
|
var LOGIN_PATH = "/api/auth/login";
|
@@ -237,11 +238,14 @@ var COOKIE_OPTIONS = {
|
|
237
238
|
path: "/"
|
238
239
|
};
|
239
240
|
function getAuthUrlOrigin() {
|
241
|
+
return getAuthUrl().origin;
|
242
|
+
}
|
243
|
+
function getAuthUrl() {
|
240
244
|
const authUrl = process.env.NEXT_PUBLIC_AUTH_URL;
|
241
245
|
if (!authUrl) {
|
242
246
|
throw new Error("NEXT_PUBLIC_AUTH_URL is not set");
|
243
247
|
}
|
244
|
-
return new URL(authUrl)
|
248
|
+
return new URL(authUrl);
|
245
249
|
}
|
246
250
|
function getRedirectUri() {
|
247
251
|
const redirectUri = process.env.PROPELAUTH_REDIRECT_URI;
|
@@ -370,6 +374,12 @@ function getUser() {
|
|
370
374
|
return void 0;
|
371
375
|
});
|
372
376
|
}
|
377
|
+
function getAccessToken() {
|
378
|
+
return __async(this, null, function* () {
|
379
|
+
var _a;
|
380
|
+
return (0, import_headers.headers)().get(CUSTOM_HEADER_FOR_ACCESS_TOKEN) || ((_a = (0, import_headers.cookies)().get(ACCESS_TOKEN_COOKIE_NAME)) == null ? void 0 : _a.value);
|
381
|
+
});
|
382
|
+
}
|
373
383
|
function authMiddleware(req) {
|
374
384
|
return __async(this, null, function* () {
|
375
385
|
var _a, _b;
|
@@ -523,18 +533,14 @@ function getRouteHandlers(args) {
|
|
523
533
|
}
|
524
534
|
});
|
525
535
|
if (response.ok) {
|
536
|
+
const userFromToken = yield validateAccessToken(accessToken);
|
526
537
|
const data = yield response.json();
|
527
|
-
const
|
528
|
-
data
|
529
|
-
|
530
|
-
|
531
|
-
|
532
|
-
|
533
|
-
data.username,
|
534
|
-
data.legacy_user_id,
|
535
|
-
data.impersonator_user_id
|
536
|
-
);
|
537
|
-
return new Response(JSON.stringify(user), {
|
538
|
+
const jsonResponse = {
|
539
|
+
userinfo: data,
|
540
|
+
accessToken,
|
541
|
+
impersonatorUserId: userFromToken.impersonatorUserId
|
542
|
+
};
|
543
|
+
return new Response(JSON.stringify(jsonResponse), {
|
538
544
|
status: 200,
|
539
545
|
headers: {
|
540
546
|
"Content-Type": "application/json"
|
@@ -616,6 +622,7 @@ function randomState() {
|
|
616
622
|
ConfigurationException,
|
617
623
|
UnauthorizedException,
|
618
624
|
authMiddleware,
|
625
|
+
getAccessToken,
|
619
626
|
getRouteHandlers,
|
620
627
|
getUser,
|
621
628
|
getUserOrRedirect
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"sources":["../../../src/server/app-router-index.ts","../../../src/server/exceptions.ts","../../../src/user.ts","../../../src/server/app-router.ts","../../../src/server/shared.ts"],"sourcesContent":["export {UnauthorizedException, ConfigurationException} from \"./exceptions\"\nexport {getRouteHandlers, getUser, getUserOrRedirect, authMiddleware} from \"./app-router\"\nexport type {RouteHandlerArgs} from \"./app-router\"\n","export class UnauthorizedException extends Error {\n readonly message: string\n readonly status: number\n\n constructor(message: string) {\n super(message)\n this.message = message\n this.status = 401\n }\n}\n\nexport class ConfigurationException extends Error {\n readonly message: string\n readonly status: number\n\n constructor(message: string) {\n super(message)\n this.message = message\n this.status = 500\n }\n}\n","export class User {\n public userId: string\n public orgIdToOrgMemberInfo?: OrgIdToOrgMemberInfo\n\n // Metadata about the user\n public email: string\n public firstName?: string\n public lastName?: string\n public username?: string\n\n // If you used our migration APIs to migrate this user from a different system,\n // this is their original ID from that system.\n public legacyUserId?: string\n public impersonatorUserId?: string\n\n constructor(\n userId: string,\n email: string,\n orgIdToOrgMemberInfo?: OrgIdToOrgMemberInfo,\n firstName?: string,\n lastName?: string,\n username?: string,\n legacyUserId?: string,\n impersonatorUserId?: string\n ) {\n this.userId = userId\n this.orgIdToOrgMemberInfo = orgIdToOrgMemberInfo\n\n this.email = email\n this.firstName = firstName\n this.lastName = lastName\n this.username = username\n\n this.legacyUserId = legacyUserId\n this.impersonatorUserId = impersonatorUserId\n }\n\n public getOrg(orgId: string): OrgMemberInfo | undefined {\n if (!this.orgIdToOrgMemberInfo) {\n return undefined\n }\n\n return this.orgIdToOrgMemberInfo[orgId]\n }\n\n public getOrgByName(orgName: string): OrgMemberInfo | undefined {\n if (!this.orgIdToOrgMemberInfo) {\n return undefined\n }\n\n const urlSafeOrgName = orgName.toLowerCase().replace(/ /g, \"-\")\n for (const orgId in this.orgIdToOrgMemberInfo) {\n const orgMemberInfo = this.orgIdToOrgMemberInfo[orgId]\n if (orgMemberInfo.urlSafeOrgName === urlSafeOrgName) {\n return orgMemberInfo\n }\n }\n\n return undefined\n }\n\n public getOrgs(): OrgMemberInfo[] {\n if (!this.orgIdToOrgMemberInfo) {\n return []\n }\n\n return Object.values(this.orgIdToOrgMemberInfo)\n }\n\n public isImpersonating(): boolean {\n return !!this.impersonatorUserId\n }\n\n public static fromJSON(json: string): User {\n const obj = JSON.parse(json)\n const orgIdToOrgMemberInfo: OrgIdToOrgMemberInfo = {}\n for (const orgId in obj.orgIdToOrgMemberInfo) {\n orgIdToOrgMemberInfo[orgId] = OrgMemberInfo.fromJSON(\n JSON.stringify(obj.orgIdToOrgMemberInfo[orgId])\n )\n }\n return new User(\n obj.userId,\n obj.email,\n orgIdToOrgMemberInfo,\n obj.firstName,\n obj.lastName,\n obj.username,\n obj.legacyUserId,\n obj.impersonatorUserId\n )\n }\n}\n\nexport type OrgIdToOrgMemberInfo = {\n [orgId: string]: OrgMemberInfo\n}\n\nexport class OrgMemberInfo {\n public orgId: string\n public orgName: string\n public orgMetadata: { [key: string]: any }\n public urlSafeOrgName: string\n\n private userAssignedRole: string\n private userInheritedRolesPlusCurrentRole: string[]\n private userPermissions: string[]\n\n constructor(\n orgId: string,\n orgName: string,\n orgMetadata: { [key: string]: any },\n urlSafeOrgName: string,\n userAssignedRole: string,\n userInheritedRolesPlusCurrentRole: string[],\n userPermissions: string[]\n ) {\n this.orgId = orgId\n this.orgName = orgName\n this.orgMetadata = orgMetadata\n this.urlSafeOrgName = urlSafeOrgName\n\n this.userAssignedRole = userAssignedRole\n this.userInheritedRolesPlusCurrentRole = userInheritedRolesPlusCurrentRole\n this.userPermissions = userPermissions\n }\n\n // validation methods\n\n public isRole(role: string): boolean {\n return this.userAssignedRole === role\n }\n\n public isAtLeastRole(role: string): boolean {\n return this.userInheritedRolesPlusCurrentRole.includes(role)\n }\n\n public hasPermission(permission: string): boolean {\n return this.userPermissions.includes(permission)\n }\n\n public hasAllPermissions(permissions: string[]): boolean {\n return permissions.every((permission) => this.hasPermission(permission))\n }\n\n public static fromJSON(json: string): OrgMemberInfo {\n const obj = JSON.parse(json)\n return new OrgMemberInfo(\n obj.orgId,\n obj.orgName,\n obj.orgMetadata,\n obj.urlSafeOrgName,\n obj.userAssignedRole,\n obj.userInheritedRolesPlusCurrentRole,\n obj.userPermissions\n )\n }\n\n // getters for the private fields\n\n get assignedRole(): string {\n return this.userAssignedRole\n }\n\n get inheritedRolesPlusCurrentRole(): string[] {\n return this.userInheritedRolesPlusCurrentRole\n }\n\n get permissions(): string[] {\n return this.userPermissions\n }\n}\n\n// These Internal types exist since the server returns snake case, but typescript/javascript\n// convention is camelCase.\nexport type InternalOrgMemberInfo = {\n org_id: string\n org_name: string\n org_metadata: { [key: string]: any }\n url_safe_org_name: string\n user_role: string\n inherited_user_roles_plus_current_role: string[]\n user_permissions: string[]\n}\nexport type InternalUser = {\n user_id: string\n org_id_to_org_member_info?: { [org_id: string]: InternalOrgMemberInfo }\n\n email: string\n first_name?: string\n last_name?: string\n username?: string\n\n // If you used our migration APIs to migrate this user from a different system, this is their original ID from that system.\n legacy_user_id?: string\n impersonatorUserId?: string\n}\n\nexport function toUser(snake_case: InternalUser): User {\n return new User(\n snake_case.user_id,\n snake_case.email,\n toOrgIdToOrgMemberInfo(snake_case.org_id_to_org_member_info),\n snake_case.first_name,\n snake_case.last_name,\n snake_case.username,\n snake_case.legacy_user_id,\n snake_case.impersonatorUserId\n )\n}\n\nexport function toOrgIdToOrgMemberInfo(snake_case?: {\n [org_id: string]: InternalOrgMemberInfo\n}): OrgIdToOrgMemberInfo | undefined {\n if (snake_case === undefined) {\n return undefined\n }\n const camelCase: OrgIdToOrgMemberInfo = {}\n\n for (const key of Object.keys(snake_case)) {\n const snakeCaseValue = snake_case[key]\n if (snakeCaseValue) {\n camelCase[key] = new OrgMemberInfo(\n snakeCaseValue.org_id,\n snakeCaseValue.org_name,\n snakeCaseValue.org_metadata,\n snakeCaseValue.url_safe_org_name,\n snakeCaseValue.user_role,\n snakeCaseValue.inherited_user_roles_plus_current_role,\n snakeCaseValue.user_permissions\n )\n }\n }\n\n return camelCase\n}\n","import {toOrgIdToOrgMemberInfo} from \"../user\";\nimport {redirect} from \"next/navigation\";\nimport {cookies, headers} from \"next/headers\";\nimport {NextRequest, NextResponse} from \"next/server\";\nimport {\n ACCESS_TOKEN_COOKIE_NAME,\n CALLBACK_PATH,\n COOKIE_OPTIONS,\n CUSTOM_HEADER_FOR_ACCESS_TOKEN,\n getAuthUrlOrigin,\n getIntegrationApiKey,\n getRedirectUri,\n LOGIN_PATH,\n LOGOUT_PATH,\n REFRESH_TOKEN_COOKIE_NAME,\n refreshTokenWithAccessAndRefreshToken,\n STATE_COOKIE_NAME,\n USERINFO_PATH,\n validateAccessTokenOrUndefined\n} from \"./shared\";\nimport {User} from \"./index\"\n\nexport async function getUserOrRedirect(): Promise<User> {\n const user = await getUser()\n if (user) {\n return user\n } else {\n redirect(LOGIN_PATH)\n throw new Error(\"Redirecting to login\")\n }\n}\n\nexport async function getUser(): Promise<User | undefined> {\n const accessToken = headers().get(CUSTOM_HEADER_FOR_ACCESS_TOKEN) || cookies().get(ACCESS_TOKEN_COOKIE_NAME)?.value\n if (accessToken) {\n const user = await validateAccessTokenOrUndefined(accessToken)\n if (user) {\n return user\n }\n }\n return undefined\n}\n\n// Purpose of this middleware is just to keep the access token cookie alive\n// In an ideal world, this could be done in `getUser`, however, you can't\n// set a cookie in a server component.\n// There also doesn't seem to be any way right now to set a cookie in a\n// middleware and pass it forward (you can only set them on the response).\n// You CAN, however, pass in custom headers,\n// so we'll use CUSTOM_HEADER_FOR_ACCESS_TOKEN as a workaround\nexport async function authMiddleware(req: NextRequest): Promise<Response> {\n if (req.headers.has(CUSTOM_HEADER_FOR_ACCESS_TOKEN)) {\n throw new Error(`${CUSTOM_HEADER_FOR_ACCESS_TOKEN} is set which is for internal use only`)\n } else if (req.nextUrl.pathname === CALLBACK_PATH || req.nextUrl.pathname === LOGOUT_PATH) {\n // Don't do anything for the callback or logout paths, as they will modify the cookies themselves\n return NextResponse.next()\n }\n\n const accessToken = req.cookies.get(ACCESS_TOKEN_COOKIE_NAME)?.value\n const refreshToken = req.cookies.get(REFRESH_TOKEN_COOKIE_NAME)?.value\n\n // For the userinfo endpoint, we want to get the most up-to-date info, so we'll refresh the access token\n if (req.nextUrl.pathname === USERINFO_PATH && refreshToken) {\n const response = await refreshTokenWithAccessAndRefreshToken(refreshToken)\n if (response.error === \"unexpected\") {\n throw new Error(\"Unexpected error while refreshing access token\")\n } else if (response.error === \"unauthorized\") {\n const headers = new Headers()\n headers.append(\"Set-Cookie\", `${ACCESS_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`)\n headers.append(\"Set-Cookie\", `${REFRESH_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`)\n return new Response(\"Unauthorized\", {status: 401, headers})\n } else {\n const headers = new Headers(req.headers)\n // Pass along the new access token in a header since cookies don't work\n headers.append(CUSTOM_HEADER_FOR_ACCESS_TOKEN, response.accessToken)\n const nextResponse = NextResponse.next({\n request: {\n headers\n }\n })\n nextResponse.cookies.set(ACCESS_TOKEN_COOKIE_NAME, response.accessToken, COOKIE_OPTIONS)\n nextResponse.cookies.set(REFRESH_TOKEN_COOKIE_NAME, response.refreshToken, COOKIE_OPTIONS)\n return nextResponse\n }\n }\n\n // If we are authenticated, we can continue\n if (accessToken) {\n const user = await validateAccessTokenOrUndefined(accessToken)\n if (user) {\n return NextResponse.next()\n }\n }\n\n // Otherwise, we need to refresh the access token\n if (refreshToken) {\n const response = await refreshTokenWithAccessAndRefreshToken(refreshToken)\n if (response.error === \"unexpected\") {\n throw new Error(\"Unexpected error while refreshing access token\")\n } else if (response.error === \"unauthorized\") {\n const response = NextResponse.next()\n response.cookies.delete(ACCESS_TOKEN_COOKIE_NAME)\n response.cookies.delete(REFRESH_TOKEN_COOKIE_NAME)\n return response\n } else {\n const headers = new Headers(req.headers)\n // Pass along the new access token in a header since cookies don't work\n headers.append(CUSTOM_HEADER_FOR_ACCESS_TOKEN, response.accessToken)\n const nextResponse = NextResponse.next({\n request: {\n headers\n }\n })\n nextResponse.cookies.set(ACCESS_TOKEN_COOKIE_NAME, response.accessToken, COOKIE_OPTIONS)\n nextResponse.cookies.set(REFRESH_TOKEN_COOKIE_NAME, response.refreshToken, COOKIE_OPTIONS)\n return nextResponse\n }\n }\n\n return NextResponse.next()\n}\n\nexport type RouteHandlerArgs = {\n postLoginRedirectPathFn?: (req: NextRequest) => string\n}\n\nexport function getRouteHandlers(args?: RouteHandlerArgs) {\n const authUrlOrigin = getAuthUrlOrigin()\n const redirectUri = getRedirectUri()\n const integrationApiKey = getIntegrationApiKey()\n\n function loginGetHandler() {\n const state = randomState()\n const authorize_url =\n authUrlOrigin + \"/propelauth/ssr/authorize?redirect_uri=\" + redirectUri + \"&state=\" + state\n return new Response(null, {\n status: 302,\n headers: {\n Location: authorize_url,\n \"Set-Cookie\": `${STATE_COOKIE_NAME}=${state}; Path=/; HttpOnly; Secure; SameSite=Lax`,\n }\n })\n }\n\n function signupGetHandler() {\n const state = randomState()\n const authorize_url =\n getAuthUrlOrigin() + \"/propelauth/ssr/authorize?redirect_uri=\" + redirectUri + \"&state=\" + state + \"&signup=true\"\n return new Response(null, {\n status: 302,\n headers: {\n Location: authorize_url,\n \"Set-Cookie\": `${STATE_COOKIE_NAME}=${state}; Path=/; HttpOnly; Secure; SameSite=Lax`,\n }\n })\n }\n\n async function callbackGetHandler(req: NextRequest) {\n const oauthState = req.cookies.get(STATE_COOKIE_NAME)?.value\n if (!oauthState || oauthState.length !== 64) {\n console.log(\"No oauth state found\")\n return new Response(null, {status: 302, headers: {Location: LOGIN_PATH}})\n }\n\n const queryParams = req.nextUrl.searchParams\n const state = queryParams.get(\"state\")\n const code = queryParams.get(\"code\")\n if (state !== oauthState) {\n console.log(\"Mismatch between states, redirecting to login\")\n return new Response(null, {status: 302, headers: {Location: LOGIN_PATH}})\n }\n\n const oauth_token_body = {\n redirect_uri: redirectUri,\n code,\n }\n const url = `${authUrlOrigin}/propelauth/ssr/token`\n const response = await fetch(url, {\n method: \"POST\",\n body: JSON.stringify(oauth_token_body),\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: \"Bearer \" + integrationApiKey,\n },\n })\n\n if (response.ok) {\n const data = await response.json()\n\n const accessToken = data.access_token\n const path = args?.postLoginRedirectPathFn ? args.postLoginRedirectPathFn(req) : \"/\"\n if (!path) {\n console.log(\"postLoginPathFn returned undefined\")\n return new Response(\"Unexpected error\", {status: 500})\n }\n\n const headers = new Headers()\n headers.append(\"Location\", path)\n headers.append(\"Set-Cookie\", `${ACCESS_TOKEN_COOKIE_NAME}=${accessToken}; Path=/; HttpOnly; Secure; SameSite=Lax`)\n headers.append(\"Set-Cookie\", `${REFRESH_TOKEN_COOKIE_NAME}=${data.refresh_token}; Path=/; HttpOnly; Secure; SameSite=Lax`)\n return new Response(null, {\n status: 302,\n headers\n })\n } else if (response.status === 401) {\n return new Response(\"Unexpected error\", {status: 500})\n } else {\n return new Response(\"Unexpected error\", {status: 500})\n }\n }\n\n async function userinfoGetHandler(req: NextRequest) {\n const accessToken = req.headers.get(CUSTOM_HEADER_FOR_ACCESS_TOKEN) || req.cookies.get(ACCESS_TOKEN_COOKIE_NAME)?.value\n if (accessToken) {\n const path = `${authUrlOrigin}/propelauth/oauth/userinfo`\n const response = await fetch(path, {\n headers: {\n \"Content-Type\": \"application/json\",\n \"Authorization\": \"Bearer \" + accessToken,\n }\n })\n if (response.ok) {\n const data = await response.json()\n\n const user = new User(\n data.user_id,\n data.email,\n toOrgIdToOrgMemberInfo(data.org_id_to_org_info),\n data.first_name,\n data.last_name,\n data.username,\n data.legacy_user_id,\n data.impersonator_user_id,\n )\n\n return new Response(JSON.stringify(user), {\n status: 200,\n headers: {\n \"Content-Type\": \"application/json\",\n }\n })\n } else if (response.status === 401) {\n return new Response(null, {status: 401})\n } else {\n return new Response(null, {status: 500})\n }\n }\n return new Response(null, {status: 401})\n }\n\n async function logoutPostHandler(req: NextRequest) {\n const refresh_token = req.cookies.get(REFRESH_TOKEN_COOKIE_NAME)?.value\n if (!refresh_token) {\n const headers = new Headers()\n headers.append(\"Set-Cookie\", `${ACCESS_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`)\n headers.append(\"Set-Cookie\", `${REFRESH_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`)\n return new Response(null, {status: 200, headers})\n }\n\n const logoutBody = {refresh_token}\n const url = `${authUrlOrigin}/api/backend/v1/logout`\n const response = await fetch(url, {\n method: \"POST\",\n body: JSON.stringify(logoutBody),\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: \"Bearer \" + integrationApiKey,\n },\n })\n\n if (!response.ok) {\n console.log(\n \"Unable to logout, clearing cookies and continuing anyway\",\n response.status,\n response.statusText\n )\n }\n const headers = new Headers()\n headers.append(\"Set-Cookie\", `${ACCESS_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`)\n headers.append(\"Set-Cookie\", `${REFRESH_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`)\n return new Response(null, {status: 200, headers})\n }\n\n function getRouteHandler(req: NextRequest, {params}: { params: { slug: string } }) {\n if (params.slug === \"login\") {\n return loginGetHandler()\n } else if (params.slug === \"signup\") {\n return signupGetHandler()\n } else if (params.slug === \"callback\") {\n return callbackGetHandler(req)\n } else if (params.slug === \"userinfo\") {\n return userinfoGetHandler(req)\n } else {\n return new Response(\"\", {status: 404})\n }\n }\n\n function postRouteHandler(req: NextRequest, {params}: { params: { slug: string } }) {\n if (params.slug === \"logout\") {\n return logoutPostHandler(req)\n } else {\n return new Response(\"\", {status: 404})\n }\n }\n\n return {\n getRouteHandler,\n postRouteHandler\n }\n}\n\nfunction randomState(): string {\n const randomBytes = crypto.getRandomValues(new Uint8Array(32))\n return Array.from(randomBytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\")\n}\n\n","import {ResponseCookie} from \"next/dist/compiled/@edge-runtime/cookies\";\nimport {InternalUser, toUser, User} from \"../user\";\nimport {ConfigurationException, UnauthorizedException} from \"./exceptions\";\nimport * as jose from \"jose\";\n\ntype RefreshAndAccessTokens = {\n refreshToken: string\n accessToken: string\n error: \"none\"\n}\n\ntype RefreshAndAccessTokensUnauthorizedError = {\n error: \"unauthorized\"\n}\n\ntype RefreshAndAccessTokensUnexpectedError = {\n error: \"unexpected\"\n}\n\nexport type RefreshTokenResponse =\n RefreshAndAccessTokens\n | RefreshAndAccessTokensUnauthorizedError\n | RefreshAndAccessTokensUnexpectedError\n\nexport const LOGIN_PATH = \"/api/auth/login\"\nexport const CALLBACK_PATH = \"/api/auth/callback\"\nexport const USERINFO_PATH = \"/api/auth/userinfo\"\nexport const LOGOUT_PATH = \"/api/auth/logout\"\nexport const ACCESS_TOKEN_COOKIE_NAME = \"__pa_at\"\nexport const REFRESH_TOKEN_COOKIE_NAME = \"__pa_rt\"\nexport const STATE_COOKIE_NAME = \"__pa_state\"\nexport const CUSTOM_HEADER_FOR_ACCESS_TOKEN = \"x-propelauth-access-token\"\n\nexport const COOKIE_OPTIONS: Partial<ResponseCookie> = {\n httpOnly: true,\n sameSite: \"lax\",\n secure: true,\n path: \"/\",\n}\n\nexport function getAuthUrlOrigin() {\n const authUrl = process.env.NEXT_PUBLIC_AUTH_URL\n if (!authUrl) {\n throw new Error(\"NEXT_PUBLIC_AUTH_URL is not set\")\n }\n return new URL(authUrl).origin\n}\n\nexport function getRedirectUri() {\n const redirectUri = process.env.PROPELAUTH_REDIRECT_URI\n if (!redirectUri) {\n throw new Error(\"PROPELAUTH_REDIRECT_URI is not set\")\n }\n return redirectUri\n}\n\nexport function getIntegrationApiKey() {\n const integrationApiKey = process.env.PROPELAUTH_API_KEY\n if (!integrationApiKey) {\n throw new Error(\"PROPELAUTH_API_KEY is not set\")\n }\n return integrationApiKey\n}\n\nexport function getVerifierKey() {\n const verifierKey = process.env.PROPELAUTH_VERIFIER_KEY\n if (!verifierKey) {\n throw new Error(\"PROPELAUTH_VERIFIER_KEY is not set\")\n }\n return verifierKey.replace(/\\\\n/g, \"\\n\")\n}\n\nexport async function refreshTokenWithAccessAndRefreshToken(refreshToken: string): Promise<RefreshTokenResponse> {\n const body = {\n refresh_token: refreshToken,\n }\n const url = `${getAuthUrlOrigin()}/api/backend/v1/refresh_token`\n const response = await fetch(url, {\n method: \"POST\",\n body: JSON.stringify(body),\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: \"Bearer \" + getIntegrationApiKey(),\n },\n })\n\n if (response.ok) {\n const data = await response.json()\n const newRefreshToken = data.refresh_token\n const {\n access_token: accessToken,\n expires_at_seconds: expiresAtSeconds,\n } = data.access_token\n\n return {\n refreshToken: newRefreshToken,\n accessToken,\n error: \"none\",\n }\n } else if (response.status === 400) {\n return {error: \"unauthorized\"}\n } else {\n return {error: \"unexpected\"}\n }\n}\n\nexport async function validateAccessTokenOrUndefined(accessToken: string | undefined): Promise<User | undefined> {\n try {\n return await validateAccessToken(accessToken)\n } catch (err) {\n if (err instanceof ConfigurationException) {\n throw err\n } else if (err instanceof UnauthorizedException) {\n return undefined\n } else {\n console.log(\"Error validating access token\", err)\n return undefined\n }\n }\n}\n\nexport async function validateAccessToken(accessToken: string | undefined): Promise<User> {\n let publicKey\n try {\n publicKey = await jose.importSPKI(getVerifierKey(), \"RS256\")\n } catch (err) {\n console.error(\"Verifier key is invalid. Make sure it's specified correctly, including the newlines.\", err)\n throw new ConfigurationException(\"Invalid verifier key\")\n }\n\n if (!accessToken) {\n throw new UnauthorizedException(\"No access token provided\")\n }\n\n let accessTokenWithoutBearer = accessToken\n if (accessToken.toLowerCase().startsWith(\"bearer \")) {\n accessTokenWithoutBearer = accessToken.substring(\"bearer \".length)\n }\n\n try {\n const {payload} = await jose.jwtVerify(accessTokenWithoutBearer, publicKey, {\n issuer: getAuthUrlOrigin(),\n algorithms: [\"RS256\"],\n })\n\n return toUser(<InternalUser>payload)\n } catch (e) {\n if (e instanceof Error) {\n throw new UnauthorizedException(e.message)\n } else {\n throw new UnauthorizedException(\"Unable to decode jwt\")\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAO,IAAM,wBAAN,cAAoC,MAAM;AAAA,EAI7C,YAAY,SAAiB;AACzB,UAAM,OAAO;AACb,SAAK,UAAU;AACf,SAAK,SAAS;AAAA,EAClB;AACJ;AAEO,IAAM,yBAAN,cAAqC,MAAM;AAAA,EAI9C,YAAY,SAAiB;AACzB,UAAM,OAAO;AACb,SAAK,UAAU;AACf,SAAK,SAAS;AAAA,EAClB;AACJ;;;ACpBO,IAAM,OAAN,MAAW;AAAA,EAed,YACI,QACA,OACA,sBACA,WACA,UACA,UACA,cACA,o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AG;AAAA,IAChC,OAAO;AACH,aAAO,IAAI,SAAS,IAAI,EAAC,QAAQ,IAAG,CAAC;AAAA,IACzC;AAAA,EACJ;AAEA,SAAO;AAAA,IACH;AAAA,IACA;AAAA,EACJ;AACJ;AAEA,SAAS,cAAsB;AAC3B,QAAM,cAAc,OAAO,gBAAgB,IAAI,WAAW,EAAE,CAAC;AAC7D,SAAO,MAAM,KAAK,WAAW,EACxB,IAAI,CAAC,MAAM,EAAE,SAAS,EAAE,EAAE,SAAS,GAAG,GAAG,CAAC,EAC1C,KAAK,EAAE;AAChB;","names":["headers","response"]}
|
1
|
+
{"version":3,"sources":["../../../src/server/app-router-index.ts","../../../src/server/exceptions.ts","../../../src/server/app-router.ts","../../../src/user.ts","../../../src/server/shared.ts"],"sourcesContent":["export {UnauthorizedException, ConfigurationException} from \"./exceptions\"\nexport {getRouteHandlers, getUser, getUserOrRedirect, getAccessToken, authMiddleware} from \"./app-router\"\nexport type {RouteHandlerArgs} from \"./app-router\"\n","export class UnauthorizedException extends Error {\n readonly message: string\n readonly status: number\n\n constructor(message: string) {\n super(message)\n this.message = message\n this.status = 401\n }\n}\n\nexport class ConfigurationException extends Error {\n readonly message: string\n readonly status: number\n\n constructor(message: string) {\n super(message)\n this.message = message\n this.status = 500\n }\n}\n","import {redirect} from \"next/navigation\";\nimport {cookies, headers} from \"next/headers\";\nimport {NextRequest, NextResponse} from \"next/server\";\nimport {\n ACCESS_TOKEN_COOKIE_NAME,\n CALLBACK_PATH,\n COOKIE_OPTIONS,\n CUSTOM_HEADER_FOR_ACCESS_TOKEN,\n getAuthUrlOrigin,\n getIntegrationApiKey,\n getRedirectUri,\n LOGIN_PATH,\n LOGOUT_PATH,\n REFRESH_TOKEN_COOKIE_NAME,\n refreshTokenWithAccessAndRefreshToken,\n STATE_COOKIE_NAME,\n USERINFO_PATH,\n validateAccessToken,\n validateAccessTokenOrUndefined\n} from \"./shared\";\nimport {UserFromToken} from \"./index\"\n\nexport async function getUserOrRedirect(): Promise<UserFromToken> {\n const user = await getUser()\n if (user) {\n return user\n } else {\n redirect(LOGIN_PATH)\n throw new Error(\"Redirecting to login\")\n }\n}\n\nexport async function getUser(): Promise<UserFromToken | undefined> {\n const accessToken = headers().get(CUSTOM_HEADER_FOR_ACCESS_TOKEN) || cookies().get(ACCESS_TOKEN_COOKIE_NAME)?.value\n if (accessToken) {\n const user = await validateAccessTokenOrUndefined(accessToken)\n if (user) {\n return user\n }\n }\n return undefined\n}\n\nexport async function getAccessToken(): Promise<string | undefined> {\n return headers().get(CUSTOM_HEADER_FOR_ACCESS_TOKEN) || cookies().get(ACCESS_TOKEN_COOKIE_NAME)?.value\n}\n\n// Purpose of this middleware is just to keep the access token cookie alive\n// In an ideal world, this could be done in `getUser`, however, you can't\n// set a cookie in a server component.\n// There also doesn't seem to be any way right now to set a cookie in a\n// middleware and pass it forward (you can only set them on the response).\n// You CAN, however, pass in custom headers,\n// so we'll use CUSTOM_HEADER_FOR_ACCESS_TOKEN as a workaround\nexport async function authMiddleware(req: NextRequest): Promise<Response> {\n if (req.headers.has(CUSTOM_HEADER_FOR_ACCESS_TOKEN)) {\n throw new Error(`${CUSTOM_HEADER_FOR_ACCESS_TOKEN} is set which is for internal use only`)\n } else if (req.nextUrl.pathname === CALLBACK_PATH || req.nextUrl.pathname === LOGOUT_PATH) {\n // Don't do anything for the callback or logout paths, as they will modify the cookies themselves\n return NextResponse.next()\n }\n\n const accessToken = req.cookies.get(ACCESS_TOKEN_COOKIE_NAME)?.value\n const refreshToken = req.cookies.get(REFRESH_TOKEN_COOKIE_NAME)?.value\n\n // For the userinfo endpoint, we want to get the most up-to-date info, so we'll refresh the access token\n if (req.nextUrl.pathname === USERINFO_PATH && refreshToken) {\n const response = await refreshTokenWithAccessAndRefreshToken(refreshToken)\n if (response.error === \"unexpected\") {\n throw new Error(\"Unexpected error while refreshing access token\")\n } else if (response.error === \"unauthorized\") {\n const headers = new Headers()\n headers.append(\"Set-Cookie\", `${ACCESS_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`)\n headers.append(\"Set-Cookie\", `${REFRESH_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`)\n return new Response(\"Unauthorized\", {status: 401, headers})\n } else {\n const headers = new Headers(req.headers)\n // Pass along the new access token in a header since cookies don't work\n headers.append(CUSTOM_HEADER_FOR_ACCESS_TOKEN, response.accessToken)\n const nextResponse = NextResponse.next({\n request: {\n headers\n }\n })\n nextResponse.cookies.set(ACCESS_TOKEN_COOKIE_NAME, response.accessToken, COOKIE_OPTIONS)\n nextResponse.cookies.set(REFRESH_TOKEN_COOKIE_NAME, response.refreshToken, COOKIE_OPTIONS)\n return nextResponse\n }\n }\n\n // If we are authenticated, we can continue\n if (accessToken) {\n const user = await validateAccessTokenOrUndefined(accessToken)\n if (user) {\n return NextResponse.next()\n }\n }\n\n // Otherwise, we need to refresh the access token\n if (refreshToken) {\n const response = await refreshTokenWithAccessAndRefreshToken(refreshToken)\n if (response.error === \"unexpected\") {\n throw new Error(\"Unexpected error while refreshing access token\")\n } else if (response.error === \"unauthorized\") {\n const response = NextResponse.next()\n response.cookies.delete(ACCESS_TOKEN_COOKIE_NAME)\n response.cookies.delete(REFRESH_TOKEN_COOKIE_NAME)\n return response\n } else {\n const headers = new Headers(req.headers)\n // Pass along the new access token in a header since cookies don't work\n headers.append(CUSTOM_HEADER_FOR_ACCESS_TOKEN, response.accessToken)\n const nextResponse = NextResponse.next({\n request: {\n headers\n }\n })\n nextResponse.cookies.set(ACCESS_TOKEN_COOKIE_NAME, response.accessToken, COOKIE_OPTIONS)\n nextResponse.cookies.set(REFRESH_TOKEN_COOKIE_NAME, response.refreshToken, COOKIE_OPTIONS)\n return nextResponse\n }\n }\n\n return NextResponse.next()\n}\n\nexport type RouteHandlerArgs = {\n postLoginRedirectPathFn?: (req: NextRequest) => string\n}\n\nexport function getRouteHandlers(args?: RouteHandlerArgs) {\n const authUrlOrigin = getAuthUrlOrigin()\n const redirectUri = getRedirectUri()\n const integrationApiKey = getIntegrationApiKey()\n\n function loginGetHandler() {\n const state = randomState()\n const authorize_url =\n authUrlOrigin + \"/propelauth/ssr/authorize?redirect_uri=\" + redirectUri + \"&state=\" + state\n return new Response(null, {\n status: 302,\n headers: {\n Location: authorize_url,\n \"Set-Cookie\": `${STATE_COOKIE_NAME}=${state}; Path=/; HttpOnly; Secure; SameSite=Lax`,\n }\n })\n }\n\n function signupGetHandler() {\n const state = randomState()\n const authorize_url =\n getAuthUrlOrigin() + \"/propelauth/ssr/authorize?redirect_uri=\" + redirectUri + \"&state=\" + state + \"&signup=true\"\n return new Response(null, {\n status: 302,\n headers: {\n Location: authorize_url,\n \"Set-Cookie\": `${STATE_COOKIE_NAME}=${state}; Path=/; HttpOnly; Secure; SameSite=Lax`,\n }\n })\n }\n\n async function callbackGetHandler(req: NextRequest) {\n const oauthState = req.cookies.get(STATE_COOKIE_NAME)?.value\n if (!oauthState || oauthState.length !== 64) {\n console.log(\"No oauth state found\")\n return new Response(null, {status: 302, headers: {Location: LOGIN_PATH}})\n }\n\n const queryParams = req.nextUrl.searchParams\n const state = queryParams.get(\"state\")\n const code = queryParams.get(\"code\")\n if (state !== oauthState) {\n console.log(\"Mismatch between states, redirecting to login\")\n return new Response(null, {status: 302, headers: {Location: LOGIN_PATH}})\n }\n\n const oauth_token_body = {\n redirect_uri: redirectUri,\n code,\n }\n const url = `${authUrlOrigin}/propelauth/ssr/token`\n const response = await fetch(url, {\n method: \"POST\",\n body: JSON.stringify(oauth_token_body),\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: \"Bearer \" + integrationApiKey,\n },\n })\n\n if (response.ok) {\n const data = await response.json()\n\n const accessToken = data.access_token\n const path = args?.postLoginRedirectPathFn ? args.postLoginRedirectPathFn(req) : \"/\"\n if (!path) {\n console.log(\"postLoginPathFn returned undefined\")\n return new Response(\"Unexpected error\", {status: 500})\n }\n\n const headers = new Headers()\n headers.append(\"Location\", path)\n headers.append(\"Set-Cookie\", `${ACCESS_TOKEN_COOKIE_NAME}=${accessToken}; Path=/; HttpOnly; Secure; SameSite=Lax`)\n headers.append(\"Set-Cookie\", `${REFRESH_TOKEN_COOKIE_NAME}=${data.refresh_token}; Path=/; HttpOnly; Secure; SameSite=Lax`)\n return new Response(null, {\n status: 302,\n headers\n })\n } else if (response.status === 401) {\n return new Response(\"Unexpected error\", {status: 500})\n } else {\n return new Response(\"Unexpected error\", {status: 500})\n }\n }\n\n async function userinfoGetHandler(req: NextRequest) {\n const accessToken = req.headers.get(CUSTOM_HEADER_FOR_ACCESS_TOKEN) || req.cookies.get(ACCESS_TOKEN_COOKIE_NAME)?.value\n if (accessToken) {\n const path = `${authUrlOrigin}/propelauth/oauth/userinfo`\n const response = await fetch(path, {\n headers: {\n \"Content-Type\": \"application/json\",\n \"Authorization\": \"Bearer \" + accessToken,\n }\n })\n if (response.ok) {\n const userFromToken = await validateAccessToken(accessToken)\n const data = await response.json()\n const jsonResponse = {\n userinfo: data,\n accessToken,\n impersonatorUserId: userFromToken.impersonatorUserId\n }\n return new Response(JSON.stringify(jsonResponse), {\n status: 200,\n headers: {\n \"Content-Type\": \"application/json\",\n }\n })\n } else if (response.status === 401) {\n return new Response(null, {status: 401})\n } else {\n return new Response(null, {status: 500})\n }\n }\n return new Response(null, {status: 401})\n }\n\n async function logoutPostHandler(req: NextRequest) {\n const refresh_token = req.cookies.get(REFRESH_TOKEN_COOKIE_NAME)?.value\n if (!refresh_token) {\n const headers = new Headers()\n headers.append(\"Set-Cookie\", `${ACCESS_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`)\n headers.append(\"Set-Cookie\", `${REFRESH_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`)\n return new Response(null, {status: 200, headers})\n }\n\n const logoutBody = {refresh_token}\n const url = `${authUrlOrigin}/api/backend/v1/logout`\n const response = await fetch(url, {\n method: \"POST\",\n body: JSON.stringify(logoutBody),\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: \"Bearer \" + integrationApiKey,\n },\n })\n\n if (!response.ok) {\n console.log(\n \"Unable to logout, clearing cookies and continuing anyway\",\n response.status,\n response.statusText\n )\n }\n const headers = new Headers()\n headers.append(\"Set-Cookie\", `${ACCESS_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`)\n headers.append(\"Set-Cookie\", `${REFRESH_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`)\n return new Response(null, {status: 200, headers})\n }\n\n function getRouteHandler(req: NextRequest, {params}: { params: { slug: string } }) {\n if (params.slug === \"login\") {\n return loginGetHandler()\n } else if (params.slug === \"signup\") {\n return signupGetHandler()\n } else if (params.slug === \"callback\") {\n return callbackGetHandler(req)\n } else if (params.slug === \"userinfo\") {\n return userinfoGetHandler(req)\n } else {\n return new Response(\"\", {status: 404})\n }\n }\n\n function postRouteHandler(req: NextRequest, {params}: { params: { slug: string } }) {\n if (params.slug === \"logout\") {\n return logoutPostHandler(req)\n } else {\n return new Response(\"\", {status: 404})\n }\n }\n\n return {\n getRouteHandler,\n postRouteHandler\n }\n}\n\nfunction randomState(): string {\n const randomBytes = crypto.getRandomValues(new Uint8Array(32))\n return Array.from(randomBytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\")\n}\n\n","export class UserFromToken {\n public userId: string\n public orgIdToOrgMemberInfo?: OrgIdToOrgMemberInfo\n\n // Metadata about the user\n public email: string\n public firstName?: string\n public lastName?: string\n public username?: string\n\n // If you used our migration APIs to migrate this user from a different system,\n // this is their original ID from that system.\n public legacyUserId?: string\n public impersonatorUserId?: string\n\n constructor(\n userId: string,\n email: string,\n orgIdToOrgMemberInfo?: OrgIdToOrgMemberInfo,\n firstName?: string,\n lastName?: string,\n username?: string,\n legacyUserId?: string,\n impersonatorUserId?: string\n ) {\n this.userId = userId\n this.orgIdToOrgMemberInfo = orgIdToOrgMemberInfo\n\n this.email = email\n this.firstName = firstName\n this.lastName = lastName\n this.username = username\n\n this.legacyUserId = legacyUserId\n this.impersonatorUserId = impersonatorUserId\n }\n\n public getOrg(orgId: string): OrgMemberInfo | undefined {\n if (!this.orgIdToOrgMemberInfo) {\n return undefined\n }\n\n return this.orgIdToOrgMemberInfo[orgId]\n }\n\n public getOrgByName(orgName: string): OrgMemberInfo | undefined {\n if (!this.orgIdToOrgMemberInfo) {\n return undefined\n }\n\n const urlSafeOrgName = orgName.toLowerCase().replace(/ /g, \"-\")\n for (const orgId in this.orgIdToOrgMemberInfo) {\n const orgMemberInfo = this.orgIdToOrgMemberInfo[orgId]\n if (orgMemberInfo.urlSafeOrgName === urlSafeOrgName) {\n return orgMemberInfo\n }\n }\n\n return undefined\n }\n\n public getOrgs(): OrgMemberInfo[] {\n if (!this.orgIdToOrgMemberInfo) {\n return []\n }\n\n return Object.values(this.orgIdToOrgMemberInfo)\n }\n\n public isImpersonating(): boolean {\n return !!this.impersonatorUserId\n }\n\n public static fromJSON(json: string): UserFromToken {\n const obj = JSON.parse(json)\n const orgIdToOrgMemberInfo: OrgIdToOrgMemberInfo = {}\n for (const orgId in obj.orgIdToOrgMemberInfo) {\n orgIdToOrgMemberInfo[orgId] = OrgMemberInfo.fromJSON(\n JSON.stringify(obj.orgIdToOrgMemberInfo[orgId])\n )\n }\n return new UserFromToken(\n obj.userId,\n obj.email,\n orgIdToOrgMemberInfo,\n obj.firstName,\n obj.lastName,\n obj.username,\n obj.legacyUserId,\n obj.impersonatorUserId\n )\n }\n}\n\nexport type OrgIdToOrgMemberInfo = {\n [orgId: string]: OrgMemberInfo\n}\n\nexport class OrgMemberInfo {\n public orgId: string\n public orgName: string\n public orgMetadata: { [key: string]: any }\n public urlSafeOrgName: string\n\n private userAssignedRole: string\n private userInheritedRolesPlusCurrentRole: string[]\n private userPermissions: string[]\n\n constructor(\n orgId: string,\n orgName: string,\n orgMetadata: { [key: string]: any },\n urlSafeOrgName: string,\n userAssignedRole: string,\n userInheritedRolesPlusCurrentRole: string[],\n userPermissions: string[]\n ) {\n this.orgId = orgId\n this.orgName = orgName\n this.orgMetadata = orgMetadata\n this.urlSafeOrgName = urlSafeOrgName\n\n this.userAssignedRole = userAssignedRole\n this.userInheritedRolesPlusCurrentRole = userInheritedRolesPlusCurrentRole\n this.userPermissions = userPermissions\n }\n\n // validation methods\n\n public isRole(role: string): boolean {\n return this.userAssignedRole === role\n }\n\n public isAtLeastRole(role: string): boolean {\n return this.userInheritedRolesPlusCurrentRole.includes(role)\n }\n\n public hasPermission(permission: string): boolean {\n return this.userPermissions.includes(permission)\n }\n\n public hasAllPermissions(permissions: string[]): boolean {\n return permissions.every((permission) => this.hasPermission(permission))\n }\n\n public static fromJSON(json: string): OrgMemberInfo {\n const obj = JSON.parse(json)\n return new OrgMemberInfo(\n obj.orgId,\n obj.orgName,\n obj.orgMetadata,\n obj.urlSafeOrgName,\n obj.userAssignedRole,\n obj.userInheritedRolesPlusCurrentRole,\n obj.userPermissions\n )\n }\n\n // getters for the private fields\n\n get assignedRole(): string {\n return this.userAssignedRole\n }\n\n get inheritedRolesPlusCurrentRole(): string[] {\n return this.userInheritedRolesPlusCurrentRole\n }\n\n get permissions(): string[] {\n return this.userPermissions\n }\n}\n\n// These Internal types exist since the server returns snake case, but typescript/javascript\n// convention is camelCase.\nexport type InternalOrgMemberInfo = {\n org_id: string\n org_name: string\n org_metadata: { [key: string]: any }\n url_safe_org_name: string\n user_role: string\n inherited_user_roles_plus_current_role: string[]\n user_permissions: string[]\n}\nexport type InternalUser = {\n user_id: string\n org_id_to_org_member_info?: { [org_id: string]: InternalOrgMemberInfo }\n\n email: string\n first_name?: string\n last_name?: string\n username?: string\n\n // If you used our migration APIs to migrate this user from a different system, this is their original ID from that system.\n legacy_user_id?: string\n impersonatorUserId?: string\n}\n\nexport function toUser(snake_case: InternalUser): UserFromToken {\n return new UserFromToken(\n snake_case.user_id,\n snake_case.email,\n toOrgIdToOrgMemberInfo(snake_case.org_id_to_org_member_info),\n snake_case.first_name,\n snake_case.last_name,\n snake_case.username,\n snake_case.legacy_user_id,\n snake_case.impersonatorUserId\n )\n}\n\nexport function toOrgIdToOrgMemberInfo(snake_case?: {\n [org_id: string]: InternalOrgMemberInfo\n}): OrgIdToOrgMemberInfo | undefined {\n if (snake_case === undefined) {\n return undefined\n }\n const camelCase: OrgIdToOrgMemberInfo = {}\n\n for (const key of Object.keys(snake_case)) {\n const snakeCaseValue = snake_case[key]\n if (snakeCaseValue) {\n camelCase[key] = new OrgMemberInfo(\n snakeCaseValue.org_id,\n snakeCaseValue.org_name,\n snakeCaseValue.org_metadata,\n snakeCaseValue.url_safe_org_name,\n snakeCaseValue.user_role,\n snakeCaseValue.inherited_user_roles_plus_current_role,\n snakeCaseValue.user_permissions\n )\n }\n }\n\n return camelCase\n}\n","import {ResponseCookie} from \"next/dist/compiled/@edge-runtime/cookies\";\nimport {InternalUser, toUser, UserFromToken} from \"../user\";\nimport {ConfigurationException, UnauthorizedException} from \"./exceptions\";\nimport * as jose from \"jose\";\n\ntype RefreshAndAccessTokens = {\n refreshToken: string\n accessToken: string\n error: \"none\"\n}\n\ntype RefreshAndAccessTokensUnauthorizedError = {\n error: \"unauthorized\"\n}\n\ntype RefreshAndAccessTokensUnexpectedError = {\n error: \"unexpected\"\n}\n\nexport type RefreshTokenResponse =\n RefreshAndAccessTokens\n | RefreshAndAccessTokensUnauthorizedError\n | RefreshAndAccessTokensUnexpectedError\n\nexport const LOGIN_PATH = \"/api/auth/login\"\nexport const CALLBACK_PATH = \"/api/auth/callback\"\nexport const USERINFO_PATH = \"/api/auth/userinfo\"\nexport const LOGOUT_PATH = \"/api/auth/logout\"\nexport const ACCESS_TOKEN_COOKIE_NAME = \"__pa_at\"\nexport const REFRESH_TOKEN_COOKIE_NAME = \"__pa_rt\"\nexport const STATE_COOKIE_NAME = \"__pa_state\"\nexport const CUSTOM_HEADER_FOR_ACCESS_TOKEN = \"x-propelauth-access-token\"\n\nexport const COOKIE_OPTIONS: Partial<ResponseCookie> = {\n httpOnly: true,\n sameSite: \"lax\",\n secure: true,\n path: \"/\",\n}\n\nexport function getAuthUrlOrigin() {\n return getAuthUrl().origin\n}\n\nexport function getAuthUrl() {\n const authUrl = process.env.NEXT_PUBLIC_AUTH_URL\n if (!authUrl) {\n throw new Error(\"NEXT_PUBLIC_AUTH_URL is not set\")\n }\n return new URL(authUrl)\n}\n\nexport function getRedirectUri() {\n const redirectUri = process.env.PROPELAUTH_REDIRECT_URI\n if (!redirectUri) {\n throw new Error(\"PROPELAUTH_REDIRECT_URI is not set\")\n }\n return redirectUri\n}\n\nexport function getIntegrationApiKey() {\n const integrationApiKey = process.env.PROPELAUTH_API_KEY\n if (!integrationApiKey) {\n throw new Error(\"PROPELAUTH_API_KEY is not set\")\n }\n return integrationApiKey\n}\n\nexport function getVerifierKey() {\n const verifierKey = process.env.PROPELAUTH_VERIFIER_KEY\n if (!verifierKey) {\n throw new Error(\"PROPELAUTH_VERIFIER_KEY is not set\")\n }\n return verifierKey.replace(/\\\\n/g, \"\\n\")\n}\n\nexport async function refreshTokenWithAccessAndRefreshToken(refreshToken: string): Promise<RefreshTokenResponse> {\n const body = {\n refresh_token: refreshToken,\n }\n const url = `${getAuthUrlOrigin()}/api/backend/v1/refresh_token`\n const response = await fetch(url, {\n method: \"POST\",\n body: JSON.stringify(body),\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: \"Bearer \" + getIntegrationApiKey(),\n },\n })\n\n if (response.ok) {\n const data = await response.json()\n const newRefreshToken = data.refresh_token\n const {\n access_token: accessToken,\n expires_at_seconds: expiresAtSeconds,\n } = data.access_token\n\n return {\n refreshToken: newRefreshToken,\n accessToken,\n error: \"none\",\n }\n } else if (response.status === 400) {\n return {error: \"unauthorized\"}\n } else {\n return {error: \"unexpected\"}\n }\n}\n\nexport async function validateAccessTokenOrUndefined(accessToken: string | undefined): Promise<UserFromToken | undefined> {\n try {\n return await validateAccessToken(accessToken)\n } catch (err) {\n if (err instanceof ConfigurationException) {\n throw err\n } else if (err instanceof UnauthorizedException) {\n return undefined\n } else {\n console.log(\"Error validating access token\", err)\n return undefined\n }\n }\n}\n\nexport async function validateAccessToken(accessToken: string | undefined): Promise<UserFromToken> {\n let publicKey\n try {\n publicKey = await jose.importSPKI(getVerifierKey(), \"RS256\")\n } catch (err) {\n console.error(\"Verifier key is invalid. Make sure it's specified correctly, including the newlines.\", err)\n throw new ConfigurationException(\"Invalid verifier key\")\n }\n\n if (!accessToken) {\n throw new UnauthorizedException(\"No access token provided\")\n }\n\n let accessTokenWithoutBearer = accessToken\n if (accessToken.toLowerCase().startsWith(\"bearer \")) {\n accessTokenWithoutBearer = accessToken.substring(\"bearer \".length)\n }\n\n try {\n const {payload} = await jose.jwtVerify(accessTokenWithoutBearer, publicKey, {\n issuer: getAuthUrlOrigin(),\n algorithms: [\"RS256\"],\n })\n\n return toUser(<InternalUser>payload)\n } catch (e) {\n if (e instanceof Error) {\n throw new UnauthorizedException(e.message)\n } else {\n throw new UnauthorizedException(\"Unable to decode jwt\")\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAO,IAAM,wBAAN,cAAoC,MAAM;AAAA,EAI7C,YAAY,SAAiB;AACzB,UAAM,OAAO;AACb,SAAK,UAAU;AACf,SAAK,SAAS;AAAA,EAClB;AACJ;AAEO,IAAM,yBAAN,cAAqC,MAAM;AAAA,EAI9C,YAAY,SAAiB;AACzB,UAAM,OAAO;AACb,SAAK,UAAU;AACf,SAAK,SAAS;AAAA,EAClB;AACJ;;;ACpBA,wBAAuB;AACvB,qBAA+B;AAC/B,oBAAwC;;;ACFjC,IAAM,gBAAN,MAAoB;AAAA,EAevB,YACI,QACA,OACA,sBACA,WACA,UACA,UACA,cACA,oBACF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kB,EAAC,OAAM,GAAiC;AAChF,QAAI,OAAO,SAAS,UAAU;AAC1B,aAAO,kBAAkB,GAAG;AAAA,IAChC,OAAO;AACH,aAAO,IAAI,SAAS,IAAI,EAAC,QAAQ,IAAG,CAAC;AAAA,IACzC;AAAA,EACJ;AAEA,SAAO;AAAA,IACH;AAAA,IACA;AAAA,EACJ;AACJ;AAEA,SAAS,cAAsB;AAC3B,QAAM,cAAc,OAAO,gBAAgB,IAAI,WAAW,EAAE,CAAC;AAC7D,SAAO,MAAM,KAAK,WAAW,EACxB,IAAI,CAAC,MAAM,EAAE,SAAS,EAAE,EAAE,SAAS,GAAG,GAAG,CAAC,EAC1C,KAAK,EAAE;AAChB;","names":["headers","response"]}
|
@@ -35,8 +35,13 @@ var ConfigurationException = class extends Error {
|
|
35
35
|
}
|
36
36
|
};
|
37
37
|
|
38
|
+
// src/server/app-router.ts
|
39
|
+
import { redirect } from "next/navigation";
|
40
|
+
import { cookies, headers } from "next/headers";
|
41
|
+
import { NextResponse } from "next/server";
|
42
|
+
|
38
43
|
// src/user.ts
|
39
|
-
var
|
44
|
+
var UserFromToken = class {
|
40
45
|
constructor(userId, email, orgIdToOrgMemberInfo, firstName, lastName, username, legacyUserId, impersonatorUserId) {
|
41
46
|
this.userId = userId;
|
42
47
|
this.orgIdToOrgMemberInfo = orgIdToOrgMemberInfo;
|
@@ -83,7 +88,7 @@ var User = class {
|
|
83
88
|
JSON.stringify(obj.orgIdToOrgMemberInfo[orgId])
|
84
89
|
);
|
85
90
|
}
|
86
|
-
return new
|
91
|
+
return new UserFromToken(
|
87
92
|
obj.userId,
|
88
93
|
obj.email,
|
89
94
|
orgIdToOrgMemberInfo,
|
@@ -142,7 +147,7 @@ var OrgMemberInfo = class {
|
|
142
147
|
}
|
143
148
|
};
|
144
149
|
function toUser(snake_case) {
|
145
|
-
return new
|
150
|
+
return new UserFromToken(
|
146
151
|
snake_case.user_id,
|
147
152
|
snake_case.email,
|
148
153
|
toOrgIdToOrgMemberInfo(snake_case.org_id_to_org_member_info),
|
@@ -175,11 +180,6 @@ function toOrgIdToOrgMemberInfo(snake_case) {
|
|
175
180
|
return camelCase;
|
176
181
|
}
|
177
182
|
|
178
|
-
// src/server/app-router.ts
|
179
|
-
import { redirect } from "next/navigation";
|
180
|
-
import { cookies, headers } from "next/headers";
|
181
|
-
import { NextResponse } from "next/server";
|
182
|
-
|
183
183
|
// src/server/shared.ts
|
184
184
|
import * as jose from "jose";
|
185
185
|
var LOGIN_PATH = "/api/auth/login";
|
@@ -197,11 +197,14 @@ var COOKIE_OPTIONS = {
|
|
197
197
|
path: "/"
|
198
198
|
};
|
199
199
|
function getAuthUrlOrigin() {
|
200
|
+
return getAuthUrl().origin;
|
201
|
+
}
|
202
|
+
function getAuthUrl() {
|
200
203
|
const authUrl = process.env.NEXT_PUBLIC_AUTH_URL;
|
201
204
|
if (!authUrl) {
|
202
205
|
throw new Error("NEXT_PUBLIC_AUTH_URL is not set");
|
203
206
|
}
|
204
|
-
return new URL(authUrl)
|
207
|
+
return new URL(authUrl);
|
205
208
|
}
|
206
209
|
function getRedirectUri() {
|
207
210
|
const redirectUri = process.env.PROPELAUTH_REDIRECT_URI;
|
@@ -330,6 +333,12 @@ function getUser() {
|
|
330
333
|
return void 0;
|
331
334
|
});
|
332
335
|
}
|
336
|
+
function getAccessToken() {
|
337
|
+
return __async(this, null, function* () {
|
338
|
+
var _a;
|
339
|
+
return headers().get(CUSTOM_HEADER_FOR_ACCESS_TOKEN) || ((_a = cookies().get(ACCESS_TOKEN_COOKIE_NAME)) == null ? void 0 : _a.value);
|
340
|
+
});
|
341
|
+
}
|
333
342
|
function authMiddleware(req) {
|
334
343
|
return __async(this, null, function* () {
|
335
344
|
var _a, _b;
|
@@ -483,18 +492,14 @@ function getRouteHandlers(args) {
|
|
483
492
|
}
|
484
493
|
});
|
485
494
|
if (response.ok) {
|
495
|
+
const userFromToken = yield validateAccessToken(accessToken);
|
486
496
|
const data = yield response.json();
|
487
|
-
const
|
488
|
-
data
|
489
|
-
|
490
|
-
|
491
|
-
|
492
|
-
|
493
|
-
data.username,
|
494
|
-
data.legacy_user_id,
|
495
|
-
data.impersonator_user_id
|
496
|
-
);
|
497
|
-
return new Response(JSON.stringify(user), {
|
497
|
+
const jsonResponse = {
|
498
|
+
userinfo: data,
|
499
|
+
accessToken,
|
500
|
+
impersonatorUserId: userFromToken.impersonatorUserId
|
501
|
+
};
|
502
|
+
return new Response(JSON.stringify(jsonResponse), {
|
498
503
|
status: 200,
|
499
504
|
headers: {
|
500
505
|
"Content-Type": "application/json"
|
@@ -575,6 +580,7 @@ export {
|
|
575
580
|
ConfigurationException,
|
576
581
|
UnauthorizedException,
|
577
582
|
authMiddleware,
|
583
|
+
getAccessToken,
|
578
584
|
getRouteHandlers,
|
579
585
|
getUser,
|
580
586
|
getUserOrRedirect
|