Skip to content
Snippets Groups Projects
Forked from PortalMEC / portalmec
1472 commits behind the upstream repository.
application_controller.rb 1.58 KiB
class ApplicationController < ActionController::API
  include ActionController::Serialization
  include DeviseTokenAuth::Concerns::SetUserByToken
  include Pundit
  include PublicActivity::StoreController

  # tracking user in papertrail
  before_filter :set_paper_trail_whodunnit

  # check if client application is allowed to consumes the API.
  before_filter :allow_client_application

  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  # protect_from_forgery with: :null_session
  before_action :configure_permitted_parameters, if: :devise_controller?
  rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized

  # ensure *current_user* can be called in PublicActivity models
  helper_method :current_user
  hide_action :current_user

  protected

  def configure_permitted_parameters
    registration_params = [:name, :email, :avatar, :password, :password_confirmation]

    if params[:action] == 'update'
      devise_parameter_sanitizer.permit(:account_update) do |user_params|
        user_params.permit(registration_params << :current_password)
      end
    elsif params[:action] == 'create'
      devise_parameter_sanitizer.permit(:sign_in) do |user_params|
        user_params.permit(registration_params << :terms_of_service)
      end
    end
  end

  private

  def allow_client_application
    app = Application.find_or_initialize_by(application_id: request.headers["PortalMEC-AppID"].to_s)
    user_not_authorized if app.domain != request.domain
  end

  def user_not_authorized
    render nothing: true, status: :unauthorized
  end
end