Skip to content

Commit

Permalink
refactor: DATA-11927 Move to url approach for authorization
Browse files Browse the repository at this point in the history
  • Loading branch information
bc-rmalyavc committed May 21, 2024
1 parent db0214f commit 4163aef
Show file tree
Hide file tree
Showing 7 changed files with 24 additions and 31 deletions.
10 changes: 0 additions & 10 deletions src/app/api/app/auth/route.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import jwt from 'jsonwebtoken';
import { type NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import * as db from '~/lib/db';
Expand Down Expand Up @@ -96,17 +95,8 @@ export async function GET(req: NextRequest) {
);
}

const clientToken = jwt.sign(
{ userId: oauthUser.id, storeHash },
env.JWT_KEY,
{ expiresIn: 3600 }
);

return NextResponse.redirect(env.APP_ORIGIN, {
status: 302,
statusText: 'Found',
headers: {
'set-cookie': `ai-app-foundation-token=${clientToken}; SameSite=None; Secure; Path=/; Partitioned; HttpOnly; Max-Age=3600;`,
},
});
}
5 changes: 1 addition & 4 deletions src/app/api/app/load/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,11 +56,8 @@ export function GET(request: NextRequest) {
expiresIn: 3600,
});

return NextResponse.redirect(new URL(path, env.APP_ORIGIN), {
return NextResponse.redirect(new URL(`${path}&authToken=${clientToken}`, env.APP_ORIGIN), {
status: 302,
statusText: 'Found',
headers: {
'set-cookie': `ai-app-foundation-token=${clientToken}; SameSite=None; Secure; Path=/; Partitioned; HttpOnly; Max-Age=3600;`,
},
});
}
4 changes: 3 additions & 1 deletion src/app/api/generateDescription/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ import { aiSchema } from './schema';
import { authorize } from '~/lib/authorize';

export async function POST(req: NextRequest) {
if (!authorize()) {
const authToken = req.nextUrl.searchParams.get('authToken') || 'missing';

if (!authorize(authToken)) {
return new NextResponse('Unauthorized', { status: 401 });
}

Expand Down
12 changes: 10 additions & 2 deletions src/app/productDescription/[productId]/form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,15 @@ import Loader from '~/components/Loader';
import { useAppContext } from '~/context/AppContext';
import { useTracking } from '~/hooks/useTracking';

export default function Form({ product, csrfToken }: { product: Product | NewProduct; csrfToken: string }) {
export default function Form({
product,
csrfToken,
authToken
}: {
product: Product | NewProduct;
csrfToken: string;
authToken: string;
}) {
const { descriptions, addDescriptionToHistory, updateDescriptionInHistory } =
useDescriptionsHistory(product.id);
const [isLoading, setIsLoading] = useState(false);
Expand All @@ -35,7 +43,7 @@ export default function Form({ product, csrfToken }: { product: Product | NewPro

const handleGenerateDescription = async () => {
setIsLoading(true);
const res = await fetch('/api/generateDescription', {
const res = await fetch(`/api/generateDescription?authToken=${authToken}`, {
method: 'POST',
body: JSON.stringify(
prepareAiPromptAttributes(currentAttributes, product)
Expand Down
6 changes: 4 additions & 2 deletions src/app/productDescription/[productId]/generator.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,15 @@ export default function Generator({
storeHash,
locale,
context,
csrfToken
csrfToken,
authToken
}: {
product: Product | NewProduct;
storeHash: string;
locale: string;
context: string;
csrfToken: string;
authToken: string;
}) {
const [isClient, setIsClient] = useState(false);

Expand All @@ -33,7 +35,7 @@ export default function Generator({
{isClient && (
<AppContext.Provider value={{ locale, storeHash, context }}>
<PromptAttributesProvider>
<Form product={product} csrfToken={csrfToken} />
<Form product={product} csrfToken={csrfToken} authToken={authToken} />
</PromptAttributesProvider>
</AppContext.Provider>
)}
Expand Down
7 changes: 4 additions & 3 deletions src/app/productDescription/[productId]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,14 @@ import { headers } from 'next/headers';

interface PageProps {
params: { productId: string };
searchParams: { product_name: string };
searchParams: { product_name: string; authToken: string };
}

export default async function Page(props: PageProps) {
const { productId } = props.params;
const { product_name: name } = props.searchParams;
const { product_name: name, authToken } = props.searchParams;

const authorized = authorize();
const authorized = authorize(authToken);

if (!authorized) {
throw new Error('Token is not valid. Try to re-open the app.');
Expand Down Expand Up @@ -42,6 +42,7 @@ export default async function Page(props: PageProps) {
product={product}
context="product_edit"
csrfToken={csrfToken}
authToken={authToken}
/>
);
}
11 changes: 2 additions & 9 deletions src/lib/authorize.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import jwt from 'jsonwebtoken';
import { cookies } from 'next/headers';
import { z } from 'zod';
import { env } from 'src/env.mjs';

Expand All @@ -8,15 +7,9 @@ const jwtPayloadSchema = z.object({
storeHash: z.string(),
});

export function authorize() {
const token = cookies().get('ai-app-foundation-token');

if (!token) {
return null;
}

export function authorize(authToken: string) {
try {
const payload = jwt.verify(token.value, env.JWT_KEY);
const payload = jwt.verify(authToken, env.JWT_KEY);

const parsed = jwtPayloadSchema.safeParse(payload);

Expand Down

0 comments on commit 4163aef

Please sign in to comment.