Class: Pusher::Authenticator

Inherits:
Object
  • Object
show all
Defined in:
lib/pusher-platform/authenticator.rb

Instance Method Summary collapse

Constructor Details

#initialize(instance_id, key_id, key_secret) ⇒ Authenticator

Returns a new instance of Authenticator.



9
10
11
12
13
# File 'lib/pusher-platform/authenticator.rb', line 9

def initialize(instance_id, key_id, key_secret)
  @instance_id = instance_id
  @key_id = key_id
  @key_secret = key_secret
end

Instance Method Details

#authenticate(request, options) ⇒ Object

Takes a Rack request to the authorization endpoint and and handles it either returning a new access/refresh token pair, or an error.

Parameters:

  • request (Rack::Request)

    the request to authenticate

Returns:

  • the response object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/pusher-platform/authenticator.rb', line 20

def authenticate(request, options)
  form_data = Rack::Utils.parse_nested_query request.body.read
  grant_type = form_data['grant_type']

  if grant_type == "client_credentials"
    return authenticate_with_client_credentials(options)
  elsif grant_type == "refresh_token"
    old_refresh_jwt = form_data['refresh_token']
    return authenticate_with_refresh_token(old_refresh_jwt, options)
  else
    return response(401, {
      error: "unsupported_grant_type"
    })
  end
end

#generate_access_token(options) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/pusher-platform/authenticator.rb', line 36

def generate_access_token(options)
  now = Time.now.utc.to_i

  claims = {
    app: @instance_id,
    iss: "api_keys/#{@key_id}",
    iat: now - TOKEN_LEEWAY,
    exp: now + TOKEN_EXPIRY + TOKEN_LEEWAY,
  }

  claims.merge!({ sub: options[:user_id] }) unless options[:user_id].nil?
  claims.merge!({ su: true }) if options[:su]

  {
    token: JWT.encode(claims, @key_secret, 'HS256'),
    expires_in: TOKEN_EXPIRY
  }
end