What would be the most elegant way to scope "before" handlers? #367
-
I have an auth module which handles user sessions. I want to write a plugin which uses some of elysias features to do e.g. cookie parsing and then enable type safe passing of user session related data. To do this, I wrote this module: import Elysia, { Context, t } from "elysia";
import { nanoid } from "nanoid";
import { createClient } from "redis";
import { appConfiguration } from "../config/config";
const client = createClient({
url: appConfiguration.db.redisUrl,
});
client.on("error", (err) => console.error("Redis Client Error", err));
await client.connect();
export type SessionData = {
userData?: {
userId: string;
email: string;
family_name: string;
given_name: string;
};
};
export const session = new Elysia()
.guard({
cookie: t.Cookie({
sessionId: t.Optional(t.String()),
}),
})
.derive(async ({ cookie: { sessionId } }) => {
const createNewSession = async () => {
sessionId.value = nanoid(30);
const data: SessionData = {};
await client.set(`user-session:${sessionId.value}`, JSON.stringify(data));
return {
session: { id: sessionId.value, data: data },
};
};
if (!sessionId.value) {
return createNewSession();
}
const rawData = await client.get(`user-session:${sessionId.value}`);
if (!rawData) {
return createNewSession();
}
const data: SessionData = JSON.parse(rawData);
return {
session: { id: sessionId.value, data },
};
});
export const loggedIn = new Elysia().use(session).guard({
beforeHandle({ session, set }) {
if (!session.data.userData) {
// biome-ignore lint/suspicious/noAssignInExpressions: just return the state as body aswell
return (set.status = "Unauthorized");
}
},
}); Now when I want to apply this to my handlers, this may look like this: import { t, Elysia } from "elysia";
import { loggedIn, session } from "../auth/session";
export const committee = new Elysia()
.use(session)
.get("/somePublicHandler", async ({ session }) => {
// do something with the session
})
.guard({}, (app) => {
return app
.use(loggedIn)
.post("/somePrivateHandler", async ({ session }) => {
// do something with the session if logged in
})
}); My problem is: Some of the handlers have more strict permission requirements. In this case, I want to make some of them available to logged in users and some simply should be public but I want to ensure that a session gets created whenever they hit an endpoint. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
Its fine! However you might want to Take a look into macros |
Beta Was this translation helpful? Give feedback.
Its fine! However you might want to Take a look into macros