Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- module V1::AuthenticationConcern
- extend ActiveSupport::Concern
- included do
- before_action :authenticate_resource_from_token!
- after_action :set_auth_header, if: -> { current_user.present? }
- end
- attr_reader :resource, :payload
- private
- def authenticate_resource_from_token!
- @token, @api_key = get_token_and_api_key_from_header
- return unless @token && @api_key
- @payload = JWT.decode(@token, Rails.application.secrets.secret_key_base).first
- @resource = payload['resource_type'].constantize_with_care(APP_CONFIG[:tokenable_types]).where(
- id: payload['resource_id']
- ).first
- authenticate_and_login
- rescue
- @error = I18n.t('user.invalid_credentials') and render_unauthorized
- end
- def set_auth_header
- return if mobile_device? && @device.blank?
- response.headers[X_USER_API_KEY] = current_user.api_key
- response.headers[X_USER_TOKEN] = (@device ? @device.auth_token : current_user.auth_token)
- end
- def get_token_and_api_key_from_header
- token = request.headers[X_USER_TOKEN]; api_key = request.headers[X_USER_API_KEY]
- unless token && api_key
- @error = I18n.t('user.access_denied') and render_unauthorized
- end
- [token, api_key]
- end
- def authenticate_and_login
- user = resource.is_a?(Device) ? resource.user : resource
- if user && !user.is_inactive? && Devise.secure_compare(user.api_key, @api_key)
- sign_in :user, user, store: false, bypass: true
- current_user.remember_me = true if payload['remember']
- else
- @error = I18n.t('user.invalid_credentials') and render_unauthorized
- end
- end
- def render_unauthorized
- render json: {
- errors: [@error]
- }, status: :unauthorized
- end
- end
Add Comment
Please, Sign In to add comment