Skip to content

Instantly share code, notes, and snippets.

@tiagogeraldi
Created July 6, 2021 20:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tiagogeraldi/1dcb78bd2b91bb4f7249d1a8e1031daf to your computer and use it in GitHub Desktop.
Save tiagogeraldi/1dcb78bd2b91bb4f7249d1a8e1031daf to your computer and use it in GitHub Desktop.
Reading a Firebase/Firestore document with Ruby, REST API and Email / password based authentication
# frozen_string_literal: true
# Usage: Importer.new.read
require 'faraday'
class Importer
AUTH_URL = "https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword"
FIREBASE_API_KEY="CHANGE_ME - see the Settings page of your DB"
FIREBASE_PROJECT_ID="CHANGE_ME - the ID / Name of your Firestore project"
FIREBASE_USER_EMAIL="CHANGE_ME - the email of your user"
FIREBASE_USER_PASS="CHANGE_ME - the password of your user"
DOCUMENT="CHANGE_ME - the document you want to read"
def initialize
sign_in
end
def read
uri = "projects/#{FIREBASE_PROJECT_ID}/databases/(default)/documents/DOC#{DOCUMENT}"
puts JSON.parse(conn.get(uri).body)
end
private
def conn
@conn ||= Faraday.new(url: "https://firestore.googleapis.com/v1/") do |req|
req.headers['Authorization'] = "Bearer #{@token}"
req.headers['Content-Type'] = 'application/json'
end
end
def sign_in
auth = Faraday.post(AUTH_URL) do |req|
req.params = { key: FIREBASE_API_KEY }
req.headers['Content-Type'] = 'application/json'
req.body = { email: FIREBASE_USER_EMAIL, password: FIREBASE_USER_PASS, returnSecureToken: true }.to_json
end
auth = JSON.parse(auth.body)
@token = auth["idToken"]
end
end
@tiagogeraldi
Copy link
Author

tiagogeraldi commented Jul 6, 2021

Google documentation is not clear. There are some Firebase gems but I couldn't find anything that could resolve my problem.
I want to read a document stored on Firestore, authenticating by User / Pass, the ones you create on Firebase Authentication.

The solution uses REST API.

I couldn't find any documentation explaining how it should work exaclty. The steps are:

  • Authenticate passing email and password to the identitytoolkit.
  • Get the returning token.
  • Use the token to make Firebase requests as a Bearer token in the header.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment