Skip to content

Instantly share code, notes, and snippets.

@HGebhardt
Forked from PJUllrich/IdentitytoolkitV3.rb
Last active February 22, 2021 06:39
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 HGebhardt/8316117c20cfc4c2af2a14d748c82db4 to your computer and use it in GitHub Desktop.
Save HGebhardt/8316117c20cfc4c2af2a14d748c82db4 to your computer and use it in GitHub Desktop.
require 'google/apis/identitytoolkit_v3'
require 'googleauth'
require 'json'
# Creates user accounts with email and password
class FirebaseAccountManager
# Konstanten ruhig in die Klassen ziehen, wenn die einen direkten Bezug haben
SCOPE = [
'https://www.googleapis.com/auth/firebase',
'https://www.googleapis.com/auth/identitytoolkit',
'https://www.googleapis.com/auth/userinfo.email'
].join(' ')
CREDENTIALS_PATH = 'credentials.json'.freeze
attr_accessor :service
# Wenn man keyword arguments mit default values nimmt, dann hast du eine Chance die Werte zu überschreiben
def initialize(scope: SCOPE, credentials_file: CREDENTIALS_PATH)
authorizer = Google::Auth::ServiceAccountCredentials.make_creds(
json_key_io: File.open(credentials_file),
scope: scope
)
@service = Google::Apis::IdentitytoolkitV3::IdentityToolkitService.new
@service.authorization = authorizer
end
# In solchen Situationen finde ich keyword arguments immer besser.
def create_user(email:, password:, uid:)
request = Google::Apis::IdentitytoolkitV3::SignupNewUserRequest.new(
email: email,
password: password,
local_id: uid
)
@service.signup_new_user(request)
end
def get_user(uid)
request = Google::Apis::IdentitytoolkitV3::GetAccountInfoRequest.new(
local_id: [uid]
)
@service.get_account_info(request)
end
def create_if_new(uid, email, password)
response = get_user(uid)
# Bie collections (was `users` bestimmt ist) muss man immer aufpassen, ob man `.nil?` oder `.empty?` verwendet.
return unless response.users.nil?
create_user(email: email, password: password, uid: uid)
end
end
manager = FirebaseAccountManager.new
uid = '736651e4-d0cd-4e26-b882-3d27635455bc'
email = 'peter.ullrich6@studitemps.de'
password = 'superSecret123'
response = manager.create_if_new(uid, email, password)
puts JSON.pretty_generate(response)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment