LoginSignup
1
0

More than 1 year has passed since last update.

FirebaseとHasuraの連携

Posted at

firebaseとHASURAの連携の勉強の一環としてメモを記載する。

Cloud Function for firebaseとは?

Cloud Functions for firebaseはGoogleが提供するクラウドサービスです。そのため、サーバーの構築や保守をすることなくプログラムを実行することができます。

firebase cloud function設定

※事前準備として、firebaseのプロジェクトを従量課金制に変更する必要がある。firebaseに必要なパッケージ、初期化設定を実施した後を記載
https://firebase.google.com/docs/cli?hl=ja

firebaseの初期化

firebase init

functionの設定

1.Functionsを選択
2.Use an existing project
3.firebaseのプロジェクト名を選択
4.Typescript
5.eslint => y
6.dependencies => y

functionsが作成される事を確認。

HASURAの環境構成変数を設定

firebase functions:config:set hasura.url="HASURAのURL" hasura.admin_secret="パスワード"

https://firebase.google.com/docs/functions/config-env?hl=ja

functionsの中身

概要として、firebaseのAuthenticationでユーザーが新規作成の時JWTトークン作成し返してくれる仕組みである。
functionsとしてやりたい事は、HASURAのエンドポイントの認証に必要な情報をJWTトークンの内容に埋め込む作業である。

import * as functions from 'firebase-functions'
import * as admin from 'firebase-admin'

//初期化
admin.initializeApp()

firebaseの新規作成時の処理

// HASURAのエンドポイントの内容を
export const setCustomClaims = functions.auth.user().onCreate(async (user) => {  
  const customClaims = {
    'https://hasura.io/jwt/claims': {
      'x-hasura-default-role': 'loginUser',
      'x-hasura-allowed-roles': ['loginUser'],
      'x-hasura-user-id': user.uid,
    },
  }
    //ログイン時にカスタムクレームを追加する処理
  try {
    await admin.auth().setCustomUserClaims(user.uid, customClaims)
    await admin.firestore().collection('user_meta').doc(user.uid).create({
      refreshTime: admin.firestore.FieldValue.serverTimestamp(),
    })
  } catch (e) {
    // エラー処理 ...省略
  }
})

HASURAの設定方法下記参照
https://hasura.io/docs/latest/graphql/core/auth/authentication/jwt.html

firebase deploy

firebase deploy --only functions
1
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
1
0