lib/namely/authenticator.rb in namely-0.0.1 vs lib/namely/authenticator.rb in namely-0.1.0
- old
+ new
@@ -65,11 +65,15 @@
# tokens["expires_in"] # => 1234
# tokens["token_type"] # => "bearer"
#
# @return [Hash]
def retrieve_tokens(options)
- request_tokens(options, "authorization_code", options.fetch(:code))
+ request_tokens(
+ options,
+ grant_type: "authorization_code",
+ code: options.fetch(:code),
+ )
end
# Get an updated access token using the refresh token.
#
# @param [Hash] options
@@ -93,28 +97,70 @@
# tokens["expires_in"] # => 1234
# tokens["token_type"] # => "bearer"
#
# @return [Hash]
def refresh_access_token(options)
- request_tokens(options, "refresh_token", options.fetch(:refresh_token))
+ request_tokens(
+ options,
+ grant_type: "refresh_token",
+ refresh_token: options.fetch(:refresh_token),
+ )
end
+ # Return the profile of the user accessing the API.
+ #
+ # @param [Hash] options
+ # @option options [String] access_token (required)
+ # @option options [String] subdomain (required)
+ #
+ # @return [Model] the profile of the current user.
+ def current_user(options)
+ access_token = options.fetch(:access_token)
+ subdomain = options.fetch(:subdomain)
+
+ user_url = URL.new(options.merge(
+ params: {
+ access_token: access_token,
+ },
+ path: "/api/v1/profiles/me",
+ )).to_s
+
+ response = RestClient.get(
+ user_url,
+ accept: :json,
+ )
+ build_profile(
+ access_token,
+ subdomain,
+ JSON.parse(response)["profiles"].first
+ )
+ end
+
private
attr_reader :client_id, :client_secret
- def request_tokens(options, grant_type, token)
+ def request_tokens(url_options, post_params)
response = RestClient.post(
- URL.new(options.merge(path: "/api/v1/oauth2/token")).to_s,
- grant_type: grant_type,
- client_id: client_id,
- client_secret: client_secret,
- refresh_token: token,
+ URL.new(url_options.merge(path: "/api/v1/oauth2/token")).to_s,
+ {
+ client_id: client_id,
+ client_secret: client_secret,
+ }.merge(post_params),
)
JSON.parse(response)
end
+ def build_profile(access_token, subdomain, attributes)
+ profile_gateway = ResourceGateway.new(
+ access_token: access_token,
+ endpoint: "profiles",
+ subdomain: subdomain,
+ )
+ Model.new(profile_gateway, attributes)
+ end
+
class URL
def initialize(options)
@options = options
end
@@ -147,17 +193,18 @@
map { |key, value| "#{CGI.escape(key.to_s)}=#{CGI.escape(value)}" }.
join("&")
end
def params
- options.fetch(:params, {}).merge(redirect_uri_param)
+ options.fetch(:params, {}).merge(optional_params)
end
- def redirect_uri_param
- if options.has_key?(:redirect_uri)
- { redirect_uri: options[:redirect_uri] }
- else
- {}
+ def optional_params
+ [:redirect_uri, :state].inject({}) do |additional_params, key|
+ if options.has_key?(key)
+ additional_params[key] = options[key]
+ end
+ additional_params
end
end
end
end
end