is this middleware is good for longterm?

hello guys, in these code snippet i want to check if user is subs and valid, but i im wondering if this thing is good to do for long term, and what is the pros and cons of this thankss
const enforceUserIsSubscribed = t.middleware(async ({ ctx, next }) => {
if (!ctx.session || !ctx.session.user) {
throw new TRPCError({ code: "UNAUTHORIZED" });
}
if (!ctx.session.user.isSubscribed || ctx.session.user.role !== "admin") {
throw new TRPCError({ code: "UNAUTHORIZED" });
}
// user is subscribed, check if subscription is still valid
const currentDateTime = new Date();
const userSubscriptions = await ctx.prisma.subscription.findMany({
where: {
subscriberId: ctx.session.user.id,
subscribedUntil: {
gte: currentDateTime,
},
},
});
if (!userSubscriptions || userSubscriptions.length === 0) {
//set user to not subscribed
await ctx.prisma.user.update({
where: {
id: ctx.session.user.id,
},
data: {
isSubscribed: false,
},
});
throw new TRPCError({ code: "UNAUTHORIZED" });
}
return next({
ctx: {
// infers the `session` as non-nullable
session: { ...ctx.session, user: ctx.session.user },
},
});
});
const enforceUserIsSubscribed = t.middleware(async ({ ctx, next }) => {
if (!ctx.session || !ctx.session.user) {
throw new TRPCError({ code: "UNAUTHORIZED" });
}
if (!ctx.session.user.isSubscribed || ctx.session.user.role !== "admin") {
throw new TRPCError({ code: "UNAUTHORIZED" });
}
// user is subscribed, check if subscription is still valid
const currentDateTime = new Date();
const userSubscriptions = await ctx.prisma.subscription.findMany({
where: {
subscriberId: ctx.session.user.id,
subscribedUntil: {
gte: currentDateTime,
},
},
});
if (!userSubscriptions || userSubscriptions.length === 0) {
//set user to not subscribed
await ctx.prisma.user.update({
where: {
id: ctx.session.user.id,
},
data: {
isSubscribed: false,
},
});
throw new TRPCError({ code: "UNAUTHORIZED" });
}
return next({
ctx: {
// infers the `session` as non-nullable
session: { ...ctx.session, user: ctx.session.user },
},
});
});
2 Replies
FleetAdmiralJakob 🗕 🗗 🗙
Hey @Fatwa , I'm stuck in a problem related to the middlewares and I think you know the answer to my problem. How does this ctx thingy work? Like why is it of type :{} and how can I get data out of it?
arete
arete11mo ago
can you be more specifc to what are you trying to achieve?