タケユー・ウェブ日報

Ruby on Rails や Flutter といったWeb・モバイルアプリ技術を武器にお客様のビジネス立ち上げを支援する、タケユー・ウェブ株式会社の技術ブログです。

Ruby で Firebase User を作成

動機

  • Firebase Auth を使ったWebアプリの Rails System Spec を書きたい
  • フロントエンドで Firebase JavaScript SDK を使っているため、バックエンドでのstubでは書けない

サンプルコード(一部抜粋)

  • Google::Apis::IdentitytoolkitV3::IdentityToolkitService Google::Apis::IdentitytoolkitV3::SignupNewUserRequest で作成できる
  • メールアドレスは実際に受信するなら MailSlurp あたりを使って用意する
require 'rails_helper'
require 'google/apis/identitytoolkit_v3'

RSpec.feature 'login', type: :system, js: true do
  def sign_in(email, password)
    visit root_path
    within(:css, '#login_modal') do
      fill_in('login_email', with: email)
      fill_in('login_password', with: password)
      find_button('Login', wait: 10).click  # Firebase JavaScript SDK によるメールアドレス認証
    end
    expect(page).to have_button('Logout', wait: 10)
  end

  def sign_out
    find_button('Logout', wait: 10).click
  end

  before do
    # Create Firebase User
    # https://qiita.com/asflash8/items/17775895e35272ae7ec8
    # https://firebase.google.com/docs/auth/admin/manage-users?hl=ja
    firebase_service_account_json_key = Rails.application.credentials.dig(:raw, :firebase_service_account_json_key)
    @identity_toolkit_service = Google::Apis::IdentitytoolkitV3::IdentityToolkitService.new
    @identity_toolkit_service.authorization = Google::Auth::ServiceAccountCredentials.make_creds(
      json_key_io: StringIO.new(firebase_service_account_json_key),
      scope: 'https://www.googleapis.com/auth/identitytoolkit'
    )
    user_data = {
      email: 'test@takeyuweb.co.jp',
      email_verified: true,
      password: 'password1234',
      disabled: false
    }
    request = Google::Apis::IdentitytoolkitV3::SignupNewUserRequest.new(user_data)
    @account = @identity_toolkit_service.signup_new_user(request)

    # Signin
    sign_in(user_data.fetch(:email), user_data.fetch(:password))

    @current_user = User.find_by(email: user_data.fetch(:email))
    @password = user_data.fetch(:password)
  end

  after do
    if @account
      request = Google::Apis::IdentitytoolkitV3::DeleteAccountRequest.new(local_id: @account.local_id)
      @identity_toolkit_service.delete_account(request)
    end
  rescue Google::Apis::ClientError => e
    Rails.logger.error(e.message)
  end

  scenario "edit profile" do
    visit root_path
    find_link('Profile').click

    expect(page).to have_field('Name')
    expect(page).to have_field('Telephone')

    fill_in 'Name', with: 'Yuichi Takeuchi'
    fill_in 'Telephone', with: '81487003094'

    # (snip)
  end
end

参考

qiita.com

firebase.google.com