Skip to content

Commit

Permalink
WIP auth with Auth.js + Auth0
Browse files Browse the repository at this point in the history
  • Loading branch information
ZIJ committed Oct 11, 2024
1 parent 5f91c40 commit a38e0c1
Show file tree
Hide file tree
Showing 13 changed files with 205 additions and 46 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,7 @@
"moment": "^2.29.4",
"nanoid": "^5.0.7",
"next": "^14.2.5",
"next-auth": "5.0.0-beta.22",
"next-mdx-remote": "^4.4.1",
"next-nprogress-bar": "^2.1.2",
"next-themes": "^0.3.0",
Expand Down
99 changes: 99 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions src/app/api/auth/[...nextauth]/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { handlers } from '@/auth';

export const { GET, POST } = handlers;
12 changes: 10 additions & 2 deletions src/app/route.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,15 @@
import { createSupabaseUserRouteHandlerClient } from '@/supabase-clients/user/createSupabaseUserRouteHandlerClient';
import { NextResponse } from 'next/server';
//import { createSupabaseUserRouteHandlerClient } from '@/supabase-clients/user/createSupabaseUserRouteHandlerClient';

import { redirect } from 'next/navigation';

export const dynamic = 'force-dynamic';

export async function GET() {
redirect('/dashboard');
}

// TODO remove when move to authjs is complete
/*
export async function GET() {
const supabase = createSupabaseUserRouteHandlerClient();
Expand Down Expand Up @@ -31,3 +38,4 @@ export async function GET() {
);
}
}
*/
13 changes: 13 additions & 0 deletions src/auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import NextAuth from 'next-auth';
import Auth0 from 'next-auth/providers/auth0';

export const { handlers, signIn, signOut, auth } = NextAuth({
//providers: [WorkOS({ connection: 'conn_01HVH5N4RFQVD9DH5QWGYT844V' })],
providers: [Auth0],
callbacks: {
authorized: async ({ auth }) => {
// Logged in users are authenticated, otherwise redirect to login page
return !!auth;
},
},
});
5 changes: 4 additions & 1 deletion src/data/user/organizations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ export const createOrganization = async (
return { status: 'error', message: orgMemberErrors.message };
}

// Why are we checking for onboarding deep in the data layer? Bad code.
if (isOnboardingFlow) {
const { error: updateError } = await supabaseClient
.from('user_private_info')
Expand Down Expand Up @@ -621,7 +622,9 @@ export async function getInitialOrganizationToRedirectTo(): Promise<
};
}

export async function getMaybeInitialOrganizationToRedirectTo(): Promise<SAPayload<string | null>> {
export async function getMaybeInitialOrganizationToRedirectTo(): Promise<
SAPayload<string | null>
> {
const initialOrganization = await getInitialOrganizationToRedirectTo();
if (initialOrganization.status === 'error') {
return {
Expand Down
2 changes: 1 addition & 1 deletion src/data/user/projects.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ export const createProjectCommentAction = async (
const user = await serverGetLoggedInUser();
const { data, error } = await supabaseClient
.from("project_comments")
.insert({ project_id: projectId, text, user_id: user.id })
.insert({ project_id: projectId, text, user_id: user.id! }) //TODO remove assertion or resolve
.select("*, user_profiles(*)")
.single();
if (error) {
Expand Down
9 changes: 6 additions & 3 deletions src/data/user/session.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
"use server"
'use server';

import { createSupabaseUserServerActionClient } from "@/supabase-clients/user/createSupabaseUserServerActionClient";
import { SAPayload } from "@/types";
import { SAPayload } from '@/types';

export async function refreshSessionAction(): Promise<SAPayload> {
/*
const supabaseClient = createSupabaseUserServerActionClient();
const refreshSessionResponse = await supabaseClient.auth.refreshSession();
Expand All @@ -13,6 +13,9 @@ export async function refreshSessionAction(): Promise<SAPayload> {
message: refreshSessionResponse.error.message,
};
}
*/

//TODO re-implement with Auth.js or remove

return {
status: 'success',
Expand Down
33 changes: 23 additions & 10 deletions src/middleware.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,9 @@
import {
createMiddlewareClient,
type User,
} from '@supabase/auth-helpers-nextjs';
import type { NextRequest } from 'next/server';
import { NextResponse } from 'next/server';
// const matchAppAdmin = match('/app_admin_preview/(.*)?');
import { auth } from '@/auth';
import { NextResponse } from 'next/server';
import { match } from 'path-to-regexp';
import type { Database } from './lib/database.types';
import { toSiteURL } from './utils/helpers';
import { authUserMetadataSchema } from './utils/zod-schemas/authUserMetadata';
import { serverGetLoggedInUser } from './utils/server/serverGetLoggedInUser';

const onboardingPaths = `/onboarding/(.*)?`;
// Using a middleware to protect pages from unauthorized access
Expand Down Expand Up @@ -48,7 +43,8 @@ function isUnprotectedPage(pathname: string) {
});
}

function shouldOnboardUser(pathname: string, user: User | undefined) {
function shouldOnboardUser(pathname: string, userId: string) {
/*
const matchOnboarding = match(onboardingPaths);
const isOnboardingRoute = matchOnboarding(pathname);
if (!isUnprotectedPage(pathname) && user && !isOnboardingRoute) {
Expand All @@ -69,11 +65,17 @@ function shouldOnboardUser(pathname: string, user: User | undefined) {
}
console.log('user is onboarded');
return false;
*/
return true;
//TODO figure way to store user metadata (extend user_profile table?)
}

// this middleware refreshes the user's session and must be run
// for any Server Component route that uses `createServerComponentSupabaseClient`
export async function middleware(req: NextRequest) {
// renamed while moving to auth.js

/*
export async function middleware_NEXTBASE_LEGACY(req: NextRequest) {
const res = NextResponse.next();
const supabase = createMiddlewareClient<Database>({ req, res });
const sessionResponse = await supabase.auth.getSession();
Expand Down Expand Up @@ -121,6 +123,17 @@ export async function middleware(req: NextRequest) {
return res;
}
*/

export default auth(async (req) => {
const user = await serverGetLoggedInUser();
if (shouldOnboardUser(req.nextUrl.pathname, user.id)) {
return NextResponse.redirect(toSiteURL('/onboarding'));
} else {
return NextResponse.next();
}
});

export const config = {
matcher: [
/*
Expand Down
Loading

0 comments on commit a38e0c1

Please sign in to comment.