0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Firebase Auth の サービスアカウントを環境によって切り替える方法

0
Last updated at Posted at 2023-11-24

概要

ステージング環境で my-project-dev というプロジェクトをFirebase で作っており、
本番環境では my-project-production というプロジェクトを作っているときに、
どうやって環境に従ってFirebaseAuthのサービスアカウントのロード(json)を切り替えようかという話。

解決策

export FIREBASE_CREDENTIAL_JSON=$(cat firebase_dev.json | base64 -w 0)

みたいにして、json を base64で環境変数にぶち込みます。

読み込み方

Node.js

node.js だったら、

import * as admin from "firebase-admin";
import { initializeApp, getApps, cert, applicationDefault } from 'firebase-admin/app';
import { getAuth } from "firebase-admin/auth";

const tmpJson = process.env.FIREBASE_CREDENTIAL_JSON as string;
const decodedFile = Buffer.from(tmpJson, 'base64')
const decodedJson = JSON.parse(decodedFile.toString());

const serviceAccount = decodedJson as admin.ServiceAccount;

みたいにして読み込みます。

Python

Python だったら、

import os
import base64
import re
import uuid
import datetime
import json

from fastapi.encoders import jsonable_encoder
from fastapi.responses import JSONResponse


import firebase_admin
from firebase_admin import credentials

tmp = os.getenv("FIREBASE_CREDENTIAL_JSON")
tmp2 = base64.b64decode(tmp.encode())
firebase_dict = json.loads(tmp2)
cred = credentials.Certificate(firebase_dict)
storage_bucket = os.getenv("STORAGE_BUCKET")
firebase_admin.initialize_app(cred, {"storageBucket": storage_bucket})

みたいな感じで読み込みます。

以上。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?