module Softwear::Auth::TokenAuthentication

Public Instance Methods

token_authenticate_user!() click to toggle source
# File lib/softwear/auth/token_authentication.rb, line 11
def token_authenticate_user!
  user_class = self.class.user_class || base_class.user_class || User
  options    = (self.class.token_auth_options || base_class.token_auth_options || {}).with_indifferent_access
  params_options  = (options[:params]  || {}).with_indifferent_access
  headers_options = (options[:headers] || {}).with_indifferent_access

  email_param  = params_options[:email]                 || 'user_email'
  token_param  = params_options[:authentication_token]  || 'user_token'
  email_header = headers_options[:email]                || 'X-User-Email'
  token_header = headers_options[:authentication_token] || 'X-User-Token'

  email = params[email_param] || request.headers[email_header]
  token = params[token_param] || request.headers[token_header]

  return render_unauthorized if email.blank? || token.blank?

  case user_class.query "token #{Figaro.env.hub_app_name} #{email} #{token}"
  when 'no'      then render_unauthorized
  when 'invaild' then render_unauthorized
  when 'sorry'   then render_internal_server_error
  when 'yes'     then true
  end
end

Private Instance Methods

http_headers() click to toggle source
# File lib/softwear/auth/token_authentication.rb, line 37
def http_headers
  Hash[
    request.headers.each
      .select { |h| h[0] =~ /^HTTP/ }
      .map { |h| [h[0].gsub(/^HTTP_/, ''), h[1]] }
  ]
end
render_internal_server_error() click to toggle source
# File lib/softwear/auth/token_authentication.rb, line 58
def render_internal_server_error
  Rails.logger.error "#{self.class.name} Token authentication request resulted in error.\n"\
    "Params: #{JSON.pretty_generate(params)}\n"\
    "Headers: #{JSON.pretty_generate(http_headers)}"

  respond_to do |format|
    format.json do
      render status: :internal_server_error,
             json: { error: "Authentication server broke" }
    end
  end
end
render_unauthorized() click to toggle source
# File lib/softwear/auth/token_authentication.rb, line 45
def render_unauthorized
  Rails.logger.error "#{self.class.name} Token authentication unauthorized request.\n"\
    "Params: #{JSON.pretty_generate(params)}\n"\
    "Headers: #{JSON.pretty_generate(http_headers)}"

  respond_to do |format|
    format.json do
      render status: :unauthorized,
             json: { error: "Invalid or missing credentials" }
    end
  end
end