prevents_csrf.rb 823 B

1234567891011121314151617181920212223
  1. module ApplicationController::PreventsCsrf
  2. extend ActiveSupport::Concern
  3. included do
  4. before_action :verify_csrf_token
  5. after_action :set_csrf_token_headers
  6. end
  7. private
  8. def set_csrf_token_headers
  9. return true if @_auth_type.present? && @_auth_type != 'session'
  10. headers['CSRF-TOKEN'] = form_authenticity_token
  11. end
  12. def verify_csrf_token
  13. return true if request.method != 'POST' && request.method != 'PUT' && request.method != 'DELETE' && request.method != 'PATCH'
  14. return true if @_auth_type == 'token_auth' || @_auth_type == 'basic_auth'
  15. return true if valid_authenticity_token?(session, params[:authenticity_token] || request.headers['X-CSRF-Token'])
  16. logger.info 'CSRF token verification failed'
  17. raise Exceptions::NotAuthorized, 'CSRF token verification failed!'
  18. end
  19. end