Skip to content

Instantly share code, notes, and snippets.

@IgorHalfeld
Last active February 4, 2024 18:02
Show Gist options
  • Save IgorHalfeld/7eb270afb290423ba0abacdaa80a8986 to your computer and use it in GitHub Desktop.
Save IgorHalfeld/7eb270afb290423ba0abacdaa80a8986 to your computer and use it in GitHub Desktop.
nuxt server methods auth middleware
// server/middleware/auth.ts
import { DecodedIdToken } from 'firebase-admin/lib/auth/token-verifier'
import { createAuth } from '@/libs/firebase/firebaseAdmin'
export interface AuthContext {
isAuthenticated: boolean
user: DecodedIdToken | null
}
export default defineEventHandler(async (event) => {
const config = useRuntimeConfig()
const url = getRequestURL(event)
const isApiCall = url.pathname.includes('/api')
if (!isApiCall) {
return
}
const contextAuth: AuthContext = {
isAuthenticated: false,
user: null,
}
const authorization = event.node.req.headers.authorization
if (!authorization) {
event.context.auth = contextAuth
return
}
const [, token] = authorization.split(' ')
const auth = createAuth({
projectId: config.public.firebaseAdminProjectId,
clientEmail: config.public.firebaseAdminClientEmail,
privateKey: config.public.firebaseAdminPrivateKey,
})
try {
const checkRevoked = false
const decoded = await auth.verifyIdToken(token, checkRevoked)
contextAuth.isAuthenticated = true
contextAuth.user = decoded as DecodedIdToken
event.context.auth = contextAuth
} catch (e) {
console.log('* auth error', e)
event.context.auth = contextAuth
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment