Skip to content

Commit

Permalink
fix(auth): admin app (#1179)
Browse files Browse the repository at this point in the history
  • Loading branch information
lindtvedtsebastian authored Aug 24, 2023
1 parent 7f7c202 commit 7fbe82b
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 13 deletions.
10 changes: 5 additions & 5 deletions next-tavla/pages/api/login.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,21 @@
import { initializeAdminApp } from 'Admin/utils/firebase'
import { initializeOrGetAdminApp } from 'Admin/utils/firebase'
import { auth } from 'firebase-admin'
import { NextApiRequest, NextApiResponse } from 'next'

const app = initializeOrGetAdminApp()

export default async function handler(
request: NextApiRequest,
response: NextApiResponse,
) {
initializeAdminApp()

const authorization = request.headers.authorization
if (authorization?.startsWith('Bearer ')) {
const idToken = authorization.split('Bearer ')[1] ?? ''
const decodedToken = await auth().verifyIdToken(idToken)
const decodedToken = await auth(app).verifyIdToken(idToken)

if (decodedToken) {
const expiresIn = 60 * 60 * 24 * 10 // Ten days
const sessionCookie = await auth().createSessionCookie(idToken, {
const sessionCookie = await auth(app).createSessionCookie(idToken, {
expiresIn,
})

Expand Down
14 changes: 6 additions & 8 deletions next-tavla/src/Admin/utils/firebase.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,21 @@
import admin, { auth } from 'firebase-admin'
import { applicationDefault } from 'firebase-admin/app'
import { applicationDefault, getApp } from 'firebase-admin/app'

initializeAdminApp()
const app = initializeOrGetAdminApp()

export function initializeAdminApp() {
export function initializeOrGetAdminApp() {
if (admin.apps.length <= 0) {
admin.initializeApp({
return admin.initializeApp({
credential: applicationDefault(),
databaseURL:
process.env.DATABASE_URL ??
'https://entur-tavla-staging.firebaseio.com',
})
}
return getApp()
}

export async function verifySession(session?: string) {
if (!session) return null
try {
return await auth().verifySessionCookie(session, true)
return await auth(app).verifySessionCookie(session, true)
} catch {
return null
}
Expand Down

0 comments on commit 7fbe82b

Please sign in to comment.