Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: deprecate withApiAuth, withPageAuth, and withMiddlewareAuth. #364

Merged
merged 9 commits into from
Nov 4, 2022
5 changes: 5 additions & 0 deletions .changeset/nine-files-hammer.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@supabase/auth-helpers-nextjs': minor
---

chore: deprecate withApiAuth, withPageAuth, and withMiddlewareAuth.
35 changes: 25 additions & 10 deletions examples/nextjs/middleware.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,29 @@
import { withMiddlewareAuth } from '@supabase/auth-helpers-nextjs';

export const middleware = withMiddlewareAuth({
redirectTo: '/',
authGuard: {
isPermitted: async (user) => {
return user.email?.endsWith('@gmail.com') ?? false;
},
redirectTo: '/insufficient-permissions'
import { createMiddlewareSupabaseClient } from '@supabase/auth-helpers-nextjs';
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

export async function middleware(req: NextRequest) {
// We need to create a response and hand it to the supabase client to be able to modify the response headers.
const res = NextResponse.next();
// Create authenticated Supabase Client
const supabase = createMiddlewareSupabaseClient({ req, res });
// Check if we have a session
const {
data: { session }
} = await supabase.auth.getSession();

// Check auth condition
if (session?.user.email?.endsWith('@gmail.com')) {
// Authentication successful, forward request to protected route.
return res;
}
});

// Auth condition not met, redirect to home page.
const redirectUrl = req.nextUrl.clone();
redirectUrl.pathname = '/';
redirectUrl.searchParams.set(`redirectedFrom`, req.nextUrl.pathname);
return NextResponse.redirect(redirectUrl);
}

export const config = {
matcher: '/middleware-protected'
Expand Down
25 changes: 21 additions & 4 deletions examples/nextjs/pages/api/protected-route.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,25 @@
// pages/api/protected-route.ts
import { withApiAuth } from '@supabase/auth-helpers-nextjs';
import { NextApiHandler } from 'next';
import { createServerSupabaseClient } from '@supabase/auth-helpers-nextjs';

const ProtectedRoute: NextApiHandler = async (req, res) => {
// Create authenticated Supabase Client
const supabase = createServerSupabaseClient({ req, res });
// Check if we have a session
const {
data: { session }
} = await supabase.auth.getSession();

if (!session)
return res.status(401).json({
error: 'not_authenticated',
description:
'The user does not have an active session or is not authenticated'
});

export default withApiAuth(async function ProtectedRoute(req, res, supabase) {
// Run queries with RLS on the server
const { data } = await supabase.from('test').select('*');
const { data } = await supabase.from('users').select('*');
res.json(data);
});
};

export default ProtectedRoute;
64 changes: 33 additions & 31 deletions examples/nextjs/pages/github-provider-token.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
// pages/protected-page.js
import { User, withPageAuth } from '@supabase/auth-helpers-nextjs';
import {
User,
createServerSupabaseClient
} from '@supabase/auth-helpers-nextjs';
import { GetServerSidePropsContext } from 'next';
import Link from 'next/link';

export default function ProtectedPage({
Expand All @@ -24,36 +28,34 @@ export default function ProtectedPage({
);
}

export const getServerSideProps = withPageAuth({
redirectTo: '/',
async getServerSideProps(ctx, supabase) {
const {
data: { session },
error
} = await supabase.auth.getSession();
if (error) {
throw error;
}
if (!session) {
return { props: {} };
}
export const getServerSideProps = async (ctx: GetServerSidePropsContext) => {
// Create authenticated Supabase Client
const supabase = createServerSupabaseClient(ctx);
// Check if we have a session
const {
data: { session }
} = await supabase.auth.getSession();

// Retrieve provider_token & logged in user's third-party id from metadata
const { provider_token, user } = session;
const userId = user.user_metadata.user_name;
if (!session)
return {
redirect: {
destination: '/',
permanent: false
}
};

const allRepos = await (
await fetch(
`https://api.github.com/search/repositories?q=user:${userId}`,
{
method: 'GET',
headers: {
Authorization: `token ${provider_token}`
}
}
)
).json();
// Retrieve provider_token & logged in user's third-party id from metadata
const { provider_token, user } = session;
const userId = user.user_metadata.user_name;

return { props: { allRepos } };
}
});
const allRepos = await (
await fetch(`https://api.github.com/search/repositories?q=user:${userId}`, {
method: 'GET',
headers: {
Authorization: `token ${provider_token}`
}
})
).json();

return { props: { user, allRepos } };
};
4 changes: 2 additions & 2 deletions examples/nextjs/pages/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,8 @@ const LoginPage: NextPage = () => {
return (
<>
<p>
[<Link href="/profile">withPageAuth</Link>] | [
<Link href="/protected-page">supabaseServerClient</Link>] |{' '}
[<Link href="/profile">getServerSideProps</Link>] | [
<Link href="/protected-page">server-side RLS</Link>] |{' '}
<button
onClick={() =>
supabaseClient.auth.updateUser({ data: { test1: 'updated' } })
Expand Down
32 changes: 29 additions & 3 deletions examples/nextjs/pages/profile.tsx
Original file line number Diff line number Diff line change
@@ -1,18 +1,44 @@
// pages/profile.js
import { withPageAuth, User } from '@supabase/auth-helpers-nextjs';
import {
createServerSupabaseClient,
User
} from '@supabase/auth-helpers-nextjs';
import { GetServerSidePropsContext } from 'next';
import Link from 'next/link';

export default function Profile({ user }: { user: User }) {
return (
<>
<p>
[<Link href="/">Home</Link>] | [
<Link href="/protected-page">supabaseServerClient</Link>]
<Link href="/protected-page">server-side RLS</Link>]
</p>
<div>Hello {user.email}</div>
<pre>{JSON.stringify(user, null, 2)}</pre>
</>
);
}

export const getServerSideProps = withPageAuth({ redirectTo: '/' });
export const getServerSideProps = async (ctx: GetServerSidePropsContext) => {
// Create authenticated Supabase Client
const supabase = createServerSupabaseClient(ctx);
// Check if we have a session
const {
data: { session }
} = await supabase.auth.getSession();

if (!session)
return {
redirect: {
destination: '/',
permanent: false
}
};

return {
props: {
initialSession: session,
user: session.user
}
};
};
42 changes: 32 additions & 10 deletions examples/nextjs/pages/protected-page.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
// pages/protected-page.js
import { withPageAuth, User } from '@supabase/auth-helpers-nextjs';
import {
createServerSupabaseClient,
User
} from '@supabase/auth-helpers-nextjs';
import { GetServerSidePropsContext } from 'next';
import Link from 'next/link';

export default function ProtectedPage({
Expand All @@ -13,7 +17,7 @@ export default function ProtectedPage({
<>
<p>
[<Link href="/">Home</Link>] | [
<Link href="/profile">withPageAuth</Link>]
<Link href="/profile">getServerSideProps</Link>]
</p>
<div>Protected content for {user?.email}</div>
<p>server-side fetched data with RLS:</p>
Expand All @@ -24,12 +28,30 @@ export default function ProtectedPage({
);
}

export const getServerSideProps = withPageAuth({
redirectTo: '/',
async getServerSideProps(ctx, supabase) {
// Run queries with RLS on the server
const { data } = await supabase.from('users').select('*');
export const getServerSideProps = async (ctx: GetServerSidePropsContext) => {
// Create authenticated Supabase Client
const supabase = createServerSupabaseClient(ctx);
// Check if we have a session
const {
data: { session }
} = await supabase.auth.getSession();

return { props: { data: data ?? [] } };
}
});
if (!session)
return {
redirect: {
destination: '/',
permanent: false
}
};

// Run queries with RLS on the server
const { data } = await supabase.from('users').select('*');

return {
props: {
initialSession: session,
user: session.user,
data: data ?? []
}
};
};
Loading