Skip to content

Commit

Permalink
feature(web): Async validate JWT account and sign out the user if the…
Browse files Browse the repository at this point in the history
…y no longer exist
  • Loading branch information
MohamedBassem committed Oct 5, 2024
1 parent 3a8d197 commit f1c956a
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 2 deletions.
2 changes: 2 additions & 0 deletions apps/web/app/dashboard/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import MobileSidebar from "@/components/dashboard/sidebar/ModileSidebar";
import Sidebar from "@/components/dashboard/sidebar/Sidebar";
import DemoModeBanner from "@/components/DemoModeBanner";
import { Separator } from "@/components/ui/separator";
import ValidAccountCheck from "@/components/utils/ValidAccountCheck";

import serverConfig from "@hoarder/shared/config";

Expand All @@ -14,6 +15,7 @@ export default async function Dashboard({
}>) {
return (
<div className="flex min-h-screen w-screen flex-col sm:h-screen sm:flex-row">
<ValidAccountCheck />
<div className="hidden flex-none sm:flex">
<Sidebar />
</div>
Expand Down
26 changes: 26 additions & 0 deletions apps/web/components/utils/ValidAccountCheck.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
"use client";

import { api } from "@/lib/trpc";
import { signOut } from "next-auth/react";

/**
* This component is used to address a confusion when the JWT token exists but the user no longer exists in the database.
* So this component synchronusly checks if the user is still valid and if not, signs out the user.
*/
export default function ValidAccountCheck() {
const { error } = api.users.whoami.useQuery(undefined, {
retry: (_failureCount, error) => {
if (error.data?.code === "UNAUTHORIZED") {
return false;
}
return true;
},
});
if (error?.data?.code === "UNAUTHORIZED") {
signOut({
callbackUrl: "/",
});
}

return <></>;
}
13 changes: 11 additions & 2 deletions packages/trpc/routers/users.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { TRPCError } from "@trpc/server";
import { count, eq } from "drizzle-orm";
import { and, count, eq } from "drizzle-orm";
import invariant from "tiny-invariant";
import { z } from "zod";

Expand Down Expand Up @@ -138,7 +138,16 @@ export const usersAppRouter = router({
email: z.string().nullish(),
}),
)
.query(({ ctx }) => {
.query(async ({ ctx }) => {
if (!ctx.user.email) {
throw new TRPCError({ code: "UNAUTHORIZED" });
}
const userDb = await ctx.db.query.users.findFirst({
where: and(eq(users.id, ctx.user.id), eq(users.email, ctx.user.email)),
});
if (!userDb) {
throw new TRPCError({ code: "UNAUTHORIZED" });
}
return { id: ctx.user.id, name: ctx.user.name, email: ctx.user.email };
}),
});

0 comments on commit f1c956a

Please sign in to comment.