Class: Firefighter::TokenGenerator

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

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(service_account_email:, private_key:, algorithm:, logger: Logger.new(STDOUT)) ⇒ TokenGenerator

Returns a new instance of TokenGenerator.



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

def initialize(service_account_email:, private_key:, algorithm:, logger: Logger.new(STDOUT))
  @service_account_email = 
  @private_key = private_key
  @algorithm = algorithm
  @logger = logger
end

Class Method Details

.from_envObject



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

def self.from_env
  config = {
    service_account_email: ENV['FIREBASE_SERVICE_ACCOUNT_EMAIL'],
    private_key: OpenSSL::PKey::RSA.new(ENV['FIREBASE_PRIVATE_KEY_DATA']),
    algorithm: 'RS256',
  }
  new(config)
end

Instance Method Details

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



22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/firefighter/token_generator.rb', line 22

def create_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

#read_token(token) ⇒ Object



37
38
39
# File 'lib/firefighter/token_generator.rb', line 37

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