PageRenderTime 26ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 1ms

/app/controllers/application_controller.rb

https://gitlab.com/oxan/gitlab-ce
Ruby | 312 lines | 239 code | 60 blank | 13 comment | 38 complexity | d30015578cd29cf299f44a6dd9ad76b2 MD5 | raw file
  1. require 'gon'
  2. require 'fogbugz'
  3. class ApplicationController < ActionController::Base
  4. include Gitlab::CurrentSettings
  5. include Gitlab::GonHelper
  6. include GitlabRoutingHelper
  7. include PageLayoutHelper
  8. include SentryHelper
  9. include WorkhorseHelper
  10. before_action :authenticate_user_from_private_token!
  11. before_action :authenticate_user!
  12. before_action :validate_user_service_ticket!
  13. before_action :reject_blocked!
  14. before_action :check_password_expiration
  15. before_action :check_2fa_requirement
  16. before_action :ldap_security_check
  17. before_action :sentry_context
  18. before_action :default_headers
  19. before_action :add_gon_variables
  20. before_action :configure_permitted_parameters, if: :devise_controller?
  21. before_action :require_email, unless: :devise_controller?
  22. protect_from_forgery with: :exception
  23. helper_method :can?, :current_application_settings
  24. helper_method :import_sources_enabled?, :github_import_enabled?, :github_import_configured?, :gitlab_import_enabled?, :gitlab_import_configured?, :bitbucket_import_enabled?, :bitbucket_import_configured?, :google_code_import_enabled?, :fogbugz_import_enabled?, :git_import_enabled?, :gitlab_project_import_enabled?
  25. rescue_from Encoding::CompatibilityError do |exception|
  26. log_exception(exception)
  27. render "errors/encoding", layout: "errors", status: 500
  28. end
  29. rescue_from ActiveRecord::RecordNotFound do |exception|
  30. log_exception(exception)
  31. render_404
  32. end
  33. rescue_from Gitlab::Access::AccessDeniedError do |exception|
  34. render_403
  35. end
  36. def redirect_back_or_default(default: root_path, options: {})
  37. redirect_to request.referer.present? ? :back : default, options
  38. end
  39. def not_found
  40. render_404
  41. end
  42. protected
  43. # This filter handles both private tokens and personal access tokens
  44. def authenticate_user_from_private_token!
  45. token_string = params[:private_token].presence || request.headers['PRIVATE-TOKEN'].presence
  46. user = User.find_by_authentication_token(token_string) || User.find_by_personal_access_token(token_string)
  47. if user
  48. # Notice we are passing store false, so the user is not
  49. # actually stored in the session and a token is needed
  50. # for every request. If you want the token to work as a
  51. # sign in token, you can simply remove store: false.
  52. sign_in user, store: false
  53. end
  54. end
  55. def authenticate_user!(*args)
  56. if redirect_to_home_page_url?
  57. redirect_to current_application_settings.home_page_url and return
  58. end
  59. super(*args)
  60. end
  61. def log_exception(exception)
  62. application_trace = ActionDispatch::ExceptionWrapper.new(env, exception).application_trace
  63. application_trace.map!{ |t| " #{t}\n" }
  64. logger.error "\n#{exception.class.name} (#{exception.message}):\n#{application_trace.join}"
  65. end
  66. def reject_blocked!
  67. if current_user && current_user.blocked?
  68. sign_out current_user
  69. flash[:alert] = "Your account is blocked. Retry when an admin has unblocked it."
  70. redirect_to new_user_session_path
  71. end
  72. end
  73. def after_sign_in_path_for(resource)
  74. if resource.is_a?(User) && resource.respond_to?(:blocked?) && resource.blocked?
  75. sign_out resource
  76. flash[:alert] = "Your account is blocked. Retry when an admin has unblocked it."
  77. new_user_session_path
  78. else
  79. stored_location_for(:redirect) || stored_location_for(resource) || root_path
  80. end
  81. end
  82. def after_sign_out_path_for(resource)
  83. current_application_settings.after_sign_out_path.presence || new_user_session_path
  84. end
  85. def can?(object, action, subject)
  86. Ability.allowed?(object, action, subject)
  87. end
  88. def access_denied!
  89. render "errors/access_denied", layout: "errors", status: 404
  90. end
  91. def git_not_found!
  92. render "errors/git_not_found.html", layout: "errors", status: 404
  93. end
  94. def render_403
  95. head :forbidden
  96. end
  97. def render_404
  98. respond_to do |format|
  99. format.html do
  100. render file: Rails.root.join("public", "404"), layout: false, status: "404"
  101. end
  102. format.any { head :not_found }
  103. end
  104. end
  105. def no_cache_headers
  106. response.headers["Cache-Control"] = "no-cache, no-store, max-age=0, must-revalidate"
  107. response.headers["Pragma"] = "no-cache"
  108. response.headers["Expires"] = "Fri, 01 Jan 1990 00:00:00 GMT"
  109. end
  110. def default_headers
  111. headers['X-Frame-Options'] = 'DENY'
  112. headers['X-XSS-Protection'] = '1; mode=block'
  113. headers['X-UA-Compatible'] = 'IE=edge'
  114. headers['X-Content-Type-Options'] = 'nosniff'
  115. # Enabling HSTS for non-standard ports would send clients to the wrong port
  116. if Gitlab.config.gitlab.https and Gitlab.config.gitlab.port == 443
  117. headers['Strict-Transport-Security'] = 'max-age=31536000'
  118. end
  119. end
  120. def validate_user_service_ticket!
  121. return unless signed_in? && session[:service_tickets]
  122. valid = session[:service_tickets].all? do |provider, ticket|
  123. Gitlab::OAuth::Session.valid?(provider, ticket)
  124. end
  125. unless valid
  126. session[:service_tickets] = nil
  127. sign_out current_user
  128. redirect_to new_user_session_path
  129. end
  130. end
  131. def check_password_expiration
  132. if current_user && current_user.password_expires_at && current_user.password_expires_at < Time.now && !current_user.ldap_user?
  133. redirect_to new_profile_password_path and return
  134. end
  135. end
  136. def check_2fa_requirement
  137. if two_factor_authentication_required? && current_user && !current_user.two_factor_enabled? && !skip_two_factor?
  138. redirect_to profile_two_factor_auth_path
  139. end
  140. end
  141. def ldap_security_check
  142. if current_user && current_user.requires_ldap_check?
  143. return unless current_user.try_obtain_ldap_lease
  144. unless Gitlab::LDAP::Access.allowed?(current_user)
  145. sign_out current_user
  146. flash[:alert] = "Access denied for your LDAP account."
  147. redirect_to new_user_session_path
  148. end
  149. end
  150. end
  151. def event_filter
  152. # Split using comma to maintain backward compatibility Ex/ "filter1,filter2"
  153. filters = cookies['event_filter'].split(',')[0] if cookies['event_filter'].present?
  154. @event_filter ||= EventFilter.new(filters)
  155. end
  156. def gitlab_ldap_access(&block)
  157. Gitlab::LDAP::Access.open { |access| block.call(access) }
  158. end
  159. # JSON for infinite scroll via Pager object
  160. def pager_json(partial, count, locals = {})
  161. html = render_to_string(
  162. partial,
  163. locals: locals,
  164. layout: false,
  165. formats: [:html]
  166. )
  167. render json: {
  168. html: html,
  169. count: count
  170. }
  171. end
  172. def view_to_html_string(partial, locals = {})
  173. render_to_string(
  174. partial,
  175. locals: locals,
  176. layout: false,
  177. formats: [:html]
  178. )
  179. end
  180. def configure_permitted_parameters
  181. devise_parameter_sanitizer.permit(:sign_in, keys: [:username, :email, :password, :login, :remember_me, :otp_attempt])
  182. end
  183. def hexdigest(string)
  184. Digest::SHA1.hexdigest string
  185. end
  186. def require_email
  187. if current_user && current_user.temp_oauth_email? && session[:impersonator_id].nil?
  188. redirect_to profile_path, notice: 'Please complete your profile with email address' and return
  189. end
  190. end
  191. def import_sources_enabled?
  192. !current_application_settings.import_sources.empty?
  193. end
  194. def github_import_enabled?
  195. current_application_settings.import_sources.include?('github')
  196. end
  197. def github_import_configured?
  198. Gitlab::OAuth::Provider.enabled?(:github)
  199. end
  200. def gitlab_import_enabled?
  201. request.host != 'gitlab.com' && current_application_settings.import_sources.include?('gitlab')
  202. end
  203. def gitlab_import_configured?
  204. Gitlab::OAuth::Provider.enabled?(:gitlab)
  205. end
  206. def bitbucket_import_enabled?
  207. current_application_settings.import_sources.include?('bitbucket')
  208. end
  209. def bitbucket_import_configured?
  210. Gitlab::OAuth::Provider.enabled?(:bitbucket) && Gitlab::BitbucketImport.public_key.present?
  211. end
  212. def google_code_import_enabled?
  213. current_application_settings.import_sources.include?('google_code')
  214. end
  215. def fogbugz_import_enabled?
  216. current_application_settings.import_sources.include?('fogbugz')
  217. end
  218. def git_import_enabled?
  219. current_application_settings.import_sources.include?('git')
  220. end
  221. def gitlab_project_import_enabled?
  222. current_application_settings.import_sources.include?('gitlab_project')
  223. end
  224. def two_factor_authentication_required?
  225. current_application_settings.require_two_factor_authentication
  226. end
  227. def two_factor_grace_period
  228. current_application_settings.two_factor_grace_period
  229. end
  230. def two_factor_grace_period_expired?
  231. date = current_user.otp_grace_period_started_at
  232. date && (date + two_factor_grace_period.hours) < Time.current
  233. end
  234. def skip_two_factor?
  235. session[:skip_tfa] && session[:skip_tfa] > Time.current
  236. end
  237. def redirect_to_home_page_url?
  238. # If user is not signed-in and tries to access root_path - redirect him to landing page
  239. # Don't redirect to the default URL to prevent endless redirections
  240. return false unless current_application_settings.home_page_url.present?
  241. home_page_url = current_application_settings.home_page_url.chomp('/')
  242. root_urls = [Gitlab.config.gitlab['url'].chomp('/'), root_url.chomp('/')]
  243. return false if root_urls.include?(home_page_url)
  244. current_user.nil? && root_path == request.path
  245. end
  246. # U2F (universal 2nd factor) devices need a unique identifier for the application
  247. # to perform authentication.
  248. # https://developers.yubico.com/U2F/App_ID.html
  249. def u2f_app_id
  250. request.base_url
  251. end
  252. end