Skip to content

Commit

Permalink
fix for emulator environment
Browse files Browse the repository at this point in the history
  • Loading branch information
ciscorn committed Oct 24, 2024
1 parent 943d3af commit bcbd918
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 12 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@mierune/sveltekit-firebase-auth-ssr",
"version": "0.0.16",
"version": "0.0.17",
"scripts": {
"dev": "vite dev",
"build": "vite build && npm run package",
Expand Down
2 changes: 1 addition & 1 deletion src/hooks.client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,4 @@ initializeApp({
});

// 認証ライブラリのセットアップ
setupAuthClient(PUBLIC_FIREBASE_AUTH_EMULATOR_HOST);
setupAuthClient({ emulatorHost: PUBLIC_FIREBASE_AUTH_EMULATOR_HOST });
29 changes: 19 additions & 10 deletions src/lib/firebase-auth/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@

import {
Auth,
ServiceAccountCredential,
type FirebaseIdToken,
type KeyStorer
type KeyStorer,
type Credential
} from 'firebase-auth-cloudflare-workers-x509';
import { type Handle, redirect, error, type Cookies } from '@sveltejs/kit';
import { env } from '$env/dynamic/public';
Expand All @@ -18,7 +18,7 @@ export {

export type AuthHandleOptions = {
projectId: string;
serviceAccountCredential?: ServiceAccountCredential;
serviceAccountCredential?: Credential;
keyStore: (platform: Readonly<App.Platform> | undefined) => KeyStorer;
guardPathPattern?: RegExp;
};
Expand All @@ -28,6 +28,15 @@ const emulatorEnv = {
FIREBASE_AUTH_EMULATOR_HOST: env.PUBLIC_FIREBASE_AUTH_EMULATOR_HOST
};

export class NopCredential implements Credential {
async getAccessToken() {
return {
access_token: 'owner',
expires_in: 9 * 3600
};
}
}

/**
* 認証ミドルウェア
*/
Expand All @@ -37,8 +46,12 @@ export function createAuthHandle({
keyStore: keyStoreMaker
}: AuthHandleOptions): Handle {
return async ({ event, resolve }) => {
if (!serviceAccountCredential && !emulatorEnv.FIREBASE_AUTH_EMULATOR_HOST) {
console.error('FIREBASE_SERVICE_ACCOUNT_KEY is not set. Authentication will not work.');
if (!serviceAccountCredential) {
if (emulatorEnv.FIREBASE_AUTH_EMULATOR_HOST) {
serviceAccountCredential ||= new NopCredential();
} else {
console.error('service account credential is not set. Authentication will not work.');
}
}

const auth = getAuth(projectId, keyStoreMaker(event.platform), serviceAccountCredential);
Expand Down Expand Up @@ -76,11 +89,7 @@ export function createAuthHandle({
};
}

export function getAuth(
projectId: string,
keyStore: KeyStorer,
credential?: ServiceAccountCredential
) {
export function getAuth(projectId: string, keyStore: KeyStorer, credential?: Credential) {
return Auth.getOrInitialize(projectId, keyStore, credential);
}

Expand Down

0 comments on commit bcbd918

Please sign in to comment.