Created
July 6, 2021 20:23
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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:
identitytoolkit
.