Skip to content

Commit

Permalink
feat(packages/api): add auth router
Browse files Browse the repository at this point in the history
include auth router for quick access to user session on client and other httpserver auth routes and utilities
  • Loading branch information
matyson committed Dec 13, 2024
1 parent d39431d commit 9b6422e
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 0 deletions.
2 changes: 2 additions & 0 deletions packages/api/src/root.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { authRouter } from "./router/auth";
import { consoleOutputRouter } from "./router/console-output";
import { devicesRouter } from "./router/devices";
import { environmentRouter } from "./router/environment";
Expand All @@ -19,6 +20,7 @@ export const appRouter = createTRPCRouter({
consoleOutput: consoleOutputRouter,
history: historyRouter,
runEngine: runEngineRouter,
auth: authRouter,
});

// export type definition of API
Expand Down
60 changes: 60 additions & 0 deletions packages/api/src/router/auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { z } from "zod";
import { env } from "../../env";
import { protectedProcedure } from "../trpc";
import { zodSnakeFetcher } from "../utils";

const principalSchema = z.object({
uuid: z.string(),
type: z.enum(["user", "service"]),
identities: z.array(
z.object({
provider: z.string(),
id: z.string(),
latestLogin: z.string().optional().nullable(),
}),
),
apiKeys: z.array(
z.object({
firstEight: z.string(),
expirationTime: z.string().optional().nullable(),
note: z.string().optional().nullable(),
scopes: z.array(z.string()),
latestActivity: z.string().optional().nullable(),
}),
),
sessions: z.array(
z.object({
uuid: z.string(),
expirationTime: z.string(),
revoked: z.boolean(),
}),
),
latestActivity: z.string().nullable(),
roles: z.array(z.string()).nullable(),
scopes: z.array(z.string()).nullable(),
apiKeyScopes: z.array(z.string()).nullable(),
});

export const authRouter = {
getSession: protectedProcedure.query(({ ctx }) => {
return ctx.session;
}),
whoAmI: protectedProcedure.query(async ({ ctx }) => {
const fetchURL = `${env.BLUESKY_HTTPSERVER_URL}/api/auth/whoami`;
const blueskyAccessToken = ctx.session.user.blueskyAccessToken;
try {
const res = await zodSnakeFetcher(principalSchema, {
url: fetchURL,
method: "GET",
authorization: `Bearer ${blueskyAccessToken}`,
body: undefined,
});
return res;
} catch (e) {
if (e instanceof Error) {
throw new Error(e.message);
}
throw new Error("Unknown error");
}
}),
};

0 comments on commit 9b6422e

Please sign in to comment.