Skip to content

Commit

Permalink
refactor: ♻️ cleaning up auth flow
Browse files Browse the repository at this point in the history
  • Loading branch information
aacevski committed Jan 5, 2025
1 parent 4ba3c4f commit d4d4f3a
Show file tree
Hide file tree
Showing 8 changed files with 31 additions and 37 deletions.
8 changes: 2 additions & 6 deletions apps/api/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,19 +9,15 @@ const app = new Elysia()
.guard({
async beforeHandle({ set, cookie: { session } }) {
if (!session?.value) {
set.status = "Unauthorized";

return set.status;
return { user: null, session: null };
}

const { user, session: validatedSession } = await validateSessionToken(
session.value,
);

if (!user || !validatedSession) {
set.status = "Unauthorized";

return set.status;
return { user: null, session: null };
}
},
})
Expand Down
5 changes: 4 additions & 1 deletion apps/web/src/components/auth/sign-in-form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { AlertCircle, Eye, EyeOff } from "lucide-react";
import { useState } from "react";
import { useForm } from "react-hook-form";
import { type ZodType, z } from "zod";
import useAuth from "../providers/auth-provider/hooks/use-auth";
import { Alert, AlertDescription, AlertTitle } from "../ui/alert";

export type SignInFormValues = {
Expand All @@ -30,6 +31,7 @@ const signInSchema: ZodType<SignInFormValues> = z.object({
export function SignInForm() {
const [showPassword, setShowPassword] = useState(false);
const { history } = useRouter();
const { setUser } = useAuth();
const form = useForm<SignInFormValues>({
resolver: zodResolver(signInSchema),
defaultValues: {
Expand All @@ -43,7 +45,8 @@ export function SignInForm() {
});

const onSubmit = async () => {
await mutateAsync();
const { data: user } = await mutateAsync();
setUser(user);
history.push("/dashboard");
};

Expand Down
5 changes: 4 additions & 1 deletion apps/web/src/components/auth/sign-up-form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { AlertCircle, Eye, EyeOff } from "lucide-react";
import { useState } from "react";
import { useForm } from "react-hook-form";
import { type ZodType, z } from "zod";
import useAuth from "../providers/auth-provider/hooks/use-auth";
import { Alert, AlertDescription, AlertTitle } from "../ui/alert";

export type SignUpFormValues = {
Expand All @@ -31,6 +32,7 @@ const signUpSchema: ZodType<SignUpFormValues> = z.object({

export function SignUpForm() {
const [showPassword, setShowPassword] = useState(false);
const { setUser } = useAuth();
const { history } = useRouter();
const form = useForm<SignUpFormValues>({
resolver: zodResolver(signUpSchema),
Expand All @@ -47,7 +49,8 @@ export function SignUpForm() {
});

const onSubmit = async () => {
await mutateAsync();
const { data: user } = await mutateAsync();
setUser(user);
history.push("/dashboard");
};

Expand Down
6 changes: 6 additions & 0 deletions apps/web/src/components/common/sidebar/sign-out-button.tsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,21 @@
import useAuth from "@/components/providers/auth-provider/hooks/use-auth";
import useSignOut from "@/hooks/mutations/use-sign-out";
import { useQueryClient } from "@tanstack/react-query";
import { useRouter } from "@tanstack/react-router";
import { LogOut } from "lucide-react";

function SignOutButton() {
const { setUser } = useAuth();
const { mutateAsync, isPending } = useSignOut();
const queryClient = useQueryClient();
const { history } = useRouter();

const handleSignOut = async () => {
await mutateAsync();
queryClient.invalidateQueries({
queryKey: ["me"],
type: "all",
});
setUser(null);
history.push("/auth/sign-in");
};
Expand Down
4 changes: 2 additions & 2 deletions apps/web/src/components/providers/auth-provider/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,15 +25,15 @@ function AuthProvider({ children }: PropsWithChildren) {
createdAt: Date;
} | null>(null);

const { data, isLoading } = useGetMe();
const { data, isFetching } = useGetMe(user?.id);

useEffect(() => {
if (data) {
setUser(data.data);
}
}, [data]);

if (isLoading) {
if (isFetching) {
return (
<div className="flex w-full items-center justify-center h-screen flex-col md:flex-row bg-zinc-50 dark:bg-zinc-950">
<div className="p-1.5 bg-gradient-to-br from-indigo-500 to-purple-500 rounded-lg shadow-sm animate-spin">
Expand Down
6 changes: 4 additions & 2 deletions apps/web/src/hooks/queries/use-get-me.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import me from "@/fetchers/user/me";
import { useQuery } from "@tanstack/react-query";

function useGetMe() {
function useGetMe(userId: string | undefined) {
console.log({ userId });

return useQuery({
queryKey: ["me"],
queryKey: ["me", userId],
queryFn: () => me(),
retry: 0,
});
Expand Down
12 changes: 8 additions & 4 deletions apps/web/src/routes/dashboard/index.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
import { Sidebar } from "@/components/common/sidebar";
import { redirect } from "@tanstack/react-router";
import { createFileRoute } from "@tanstack/react-router";

export const Route = createFileRoute("/dashboard/")({
component: DashboardIndexRouteComponent,
loader: ({ context: { queryClient } }) =>
queryClient.ensureQueryData({
queryKey: ["me"],
}),
async beforeLoad({ context: { user } }) {
if (!user) {
throw redirect({
to: "/auth/sign-in",
});
}
},
});

function DashboardIndexRouteComponent() {
Expand Down
22 changes: 1 addition & 21 deletions apps/web/src/routes/index.tsx
Original file line number Diff line number Diff line change
@@ -1,23 +1,3 @@
import type { User } from "@/types/user";
import { redirect } from "@tanstack/react-router";
import { createFileRoute } from "@tanstack/react-router";

export const Route = createFileRoute("/")({
async beforeLoad({ context: { queryClient } }) {
const { data: user } = await queryClient.ensureQueryData<{
data: User;
}>({
queryKey: ["me"],
});

if (!user) {
throw redirect({
to: "/auth/sign-in",
});
}

throw redirect({
to: "/dashboard",
});
},
});
export const Route = createFileRoute("/")();

0 comments on commit d4d4f3a

Please sign in to comment.