-
Notifications
You must be signed in to change notification settings - Fork 2
fix: standardize auth - single source of truth, getUser() for authz #154
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
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
9faaf68
fix: standardize auth flow - single source of truth, getUser() for au…
deepu0 f1874d2
Merge remote-tracking branch 'origin/main' into fix/auth-standardization
deepu0 bdb0de0
fix: resolve build failures - missing blog images and layout cross-br…
deepu0 b938ab0
fix: address PR review - single response in middleware, broader match…
deepu0 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| import { NextResponse } from 'next/server'; | ||
| import { getAuthState } from '@/lib/auth'; | ||
|
|
||
| // Never cache — this reflects per-request session state. | ||
| export const dynamic = 'force-dynamic'; | ||
| export const revalidate = 0; | ||
|
|
||
| export async function GET() { | ||
| const { isAdmin, role } = await getAuthState(); | ||
| return NextResponse.json( | ||
| { isAdmin, role: role ?? null }, | ||
| { headers: { 'Cache-Control': 'no-store, max-age=0' } } | ||
| ); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Binary file added
BIN
+631 KB
content/blog/images/blog_accessibility-best-practices-every-frontend-develo.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added
BIN
+475 KB
content/blog/images/blog_frontend-architecture-patterns-building-maintainab.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added
BIN
+536 KB
content/blog/images/blog_frontend-testing-strategies-that-actually-work-in-.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added
BIN
+554 KB
content/blog/images/blog_react-performance-optimization-a-practical-guide-f.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added
BIN
+565 KB
content/blog/images/blog_react-server-components-in-2026-a-practical-guide.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added
BIN
+570 KB
content/blog/images/blog_state-management-in-2026-signals-simplicity-and-th.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,115 @@ | ||
| import 'server-only'; | ||
| import { createServerClient, type CookieOptions } from '@supabase/ssr'; | ||
| import { cookies } from 'next/headers'; | ||
| import type { SupabaseClient, User } from '@supabase/supabase-js'; | ||
|
|
||
| const ADMIN_ROLES = ['admin', 'superadmin'] as const; | ||
|
|
||
| export interface AuthState { | ||
| user: User | null; | ||
| role: string | null; | ||
| isAdmin: boolean; | ||
| } | ||
|
|
||
| export class AuthError extends Error { | ||
| status: number; | ||
| constructor(message: string, status: number) { | ||
| super(message); | ||
| this.name = 'AuthError'; | ||
| this.status = status; | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * The single server-side Supabase client factory. | ||
| * Full cookie read/write so session refresh works in route handlers | ||
| * and server actions. (In Server Components, writes are no-ops — that's fine, | ||
| * middleware refreshes the session.) | ||
| */ | ||
| export async function getServerSupabase(): Promise<SupabaseClient> { | ||
| const cookieStore = await cookies(); | ||
| return createServerClient( | ||
| process.env.NEXT_PUBLIC_SUPABASE_URL!, | ||
| process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!, | ||
| { | ||
| cookies: { | ||
| get(name: string) { | ||
| return cookieStore.get(name)?.value; | ||
| }, | ||
| set(name: string, value: string, options: CookieOptions) { | ||
| try { | ||
| cookieStore.set({ name, value, ...options }); | ||
| } catch { | ||
| /* called from a Server Component — middleware handles refresh */ | ||
| } | ||
| }, | ||
| remove(name: string, options: CookieOptions) { | ||
| try { | ||
| cookieStore.set({ name, value: '', ...options }); | ||
| } catch { | ||
| /* called from a Server Component */ | ||
| } | ||
| }, | ||
| }, | ||
| } | ||
| ); | ||
| } | ||
|
|
||
| /** | ||
| * Returns the verified user (validated against the Supabase Auth server via | ||
| * getUser()). Use this for ALL authorization decisions — never getSession(), | ||
| * which only reads the (potentially forged) cookie without verifying the JWT. | ||
| */ | ||
| export async function getVerifiedUser( | ||
| client?: SupabaseClient | ||
| ): Promise<User | null> { | ||
| const supabase = client ?? (await getServerSupabase()); | ||
| const { | ||
| data: { user }, | ||
| error, | ||
| } = await supabase.auth.getUser(); | ||
| if (error) return null; | ||
| return user; | ||
| } | ||
|
|
||
| /** | ||
| * Resolves the full auth state with the canonical admin rule: | ||
| * admin if app_metadata.role OR users.user_role is in {admin, superadmin}. | ||
| * This is the ONE place role resolution lives. | ||
| */ | ||
| export async function getAuthState(): Promise<AuthState> { | ||
| const supabase = await getServerSupabase(); | ||
| const user = await getVerifiedUser(supabase); | ||
|
|
||
| if (!user) { | ||
| return { user: null, role: null, isAdmin: false }; | ||
| } | ||
|
|
||
| // 1. Prefer the role embedded in the verified JWT. | ||
| let role: string | null = (user.app_metadata as any)?.role ?? null; | ||
|
|
||
| // 2. Fall back to the users table when the JWT has no admin role. | ||
| if (!role || !ADMIN_ROLES.includes(role as any)) { | ||
| const { data: profile } = await supabase | ||
| .from('users') | ||
| .select('user_role') | ||
| .eq('id', user.id) | ||
| .maybeSingle(); | ||
| role = profile?.user_role ?? role; | ||
| } | ||
|
|
||
| const isAdmin = role != null && ADMIN_ROLES.includes(role as any); | ||
| return { user, role, isAdmin }; | ||
| } | ||
|
|
||
| /** | ||
| * Guard for API routes and server actions. Returns the AuthState when the | ||
| * caller is an admin; otherwise throws AuthError (401 if unauthenticated, | ||
| * 403 if authenticated but not admin). | ||
| */ | ||
| export async function requireAdmin(): Promise<AuthState> { | ||
| const state = await getAuthState(); | ||
| if (!state.user) throw new AuthError('Unauthorized', 401); | ||
| if (!state.isAdmin) throw new AuthError('Forbidden', 403); | ||
| return state; | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🌐 Web query:
In@supabase/supabase-jsv2.108.0, what error does auth.getUser() return when no session is present, and how should it be distinguished from network or auth service failures?💡 Result:
In
@supabase/supabase-jsv2.108.0, when no session is present, auth.getUser returns an object where the data.user property is null, and the error property is typically null (or specifically indicates no error occurred, as the absence of a session is a valid state) [1][2]. To distinguish between the absence of a session and actual service failures (such as network issues or auth server errors), you should inspect the returned error object: 1. No Session (Expected State): If data.user is null and error is null, this simply means the client has no valid session. This is the expected behavior when a user is not logged in [1][2]. 2. Auth/Network Failures: If the error property is populated, it will contain an AuthError (often an AuthApiError or similar) [3][4]. These errors, such as a 400 status code with a "session_not_found" or other service-level messages, indicate that the attempt to retrieve the user failed due to an issue with the request, the token, or the connection to the Supabase Auth server [4][5]. For robust error handling, you should prioritize checking if the error object is truthy before assuming that a null user signifies a logged-out state [5]. If an error exists, you can inspect its properties (e.g., status or code) to determine if it is a transient network issue or a persistent service-side failure [4]. Note that auth.getUser performs a network request to the Supabase Auth server to verify the authenticity of the session [6][7]. This distinguishes it from auth.getSession, which primarily reads from local storage and should not be used for critical authorization checks on the server [8][7].Citations:
getUserreturns null if there is no session supabase/auth-js#876Don't collapse
getUser()errors intonull.auth.getUser()returnserror = nullfor the expected no-session case; unexpected auth/network failures should be rethrown so protected routes fail with a real server error instead of 401.🤖 Prompt for AI Agents