module Softwear module Auth module TokenAuthentication extend ActiveSupport::Concern included do cattr_accessor :user_class cattr_accessor :token_auth_options end 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 def http_headers Hash[ request.headers.each .select { |h| h[0] =~ /^HTTP/ } .map { |h| [h[0].gsub(/^HTTP_/, ''), h[1]] } ] end 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 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 end end end