Skip to content

Commit

Permalink
Merge pull request #469 from karrioapi/debug-org-switcher
Browse files Browse the repository at this point in the history
fix: org switching issues
  • Loading branch information
danh91 authored Dec 18, 2023
2 parents 3f4cfa0 + 2ac4e86 commit c1d56a5
Show file tree
Hide file tree
Showing 6 changed files with 22 additions and 32 deletions.
19 changes: 1 addition & 18 deletions apps/dashboard/src/context/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import axios from "axios";

type RequestContext = GetServerSidePropsContext | { req: NextApiRequest, res: NextApiResponse };
const { serverRuntimeConfig, publicRuntimeConfig } = getConfig();
const ACTIVE_SUBSCRIPTIONS = ["active", "trialing", "incomplete", "free"];
const AUTH_HTTP_CODES = [401, 403, 407];


Expand All @@ -26,15 +25,6 @@ export const getServerSideProps: GetServerSideProps = async (ctx) => {

await setSessionCookies(ctx, orgId);

if (needValidSubscription(subscription)) {
return {
redirect: {
permanent: false,
destination: '/billing'
}
}
}

if (needStaffAccess(pathname, data)) {
return {
redirect: {
Expand Down Expand Up @@ -84,7 +74,7 @@ export async function loadContextData(session: SessionType, metadata: Metadata):
const { accessToken, orgId, testMode } = session;
const headers = {
...(orgId ? { 'x-org-id': orgId } : {}),
...(testMode ? { 'x-test-id': testMode } : {}),
...(testMode ? { 'x-test-mode': testMode } : {}),
'authorization': `Bearer ${accessToken}`,
} as any;

Expand Down Expand Up @@ -199,13 +189,6 @@ export async function loadTenantInfo(filter: { app_domain?: string, schema_name?
}
}

function needValidSubscription({ subscription }: { subscription?: SubscriptionType | null }) {
return (
subscription &&
!ACTIVE_SUBSCRIPTIONS.includes(subscription?.status as string)
)
}

function needStaffAccess(pathname, { user }: { user?: any | null }) {
return (
pathname.includes('/admin') &&
Expand Down
24 changes: 14 additions & 10 deletions apps/dashboard/src/pages/api/auth/[...nextauth].ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ async function AuthAPI(req: NextApiRequest, res: NextApiResponse) {
);

return {
email: credentials.email,
accessToken: token.access,
refreshToken: token.refresh,
orgId: org?.id,
Expand All @@ -51,7 +52,7 @@ async function AuthAPI(req: NextApiRequest, res: NextApiResponse) {
})
],
callbacks: {
jwt: async ({ token, user }: any): Promise<JWT> => {
jwt: async ({ token, user, trigger, session }: any): Promise<JWT> => {
if (user?.accessToken) {
token.orgId = user.orgId;
token.testMode = user.testMode;
Expand All @@ -62,12 +63,9 @@ async function AuthAPI(req: NextApiRequest, res: NextApiResponse) {
token.testMode = computeTestMode(req);
}

// Check if organization updated
const cookieOrgId = req.cookies['orgId'];
if (!isNoneOrEmpty(cookieOrgId) && !isNoneOrEmpty((token as any).orgId) && cookieOrgId !== (token as any).orgId) {
logger.debug(`Switching organization to ${cookieOrgId}...`);

const org = await auth.getCurrentOrg((token as any).accessToken, cookieOrgId);
if (trigger === "update" && session?.orgId) {
// Note, that `session` can be any arbitrary object, remember to validate it!
const org = await auth.getCurrentOrg((token as any).accessToken, session.orgId);
token.orgId = org?.id;
}

Expand All @@ -76,7 +74,7 @@ async function AuthAPI(req: NextApiRequest, res: NextApiResponse) {
return token;
}

// Access token has expired, try to update it OR orgId has changed
// Access token has expired, try to update it
try {
logger.info('Refreshing expired token...');
const { access, refresh } = await auth.refreshToken(token.refreshToken as string);
Expand All @@ -95,14 +93,20 @@ async function AuthAPI(req: NextApiRequest, res: NextApiResponse) {
}
}
},
session: async ({ session, token }: any) => {
session: async ({ session, token, user }: any) => {
session.accessToken = token.accessToken;
session.expires = token.expiration;
session.testMode = token.testMode;
session.error = token.error;
session.orgId = token.orgId;
session.user = {
...(user || session.user || {}),
accessToken: token.accessToken,
testMode: token.testMode,
orgId: token.orgId,
};

return session
return session;
}
}
})(req, res);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ def _extract_tracking(
(
status.name
for status in list(provider_units.TrackingStatus)
if track_detail.StatusDetail.Code in status.value
if getattr(track_detail.StatusDetail, "Code") in status.value
),
provider_units.TrackingStatus.in_transit.name,
)
Expand Down
4 changes: 2 additions & 2 deletions packages/hooks/karrio.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { useAPIMetadata } from "@karrio/hooks/api-metadata";
import { SessionType, KarrioClient } from "@karrio/types";
import { useSyncedSession } from "@karrio/hooks/session";
import { logger, url$ } from "@karrio/lib";
import { getCookie, logger, url$ } from "@karrio/lib";
import getConfig from 'next/config';
import React from "react";

Expand Down Expand Up @@ -38,9 +38,9 @@ export function useKarrio() {

function requestInterceptor(session?: SessionType) {
return (config: any = { headers: {} }) => {
const orgHeader: any = !!session?.orgId ? { 'x-org-id': session.orgId } : {};
const testHeader: any = !!session?.testMode ? { 'x-test-mode': session.testMode } : {};
const authHeader: any = !!session?.accessToken ? { 'authorization': `Bearer ${session.accessToken}` } : {};
const orgHeader: any = !!session?.orgId ? { 'x-org-id': getCookie("orgId") } : {};

config.headers = {
...config.headers,
Expand Down
3 changes: 3 additions & 0 deletions packages/hooks/organization.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { accept_organization_invitation, ACCEPT_ORGANIZATION_INVITATION, ChangeOrganizationOwnerMutationInput, change_organization_owner, CHANGE_ORGANIZATION_OWNER, CreateOrganizationMutationInput, create_organization, CREATE_ORGANIZATION, delete_organization, DELETE_ORGANIZATION, delete_organization_invitation, DELETE_ORGANIZATION_INVITES, get_organizations, GET_ORGANIZATIONS, get_organizations_organizations, get_organization_invitation, GET_ORGANIZATION_INVITATION, SendOrganizationInvitesMutationInput, send_organization_invites, SEND_ORGANIZATION_INVITES, SetOrganizationUserRolesMutationInput, set_organization_user_roles, SET_ORGANIZATION_USER_ROLES, UpdateOrganizationMutationInput, update_organization, UPDATE_ORGANIZATION } from "@karrio/types";
import { DefinedUseQueryResult, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { gqlstr, insertUrlParam, onError, setCookie } from "@karrio/lib";
import { useSession } from "next-auth/react";
import { useKarrio } from "./karrio";
import React from "react";

Expand Down Expand Up @@ -61,6 +62,7 @@ export function useOrganizations() {
}

export function useOrganizationMutation() {
const { update } = useSession();
const karrio = useKarrio();
const queryClient = useQueryClient();
const invalidateCache = () => { queryClient.invalidateQueries(['organizations']) };
Expand Down Expand Up @@ -112,6 +114,7 @@ export function useOrganizationMutation() {
// Helpers
const changeActiveOrganization = async (orgId: string) => {
setCookie("orgId", orgId);
update({ orgId });
insertUrlParam({});
setTimeout(() => location.reload(), 1000);
};
Expand Down
2 changes: 1 addition & 1 deletion packages/ui/components/organization-dropdown.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ import React, { useContext, useEffect, useRef, useState } from 'react';
import { useAPIMetadata } from '@karrio/hooks/api-metadata';
import { useAPIToken } from '@karrio/hooks/api-token';
import { isNoneOrEmpty } from '@karrio/lib';
import { Loading } from './loader';
import { useRouter } from 'next/router';
import { Loading } from './loader';
import { p } from '@karrio/lib';
import Image from 'next/image';

Expand Down

0 comments on commit c1d56a5

Please sign in to comment.