Why Gemfury? Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Debian packages RPM packages NuGet packages

Repository URL to install this package:

Details    
namara / lib / authenticator.rb
Size: Mime:
class Authenticator
  attr_reader :user_id, :profile

  protected

  # Protected constructor so child classes can call super.
  def initialize(account_url)
    @account_url = account_url
    fetch_profile
  end

  def fetch_token
    begin
      response = token_request.execute
      return JSON.parse(response)['jwt']
    rescue => e
      raise ::Namara::RequestError.new(e)
    end
  end

  private

  def fetch_profile
    begin
      response = profile_request.execute
      @profile = parse_profile(response)
      @user_id = @profile[:id]
    rescue KeyError => e
      raise UserNotFound.new("User not found for token on domain #{account_url}")
    rescue => e
      raise ::Namara::RequestError.new(e)
    end
  end

  def parse_profile(json)
    profile = JSON.parse(json)

    # White list the following fields to expose
    {
      name: profile['name'],
      email: profile['email'],
      id: profile['id'],
      email_hash: profile['email_hash'],
      api_key: profile['api_key']
    }
  end

  def profile_request
    RestClient::Request.new(method: "POST", url: profile_url, headers: headers, timeout: 5)
  end

  def profile_url
    "#{@account_url}/users/profile.json"
  end

  def token_request
    RestClient::Request.new(method: "POST", url: token_url, headers: headers, timeout: 5)
  end

  def token_url
    "#{@account_url}/users/jwt.json"
  end
end