refactor: Replicate Drop's authentication system exactly

This commit is contained in:
Usman Baig
2026-01-16 14:11:14 +01:00
parent b66f367c94
commit 0c3fd5f766
4 changed files with 53 additions and 38 deletions

View File

@@ -13,8 +13,10 @@ function AuthCallbackContent() {
const processedRef = useRef(false) const processedRef = useRef(false)
useEffect(() => { useEffect(() => {
// * Prevent double execution (React Strict Mode or fast re-renders)
if (processedRef.current) return if (processedRef.current) return
// * Check for direct token passing (from auth-frontend direct login)
const token = searchParams.get('token') const token = searchParams.get('token')
const refreshToken = searchParams.get('refresh_token') const refreshToken = searchParams.get('refresh_token')
@@ -38,14 +40,21 @@ function AuthCallbackContent() {
const code = searchParams.get('code') const code = searchParams.get('code')
const state = searchParams.get('state') const state = searchParams.get('state')
// * Skip if params are missing (might be initial render before params are ready)
if (!code || !state) return if (!code || !state) return
processedRef.current = true processedRef.current = true
const storedState = sessionStorage.getItem('oauth_state') const storedState = localStorage.getItem('oauth_state')
const codeVerifier = sessionStorage.getItem('oauth_code_verifier') const codeVerifier = localStorage.getItem('oauth_code_verifier')
if (!code || !state) {
setError('Missing code or state')
return
}
if (state !== storedState) { if (state !== storedState) {
// * Debugging: Log state mismatch to help user diagnose
console.error('State mismatch', { received: state, stored: storedState }) console.error('State mismatch', { received: state, stored: storedState })
setError('Invalid state') setError('Invalid state')
return return
@@ -53,7 +62,7 @@ function AuthCallbackContent() {
const exchangeCode = async () => { const exchangeCode = async () => {
try { try {
const authApiUrl = process.env.NEXT_PUBLIC_AUTH_API_URL || 'https://auth-api.ciphera.net' const authApiUrl = process.env.NEXT_PUBLIC_AUTH_API_URL || process.env.NEXT_PUBLIC_AUTH_URL || 'http://localhost:8081'
const res = await fetch(`${authApiUrl}/oauth/token`, { const res = await fetch(`${authApiUrl}/oauth/token`, {
method: 'POST', method: 'POST',
headers: { headers: {
@@ -79,12 +88,13 @@ function AuthCallbackContent() {
login(data.access_token, data.refresh_token, { login(data.access_token, data.refresh_token, {
id: payload.sub, id: payload.sub,
email: payload.email || 'user@ciphera.net', email: payload.email || 'user@ciphera.net', // Fallback if email claim missing
totp_enabled: payload.totp_enabled || false totp_enabled: payload.totp_enabled || false
}) })
sessionStorage.removeItem('oauth_state') // * Cleanup
sessionStorage.removeItem('oauth_code_verifier') localStorage.removeItem('oauth_state')
localStorage.removeItem('oauth_code_verifier')
router.push('/') router.push('/')
} catch (err: any) { } catch (err: any) {

View File

@@ -1,7 +1,7 @@
'use client' 'use client'
import { useAuth } from '@/lib/auth/context' import { useAuth } from '@/lib/auth/context'
import { initiateOAuthFlow } from '@/lib/api/oauth' import { initiateOAuthFlow, initiateSignupFlow } from '@/lib/api/oauth'
import LoadingOverlay from '@/components/LoadingOverlay' import LoadingOverlay from '@/components/LoadingOverlay'
import SiteList from '@/components/sites/SiteList' import SiteList from '@/components/sites/SiteList'
@@ -30,10 +30,7 @@ export default function HomePage() {
Sign In Sign In
</button> </button>
<button <button
onClick={() => { onClick={() => initiateSignupFlow()}
const authUrl = process.env.NEXT_PUBLIC_AUTH_URL || 'https://auth.ciphera.net'
window.location.href = `${authUrl}/signup?client_id=analytics-app&redirect_uri=${encodeURIComponent((process.env.NEXT_PUBLIC_APP_URL || window.location.origin) + '/auth/callback')}&response_type=code`
}}
className="btn-secondary" className="btn-secondary"
> >
Sign Up Sign Up

View File

@@ -1,14 +1,13 @@
'use client' 'use client'
import { useEffect } from 'react' import { useEffect } from 'react'
import { initiateOAuthFlow } from '@/lib/api/oauth' import { initiateSignupFlow } from '@/lib/api/oauth'
import LoadingOverlay from '@/components/LoadingOverlay' import LoadingOverlay from '@/components/LoadingOverlay'
export default function SignupPage() { export default function SignupPage() {
useEffect(() => { useEffect(() => {
// * Immediately initiate OAuth flow when page loads // * Immediately initiate signup flow when page loads
// * The auth service will handle showing signup vs login initiateSignupFlow()
initiateOAuthFlow()
}, []) }, [])
return ( return (

View File

@@ -1,12 +1,14 @@
/** import { AUTH_URL, APP_URL } from './client'
* OAuth 2.0 PKCE utilities
*/
function generateRandomString(length: number): string { function generateRandomString(length: number): string {
const charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~' const charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~'
let result = ''
const values = new Uint8Array(length) const values = new Uint8Array(length)
crypto.getRandomValues(values) crypto.getRandomValues(values)
return Array.from(values, (x) => charset[x % charset.length]).join('') for (let i = 0; i < length; i++) {
result += charset[values[i] % charset.length]
}
return result
} }
async function generateCodeChallenge(codeVerifier: string): Promise<string> { async function generateCodeChallenge(codeVerifier: string): Promise<string> {
@@ -42,24 +44,31 @@ export async function generateOAuthParams(): Promise<OAuthParams> {
export async function initiateOAuthFlow(redirectPath = '/auth/callback') { export async function initiateOAuthFlow(redirectPath = '/auth/callback') {
if (typeof window === 'undefined') return if (typeof window === 'undefined') return
const params = await generateOAuthParams() const { state, codeVerifier, codeChallenge } = await generateOAuthParams()
const redirectUri = `${window.location.origin}${redirectPath}`
// Store params for verification in callback
localStorage.setItem('oauth_state', state)
localStorage.setItem('oauth_code_verifier', codeVerifier)
const redirectUri = encodeURIComponent(`${APP_URL}${redirectPath}`)
// Store PKCE params in sessionStorage for later use const loginUrl = `${AUTH_URL}/login?client_id=analytics-app&redirect_uri=${redirectUri}&response_type=code&state=${state}&code_challenge=${codeChallenge}&code_challenge_method=S256`
sessionStorage.setItem('oauth_state', params.state)
sessionStorage.setItem('oauth_code_verifier', params.codeVerifier) window.location.href = loginUrl
const authUrl = process.env.NEXT_PUBLIC_AUTH_URL || 'https://auth.ciphera.net'
const authApiUrl = process.env.NEXT_PUBLIC_AUTH_API_URL || 'https://auth-api.ciphera.net'
// Redirect to OAuth authorize endpoint
const authorizeUrl = new URL(`${authApiUrl}/oauth/authorize`)
authorizeUrl.searchParams.set('client_id', 'analytics-app')
authorizeUrl.searchParams.set('redirect_uri', redirectUri)
authorizeUrl.searchParams.set('response_type', 'code')
authorizeUrl.searchParams.set('state', params.state)
authorizeUrl.searchParams.set('code_challenge', params.codeChallenge)
authorizeUrl.searchParams.set('code_challenge_method', 'S256')
window.location.href = authorizeUrl.toString()
} }
export async function initiateSignupFlow(redirectPath = '/auth/callback') {
if (typeof window === 'undefined') return
const { state, codeVerifier, codeChallenge } = await generateOAuthParams()
// Store params for verification in callback
localStorage.setItem('oauth_state', state)
localStorage.setItem('oauth_code_verifier', codeVerifier)
const redirectUri = encodeURIComponent(`${APP_URL}${redirectPath}`)
const signupUrl = `${AUTH_URL}/signup?client_id=analytics-app&redirect_uri=${redirectUri}&response_type=code&state=${state}&code_challenge=${codeChallenge}&code_challenge_method=S256`
window.location.href = signupUrl
}