Skip to content

Commit

Permalink
test: auth api route for token
Browse files Browse the repository at this point in the history
  • Loading branch information
mgramigna committed Dec 16, 2023
1 parent 0814b24 commit b1da417
Show file tree
Hide file tree
Showing 4 changed files with 43 additions and 0 deletions.
1 change: 1 addition & 0 deletions apps/nextjs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
},
"dependencies": {
"@canvas-challenge/api": "workspace:*",
"@canvas-challenge/canvas": "workspace:*",
"@tanstack/react-query": "^5.8.7",
"@tanstack/react-query-devtools": "^5.8.7",
"@tanstack/react-query-next-experimental": "5.8.7",
Expand Down
33 changes: 33 additions & 0 deletions apps/nextjs/src/app/api/test/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { getAuthToken } from '@canvas-challenge/canvas';

export const runtime = 'edge';

function setCorsHeaders(res: Response) {
res.headers.set('Access-Control-Allow-Origin', '*');
res.headers.set('Access-Control-Request-Method', '*');
res.headers.set('Access-Control-Allow-Methods', 'OPTIONS, GET, POST');
res.headers.set('Access-Control-Allow-Headers', '*');
}

export function OPTIONS() {
const response = new Response(null, {
status: 204,
});
setCorsHeaders(response);
return response;
}

const handler = async () => {
const { token, expiresInSeconds } = await getAuthToken({
clientSecret: process.env.CANVAS_CLIENT_SECRET!,
clientId: process.env.CANVAS_CLIENT_ID!,
baseUrl: process.env.CANVAS_EMR_BASE_URL!,
});

return Response.json({
token,
expiresInSeconds,
});
};

export { handler as GET, handler as POST };
6 changes: 6 additions & 0 deletions packages/canvas/src/services/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,12 @@ export async function getAuthToken({
}),
});

if (!response.ok) {
return response.text().then((text) => {
throw new Error(text);
});
}

const json = AuthTokenResponseBodySchema.parse(await response.json());

return { token: json.access_token, expiresInSeconds: json.expires_in };
Expand Down
3 changes: 3 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit b1da417

Please sign in to comment.