Guest User

Untitled

a guest
May 30th, 2018
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.68 KB | None | 0 0
  1. module V1::AuthenticationConcern
  2. extend ActiveSupport::Concern
  3.  
  4. included do
  5. before_action :authenticate_resource_from_token!
  6. after_action :set_auth_header, if: -> { current_user.present? }
  7. end
  8.  
  9. attr_reader :resource, :payload
  10.  
  11. private
  12.  
  13. def authenticate_resource_from_token!
  14. @token, @api_key = get_token_and_api_key_from_header
  15. return unless @token && @api_key
  16.  
  17. @payload = JWT.decode(@token, Rails.application.secrets.secret_key_base).first
  18. @resource = payload['resource_type'].constantize_with_care(APP_CONFIG[:tokenable_types]).where(
  19. id: payload['resource_id']
  20. ).first
  21.  
  22. authenticate_and_login
  23. rescue
  24. @error = I18n.t('user.invalid_credentials') and render_unauthorized
  25. end
  26.  
  27. def set_auth_header
  28. return if mobile_device? && @device.blank?
  29.  
  30. response.headers[X_USER_API_KEY] = current_user.api_key
  31. response.headers[X_USER_TOKEN] = (@device ? @device.auth_token : current_user.auth_token)
  32. end
  33.  
  34. def get_token_and_api_key_from_header
  35. token = request.headers[X_USER_TOKEN]; api_key = request.headers[X_USER_API_KEY]
  36.  
  37. unless token && api_key
  38. @error = I18n.t('user.access_denied') and render_unauthorized
  39. end
  40. [token, api_key]
  41. end
  42.  
  43. def authenticate_and_login
  44. user = resource.is_a?(Device) ? resource.user : resource
  45.  
  46. if user && !user.is_inactive? && Devise.secure_compare(user.api_key, @api_key)
  47. sign_in :user, user, store: false, bypass: true
  48. current_user.remember_me = true if payload['remember']
  49. else
  50. @error = I18n.t('user.invalid_credentials') and render_unauthorized
  51. end
  52. end
  53.  
  54. def render_unauthorized
  55. render json: {
  56. errors: [@error]
  57. }, status: :unauthorized
  58. end
  59. end
Add Comment
Please, Sign In to add comment