Skip to content

Commit

Permalink
Completly removed next-auth 😄
Browse files Browse the repository at this point in the history
  • Loading branch information
atrincas committed Jan 8, 2025
1 parent c196847 commit b8a118b
Show file tree
Hide file tree
Showing 15 changed files with 94 additions and 224 deletions.
1 change: 0 additions & 1 deletion client/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,6 @@
"lucide-react": "0.447.0",
"mapbox-gl": "3.7.0",
"next": "14.2.10",
"next-auth": "4.24.8",
"nuqs": "2.0.4",
"react": "^18",
"react-country-flag": "^3.1.0",
Expand Down
16 changes: 16 additions & 0 deletions client/src/app/auth/api/session/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { NextResponse } from "next/server";

import { getServerSession } from "@/lib/auth/server";
import { AuthApiResponse } from "@/lib/auth/types";
import { AppSession } from "@/lib/auth/types";

export async function GET(): Promise<
NextResponse<AuthApiResponse<AppSession | null>>
> {
const session = await getServerSession();

return NextResponse.json({
body: session || null,
status: session ? 200 : 401,
});
}
29 changes: 18 additions & 11 deletions client/src/app/auth/api/signin/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@ import { NextRequest, NextResponse } from "next/server";

import { generateUserJWT } from "@/lib/auth/jwt";
import { setAuthCookie, setResponseCookie } from "@/lib/auth/server";
import { AppSession } from "@/lib/auth/types";
import { AuthApiResponse, AppSession } from "@/lib/auth/types";
import { client } from "@/lib/query-client";

export async function POST(req: NextRequest) {
export async function POST(
req: NextRequest,
): Promise<NextResponse<AuthApiResponse<AppSession | null>>> {
try {
const { email, password } = await req.json();

Expand All @@ -14,10 +16,11 @@ export async function POST(req: NextRequest) {
});

if (response.status !== 201) {
return NextResponse.json(
{ error: response.body.errors?.[0]?.title || "Invalid credentials" },
{ status: response.status },
);
return NextResponse.json({
body: null,
status: response.status,
error: response.body.errors?.[0]?.title || "Invalid credentials",
});
}

setResponseCookie(response.headers);
Expand All @@ -26,11 +29,15 @@ export async function POST(req: NextRequest) {
const token = await generateUserJWT(appSession);
setAuthCookie(token);

return NextResponse.json(appSession);
return NextResponse.json({
body: appSession,
status: 201,
});
} catch (err) {
return NextResponse.json(
{ error: "An error occurred during sign in" },
{ status: 500 },
);
return NextResponse.json({
body: null,
status: 500,
error: "An error occurred during sign in",
});
}
}
8 changes: 6 additions & 2 deletions client/src/app/auth/api/signout/route.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
import { NextResponse } from "next/server";

import { revokeSession } from "@/lib/auth/server";
import { AuthApiResponse } from "@/lib/auth/types";

export async function POST() {
export async function POST(): Promise<NextResponse<AuthApiResponse<null>>> {
await revokeSession();

return NextResponse.json({ message: "Logged out" });
return NextResponse.json({
body: null,
status: 200,
});
}
6 changes: 1 addition & 5 deletions client/src/app/providers.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import { AuthProvider } from "@/lib/auth/context";
import { AppSession } from "@/lib/auth/types";
import { makeQueryClient } from "@/lib/query-client";

import SessionChecker from "@/components/session-checker";
import { TooltipProvider } from "@/components/ui/tooltip";

let browserQueryClient: QueryClient | undefined = undefined;
Expand Down Expand Up @@ -45,10 +44,7 @@ export default function LayoutProviders({
<TooltipProvider>
<QueryClientProvider client={queryClient}>
<TooltipProvider>
<JotaiProvider store={appStore}>
<SessionChecker />
{children}
</JotaiProvider>
<JotaiProvider store={appStore}>{children}</JotaiProvider>
</TooltipProvider>
</QueryClientProvider>
</TooltipProvider>
Expand Down
53 changes: 0 additions & 53 deletions client/src/components/session-checker/index.tsx

This file was deleted.

2 changes: 1 addition & 1 deletion client/src/containers/auth/signin/form/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ const SignInForm: FC<SignInFormProps> = ({ onSignIn }) => {
resolver: zodResolver(LogInSchema),
defaultValues: {
email: "[email protected]",
password: "12345678",
password: "",
},
});

Expand Down
10 changes: 6 additions & 4 deletions client/src/containers/profile/delete-account/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@

import { FC, useCallback } from "react";

import { signOut } from "next-auth/react";
import { useRouter } from "next/navigation";

import { signOut } from "@/lib/auth/api";
import { useAuth } from "@/lib/auth/context";
import { client } from "@/lib/query-client";

Expand All @@ -24,7 +25,7 @@ import { useToast } from "@/components/ui/toast/use-toast";
const DeleteAccount: FC = () => {
const { session } = useAuth();
const { toast } = useToast();

const router = useRouter();
const onDeleteAccount = useCallback(async () => {
try {
const { status, body } = await client.user.deleteMe.mutation({
Expand All @@ -34,7 +35,8 @@ const DeleteAccount: FC = () => {
});

if (status === 200) {
signOut({ callbackUrl: "/auth/signin", redirect: true });
await signOut();
router.push("/auth/signin");
} else if (status === 400 || status === 401) {
toast({
variant: "destructive",
Expand All @@ -47,7 +49,7 @@ const DeleteAccount: FC = () => {
description: "Something went wrong deleting the account.",
});
}
}, [session?.accessToken, toast]);
}, [session?.accessToken, toast, router]);

return (
<AlertDialog>
Expand Down
4 changes: 2 additions & 2 deletions client/src/containers/profile/file-upload/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ import React, { FC, useCallback, useState } from "react";
import { useDropzone } from "react-dropzone";

import { FileUpIcon, XIcon } from "lucide-react";
import { useSession } from "next-auth/react";

import { useAuth } from "@/lib/auth/context";
import { client } from "@/lib/query-client";
import { cn } from "@/lib/utils";

Expand All @@ -30,7 +30,7 @@ const MAX_FILES = 2;

const FileUpload: FC = () => {
const [files, setFiles] = useState<File[]>([]);
const { data: session } = useSession();
const { session } = useAuth();
const { toast } = useToast();
const onDropAccepted = useCallback(
(acceptedFiles: File[]) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,10 @@ import { CustomProject as CustomProjectEntity } from "@shared/entities/custom-pr
import { useQueryClient } from "@tanstack/react-query";
import { useAtom } from "jotai";
import { LayoutListIcon } from "lucide-react";
import { Session } from "next-auth";
import { getSession, useSession } from "next-auth/react";

import { getSession } from "@/lib/auth/api";
import { useAuth } from "@/lib/auth/context";
import { AppSession } from "@/lib/auth/types";
import { client } from "@/lib/query-client";
import { cn, getAuthHeader } from "@/lib/utils";

Expand All @@ -29,11 +30,11 @@ const CustomProjectHeader: FC<CustomProjectHeaderProps> = ({ data }) => {
const [{ projectSummaryOpen }, setProjectSummaryOpen] =
useAtom(projectsUIState);
const queryClient = useQueryClient();
const { data: session } = useSession();
const { session } = useAuth();
const { toast } = useToast();
const [saved, setSaved] = useState<boolean>(false);
const SaveProject = useCallback(
async (arg: Session | null = session) => {
async (arg: AppSession | null = session) => {
try {
const { status, body } =
await client.customProjects.saveCustomProject.mutation({
Expand Down
4 changes: 2 additions & 2 deletions client/src/hooks/use-get-custom-project.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,14 @@ import { usePathname, useRouter } from "next/navigation";

import { CustomProject as CustomProjectEntity } from "@shared/entities/custom-project.entity";
import { useQueryClient } from "@tanstack/react-query";
import { useSession } from "next-auth/react";

import { useAuth } from "@/lib/auth/context";
import { client } from "@/lib/query-client";
import { queryKeys } from "@/lib/query-keys";
import { getAuthHeader } from "@/lib/utils";

export function useGetCustomProject(id?: string) {
const { data: session } = useSession();
const { session } = useAuth();
const queryCache = useQueryClient().getQueryData<{
data: InstanceType<typeof CustomProjectEntity>;
}>(queryKeys.customProjects.cached.queryKey);
Expand Down
17 changes: 16 additions & 1 deletion client/src/lib/auth/api.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { UserWithAccessToken } from "@shared/dtos/users/user.dto";

import { AppSession, AuthApiResponse } from "@/lib/auth/types";

import { getServerAuthUrl } from "./server";

/**
Expand Down Expand Up @@ -38,7 +40,13 @@ export async function signIn(
body: JSON.stringify({ email, password }),
});

return response.json();
const data: AuthApiResponse<UserWithAccessToken> = await response.json();

if (data.status !== 201) {
throw new Error(data.error || "Invalid credentials");
}

return data.body;
} catch (error) {
throw error;
}
Expand All @@ -47,6 +55,7 @@ export async function signIn(
/**
* Signs out the current user by making a POST request to the signout endpoint.
* @returns {Promise<void>}
* TODO: nice to have: { callbackUrl: string; redirect: boolean }
*/
export async function signOut(): Promise<void> {
try {
Expand All @@ -61,3 +70,9 @@ export async function signOut(): Promise<void> {
console.error("Error signing out", error);
}
}

export async function getSession(): Promise<AppSession> {
const baseUrl = await getAuthUrl();
const response = await fetch(`${baseUrl}/session`);
return response.json();
}
6 changes: 6 additions & 0 deletions client/src/lib/auth/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,9 @@ export enum AuthStatus {
UNAUTHENTICATED = "unauthenticated",
AUTHENTICATED = "authenticated",
}

export interface AuthApiResponse<T> {
body: T;
status: number;
error?: string;
}
3 changes: 1 addition & 2 deletions client/src/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,10 @@ import { NextRequest, NextResponse } from "next/server";
import { signOut } from "@/lib/auth/api";
import { SIGNIN_PATH } from "@/lib/auth/constants";
import { getServerSession } from "@/lib/auth/server";

import { isPrivatePath } from "@/lib/utils";

export async function middleware(req: NextRequest) {
if (PRIVATE_PAGES.test(req.nextUrl.pathname)) {
if (isPrivatePath(req.nextUrl.pathname)) {
const session = await getServerSession();

if (!session) {
Expand Down
Loading

0 comments on commit b8a118b

Please sign in to comment.