Class: Firefighter::TokenGenerator

Inherits:
Object
  • Object
show all
Includes:
Web
Defined in:
lib/firefighter/token_generator.rb

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Web

#call, #logger, #sse

Constructor Details

#initialize(service_account_email:, service_account_private_key:, algorithm: 'RS256') ⇒ TokenGenerator

Returns a new instance of TokenGenerator.



15
16
17
18
19
# File 'lib/firefighter/token_generator.rb', line 15

def initialize(service_account_email:, service_account_private_key:, algorithm: 'RS256')
  @service_account_email = 
  @algorithm = algorithm
  @private_key = OpenSSL::PKey::RSA.new()
end

Class Method Details

.from_envObject



8
9
10
11
12
13
# File 'lib/firefighter/token_generator.rb', line 8

def self.from_env
  new(
    service_account_email: ENV['FIREBASE_SERVICE_ACCOUNT_EMAIL'],
    service_account_private_key: ENV['FIREBASE_SERVICE_ACCOUNT_PRIVATE_KEY'],
  )
end

Instance Method Details

#create_access_token(expiration: 60 * 60) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
# File 'lib/firefighter/token_generator.rb', line 31

def create_access_token(expiration: 60 * 60)
  now_seconds = Time.now.to_i
  payload = {
      iss: @service_account_email,
      scope: 'https://www.googleapis.com/auth/identitytoolkit',
      aud: 'https://accounts.google.com/o/oauth2/token',
      iat: now_seconds,
      exp: now_seconds + expiration, # Maximum expiration time is one hour
  }
  ::JWT.encode(payload, @private_key, @algorithm)
end

#create_custom_token(uid, data: {}, expiration: 60 * 60) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/firefighter/token_generator.rb', line 43

def create_custom_token(uid, data: {}, expiration: 60 * 60)
  now_seconds = Time.now.to_i
  payload = {
    iss: @service_account_email,
    sub: @service_account_email,
    aud: 'https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit',
    iat: now_seconds,
    exp: now_seconds + expiration, # Maximum expiration time is one hour
    uid: uid,
    data: data,
  }

  ::JWT.encode(payload, @private_key, @algorithm)
end

#fetch_access_tokenObject



21
22
23
24
25
26
27
28
29
# File 'lib/firefighter/token_generator.rb', line 21

def fetch_access_token
  url = 'https://accounts.google.com/o/oauth2/token'
  data = {
    assertion: create_access_token,
    grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer'
  }
  response = call(:post, url, data)
  response['access_token']
end

#read_token(token) ⇒ Object



58
59
60
# File 'lib/firefighter/token_generator.rb', line 58

def read_token(token)
  JWT.decode(token, @private_key, true, algorithm: @algorithm).first
end