LoginSignup
33
16

More than 3 years have passed since last update.

Firebase Authentication for ruby

Last updated at Posted at 2021-02-05

概要

Java や Node などは Firebase Admin SDK を使用することで、Firebase Authentication の操作をサーバーサイドで行うことが出来ますが、ruby には gem が用意されていません。
そのため、google-apis のライブラリを利用する必要があります。
その使い方のメモです。

利用可能なAPI

github のレポジトリgenerated/google-apis-identitytoolkit_v3 にライブラリのソースコードが配置してあります。(v3 部分が変わっているかもしれません)
https://github.com/googleapis/google-api-ruby-client/tree/master/generated/google-apis-identitytoolkit_v3

lib/google/apis/identitytoolkit_v3/service.rb 内にAPIクライアント、
lib/google/apis/identitytoolkit_v3/classes.rb 内にAPI実行時に使用するクラスがあります。

ライブラリの利用

ライブラリインストール

Gemfile
gem 'google-apis-identitytoolkit_v3'

認証

FirebaseConsole でダウンロードしてきたサービスアカウントのファイルを利用する場合

service_account = "/path/to/serviceAccountKey.json"
client = Google::Apis::IdentitytoolkitV3::IdentityToolkitService.new
client.authorization = Google::Auth::ServiceAccountCredentials.make_creds(
  json_key_io: File.open(service_account),
  scope: 'https://www.googleapis.com/auth/identitytoolkit'
)

環境変数を利用する場合

以下の環境変数を設定しておきます。値はFirebaseConsoleからダウンロードできるサービスアカウントのファイル内の値です。

  • GOOGLE_ACCOUNT_TYPE
  • GOOGLE_CLIENT_ID
  • GOOGLE_CLIENT_EMAIL
  • GOOGLE_PRIVATE_KEY
client = Google::Apis::IdentitytoolkitV3::IdentityToolkitService.new
client.authorization = Google::Auth::ServiceAccountCredentials.make_creds(
  scope: 'https://www.googleapis.com/auth/identitytoolkit'
)

APIの利用

uid は、FirebaseConsole の Authentication ページの Users タブ内で確認できます。

アカウント情報取得

uid = 'uid'
request = Google::Apis::IdentitytoolkitV3::GetAccountInfoRequest.new(local_id: [uid])
account = client.get_account_info(request)
pp account.users[0]

ユーザー作成

request = Google::Apis::IdentitytoolkitV3::SignupNewUserRequest.new(
  display_name: display_name,
  email: email,
  password: password,
  email_verified: true
)
result = client.signup_new_user(request)

ユーザー情報更新

uid = 'uid'
request = Google::Apis::IdentitytoolkitV3::SetAccountInfoRequest.new(
  local_id: uid,
  display_name: display_name_changed,
  email: email_changed,
  password: password_changed
)
result = client.set_account_info(request)

ユーザー削除

uid = 'uid'
request = Google::Apis::IdentitytoolkitV3::DeleteAccountRequest.new(
  local_id: uid
)
client.delete_account(request)

パスワードリセット、メールアドレス確認メール等を ruby から送る

ユーザー情報更新メソッドを利用することで、パスワードの変更や、email_verified の値を書き換えることが出来るため、ワンタイムトークンを発行しメールに記載する等の方法で実装できそうです。

参考

33
16
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
33
16