2021-06-01 12:20:20 +00:00
|
|
|
# Copyright (C) 2012-2021 Zammad Foundation, http://zammad-foundation.org/
|
|
|
|
|
2017-03-09 11:44:51 +00:00
|
|
|
module ApplicationController::PreventsCsrf
|
|
|
|
extend ActiveSupport::Concern
|
|
|
|
|
|
|
|
included do
|
2019-07-04 13:05:18 +00:00
|
|
|
# disable Rails default (>= 5.2) CSRF verification because we
|
|
|
|
# have an advanced use case with our JS App/SPA and the different
|
|
|
|
# Auth mechanisms (e.g. Token- or BasicAuth) that can't be covered
|
|
|
|
# with the built-in functionality
|
2019-07-04 11:16:55 +00:00
|
|
|
skip_before_action :verify_authenticity_token, raise: false
|
|
|
|
|
2019-07-04 13:05:18 +00:00
|
|
|
# register custom CSRF verification and provisioning functionality
|
2017-03-09 11:44:51 +00:00
|
|
|
before_action :verify_csrf_token
|
|
|
|
after_action :set_csrf_token_headers
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def set_csrf_token_headers
|
|
|
|
return true if @_auth_type.present? && @_auth_type != 'session'
|
2018-10-09 06:17:41 +00:00
|
|
|
|
2019-07-04 13:05:18 +00:00
|
|
|
# call Rails method to provide CRSF token
|
2017-03-09 11:44:51 +00:00
|
|
|
headers['CSRF-TOKEN'] = form_authenticity_token
|
|
|
|
end
|
|
|
|
|
|
|
|
def verify_csrf_token
|
2018-07-09 06:47:03 +00:00
|
|
|
return true if !protect_against_forgery?
|
2021-07-20 13:31:46 +00:00
|
|
|
return true if request.get? || request.head?
|
2018-07-09 06:47:03 +00:00
|
|
|
return true if %w[token_auth basic_auth].include?(@_auth_type)
|
2019-07-04 13:05:18 +00:00
|
|
|
|
|
|
|
# call Rails method to verify CRSF token
|
2017-03-09 11:44:51 +00:00
|
|
|
return true if valid_authenticity_token?(session, params[:authenticity_token] || request.headers['X-CSRF-Token'])
|
2018-10-09 06:17:41 +00:00
|
|
|
|
2017-03-09 11:44:51 +00:00
|
|
|
logger.info 'CSRF token verification failed'
|
|
|
|
raise Exceptions::NotAuthorized, 'CSRF token verification failed!'
|
|
|
|
end
|
|
|
|
end
|