PageRenderTime 55ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 1ms

/app/controllers/application_controller.rb

https://gitlab.com/solidnerd/gitlab-ce
Ruby | 476 lines | 351 code | 92 blank | 33 comment | 45 complexity | 161a199fe72f168a1bef4e3edef58460 MD5 | raw file
  1. # frozen_string_literal: true
  2. require 'gon'
  3. require 'fogbugz'
  4. class ApplicationController < ActionController::Base
  5. include Gitlab::GonHelper
  6. include GitlabRoutingHelper
  7. include PageLayoutHelper
  8. include SafeParamsHelper
  9. include SentryHelper
  10. include WorkhorseHelper
  11. include EnforcesTwoFactorAuthentication
  12. include WithPerformanceBar
  13. include InvalidUTF8ErrorHandler
  14. before_action :authenticate_sessionless_user!
  15. before_action :authenticate_user!
  16. before_action :enforce_terms!, if: :should_enforce_terms?
  17. before_action :validate_user_service_ticket!
  18. before_action :check_password_expiration
  19. before_action :ldap_security_check
  20. before_action :sentry_context
  21. before_action :default_headers
  22. before_action :add_gon_variables, unless: [:peek_request?, :json_request?]
  23. before_action :configure_permitted_parameters, if: :devise_controller?
  24. before_action :require_email, unless: :devise_controller?
  25. before_action :set_usage_stats_consent_flag
  26. around_action :set_locale
  27. after_action :set_page_title_header, if: :json_request?
  28. after_action :limit_unauthenticated_session_times
  29. protect_from_forgery with: :exception, prepend: true
  30. helper_method :can?
  31. helper_method :import_sources_enabled?, :github_import_enabled?,
  32. :gitea_import_enabled?, :github_import_configured?,
  33. :gitlab_import_enabled?, :gitlab_import_configured?,
  34. :bitbucket_import_enabled?, :bitbucket_import_configured?,
  35. :bitbucket_server_import_enabled?,
  36. :google_code_import_enabled?, :fogbugz_import_enabled?,
  37. :git_import_enabled?, :gitlab_project_import_enabled?,
  38. :manifest_import_enabled?
  39. rescue_from Encoding::CompatibilityError do |exception|
  40. log_exception(exception)
  41. render "errors/encoding", layout: "errors", status: 500
  42. end
  43. rescue_from ActiveRecord::RecordNotFound do |exception|
  44. log_exception(exception)
  45. render_404
  46. end
  47. rescue_from(ActionController::UnknownFormat) do
  48. render_404
  49. end
  50. rescue_from Gitlab::Access::AccessDeniedError do |exception|
  51. render_403
  52. end
  53. rescue_from Gitlab::Auth::TooManyIps do |e|
  54. head :forbidden, retry_after: Gitlab::Auth::UniqueIpsLimiter.config.unique_ips_limit_time_window
  55. end
  56. rescue_from Gitlab::Git::Storage::Inaccessible, GRPC::Unavailable, Gitlab::Git::CommandError do |exception|
  57. Raven.capture_exception(exception) if sentry_enabled?
  58. log_exception(exception)
  59. headers['Retry-After'] = exception.retry_after if exception.respond_to?(:retry_after)
  60. render_503
  61. end
  62. def redirect_back_or_default(default: root_path, options: {})
  63. redirect_to request.referer.present? ? :back : default, options
  64. end
  65. def not_found
  66. render_404
  67. end
  68. def route_not_found
  69. if current_user
  70. not_found
  71. else
  72. authenticate_user!
  73. end
  74. end
  75. # By default, all sessions are given the same expiration time configured in
  76. # the session store (e.g. 1 week). However, unauthenticated users can
  77. # generate a lot of sessions, primarily for CSRF verification. It makes
  78. # sense to reduce the TTL for unauthenticated to something much lower than
  79. # the default (e.g. 1 hour) to limit Redis memory. In addition, Rails
  80. # creates a new session after login, so the short TTL doesn't even need to
  81. # be extended.
  82. def limit_unauthenticated_session_times
  83. return if current_user
  84. # Rack sets this header, but not all tests may have it: https://github.com/rack/rack/blob/fdcd03a3c5a1c51d1f96fc97f9dfa1a9deac0c77/lib/rack/session/abstract/id.rb#L251-L259
  85. return unless request.env['rack.session.options']
  86. # This works because Rack uses these options every time a request is handled:
  87. # https://github.com/rack/rack/blob/fdcd03a3c5a1c51d1f96fc97f9dfa1a9deac0c77/lib/rack/session/abstract/id.rb#L342
  88. request.env['rack.session.options'][:expire_after] = Settings.gitlab['unauthenticated_session_expire_delay']
  89. end
  90. def render(*args)
  91. super.tap do
  92. # Set a header for custom error pages to prevent them from being intercepted by gitlab-workhorse
  93. if response.content_type == 'text/html' && (400..599).cover?(response.status)
  94. response.headers['X-GitLab-Custom-Error'] = '1'
  95. end
  96. end
  97. end
  98. protected
  99. def append_info_to_payload(payload)
  100. super
  101. payload[:ua] = request.env["HTTP_USER_AGENT"]
  102. payload[:remote_ip] = request.remote_ip
  103. logged_user = auth_user
  104. if logged_user.present?
  105. payload[:user_id] = logged_user.try(:id)
  106. payload[:username] = logged_user.try(:username)
  107. end
  108. if response.status == 422 && response.body.present? && response.content_type == 'application/json'.freeze
  109. payload[:response] = response.body
  110. end
  111. end
  112. ##
  113. # Controllers such as GitHttpController may use alternative methods
  114. # (e.g. tokens) to authenticate the user, whereas Devise sets current_user.
  115. #
  116. def auth_user
  117. if user_signed_in?
  118. current_user
  119. else
  120. try(:authenticated_user)
  121. end
  122. end
  123. # This filter handles personal access tokens, and atom requests with rss tokens
  124. def authenticate_sessionless_user!
  125. user = Gitlab::Auth::RequestAuthenticator.new(request).find_sessionless_user
  126. sessionless_sign_in(user) if user
  127. end
  128. def log_exception(exception)
  129. Raven.capture_exception(exception) if sentry_enabled?
  130. backtrace_cleaner = Gitlab.rails5? ? env["action_dispatch.backtrace_cleaner"] : env
  131. application_trace = ActionDispatch::ExceptionWrapper.new(backtrace_cleaner, exception).application_trace
  132. application_trace.map! { |t| " #{t}\n" }
  133. logger.error "\n#{exception.class.name} (#{exception.message}):\n#{application_trace.join}"
  134. end
  135. def after_sign_in_path_for(resource)
  136. stored_location_for(:redirect) || stored_location_for(resource) || root_path
  137. end
  138. def after_sign_out_path_for(resource)
  139. Gitlab::CurrentSettings.after_sign_out_path.presence || new_user_session_path
  140. end
  141. def can?(object, action, subject = :global)
  142. Ability.allowed?(object, action, subject)
  143. end
  144. def access_denied!(message = nil)
  145. # If we display a custom access denied message to the user, we don't want to
  146. # hide existence of the resource, rather tell them they cannot access it using
  147. # the provided message
  148. status = message.present? ? :forbidden : :not_found
  149. respond_to do |format|
  150. format.any { head status }
  151. format.html do
  152. render "errors/access_denied",
  153. layout: "errors",
  154. status: status,
  155. locals: { message: message }
  156. end
  157. end
  158. end
  159. def git_not_found!
  160. render "errors/git_not_found.html", layout: "errors", status: 404
  161. end
  162. def render_403
  163. respond_to do |format|
  164. format.any { head :forbidden }
  165. format.html { render "errors/access_denied", layout: "errors", status: 403 }
  166. end
  167. end
  168. def render_404
  169. respond_to do |format|
  170. format.html { render "errors/not_found", layout: "errors", status: 404 }
  171. # Prevent the Rails CSRF protector from thinking a missing .js file is a JavaScript file
  172. format.js { render json: '', status: :not_found, content_type: 'application/json' }
  173. format.any { head :not_found }
  174. end
  175. end
  176. def respond_422
  177. head :unprocessable_entity
  178. end
  179. def render_503
  180. respond_to do |format|
  181. format.html do
  182. render(
  183. file: Rails.root.join("public", "503"),
  184. layout: false,
  185. status: :service_unavailable
  186. )
  187. end
  188. format.any { head :service_unavailable }
  189. end
  190. end
  191. def no_cache_headers
  192. response.headers["Cache-Control"] = "no-cache, no-store, max-age=0, must-revalidate"
  193. response.headers["Pragma"] = "no-cache"
  194. response.headers["Expires"] = "Fri, 01 Jan 1990 00:00:00 GMT"
  195. end
  196. def default_headers
  197. headers['X-Frame-Options'] = 'DENY'
  198. headers['X-XSS-Protection'] = '1; mode=block'
  199. headers['X-UA-Compatible'] = 'IE=edge'
  200. headers['X-Content-Type-Options'] = 'nosniff'
  201. end
  202. def validate_user_service_ticket!
  203. return unless signed_in? && session[:service_tickets]
  204. valid = session[:service_tickets].all? do |provider, ticket|
  205. Gitlab::Auth::OAuth::Session.valid?(provider, ticket)
  206. end
  207. unless valid
  208. session[:service_tickets] = nil
  209. sign_out current_user
  210. redirect_to new_user_session_path
  211. end
  212. end
  213. def check_password_expiration
  214. return if session[:impersonator_id] || !current_user&.allow_password_authentication?
  215. password_expires_at = current_user&.password_expires_at
  216. if password_expires_at && password_expires_at < Time.now
  217. return redirect_to new_profile_password_path
  218. end
  219. end
  220. def ldap_security_check
  221. if current_user && current_user.requires_ldap_check?
  222. return unless current_user.try_obtain_ldap_lease
  223. unless Gitlab::Auth::LDAP::Access.allowed?(current_user)
  224. sign_out current_user
  225. flash[:alert] = "Access denied for your LDAP account."
  226. redirect_to new_user_session_path
  227. end
  228. end
  229. end
  230. def event_filter
  231. @event_filter ||=
  232. EventFilter.new(params[:event_filter].presence || cookies[:event_filter]).tap do |new_event_filter|
  233. cookies[:event_filter] = new_event_filter.filter
  234. end
  235. end
  236. # JSON for infinite scroll via Pager object
  237. def pager_json(partial, count, locals = {})
  238. html = render_to_string(
  239. partial,
  240. locals: locals,
  241. layout: false,
  242. formats: [:html]
  243. )
  244. render json: {
  245. html: html,
  246. count: count
  247. }
  248. end
  249. def view_to_html_string(partial, locals = {})
  250. render_to_string(
  251. partial,
  252. locals: locals,
  253. layout: false,
  254. formats: [:html]
  255. )
  256. end
  257. def configure_permitted_parameters
  258. devise_parameter_sanitizer.permit(:sign_in, keys: [:username, :email, :password, :login, :remember_me, :otp_attempt])
  259. end
  260. def hexdigest(string)
  261. Digest::SHA1.hexdigest string
  262. end
  263. def require_email
  264. if current_user && current_user.temp_oauth_email? && session[:impersonator_id].nil?
  265. return redirect_to profile_path, notice: 'Please complete your profile with email address'
  266. end
  267. end
  268. def enforce_terms!
  269. return unless current_user
  270. return if current_user.terms_accepted?
  271. message = _("Please accept the Terms of Service before continuing.")
  272. if sessionless_user?
  273. access_denied!(message)
  274. else
  275. # Redirect to the destination if the request is a get.
  276. # Redirect to the source if it was a post, so the user can re-submit after
  277. # accepting the terms.
  278. redirect_path = if request.get?
  279. request.fullpath
  280. else
  281. URI(request.referer).path if request.referer
  282. end
  283. flash[:notice] = message
  284. redirect_to terms_path(redirect: redirect_path), status: :found
  285. end
  286. end
  287. def import_sources_enabled?
  288. !Gitlab::CurrentSettings.import_sources.empty?
  289. end
  290. def bitbucket_server_import_enabled?
  291. Gitlab::CurrentSettings.import_sources.include?('bitbucket_server')
  292. end
  293. def github_import_enabled?
  294. Gitlab::CurrentSettings.import_sources.include?('github')
  295. end
  296. def gitea_import_enabled?
  297. Gitlab::CurrentSettings.import_sources.include?('gitea')
  298. end
  299. def github_import_configured?
  300. Gitlab::Auth::OAuth::Provider.enabled?(:github)
  301. end
  302. def gitlab_import_enabled?
  303. request.host != 'gitlab.com' && Gitlab::CurrentSettings.import_sources.include?('gitlab')
  304. end
  305. def gitlab_import_configured?
  306. Gitlab::Auth::OAuth::Provider.enabled?(:gitlab)
  307. end
  308. def bitbucket_import_enabled?
  309. Gitlab::CurrentSettings.import_sources.include?('bitbucket')
  310. end
  311. def bitbucket_import_configured?
  312. Gitlab::Auth::OAuth::Provider.enabled?(:bitbucket)
  313. end
  314. def google_code_import_enabled?
  315. Gitlab::CurrentSettings.import_sources.include?('google_code')
  316. end
  317. def fogbugz_import_enabled?
  318. Gitlab::CurrentSettings.import_sources.include?('fogbugz')
  319. end
  320. def git_import_enabled?
  321. Gitlab::CurrentSettings.import_sources.include?('git')
  322. end
  323. def gitlab_project_import_enabled?
  324. Gitlab::CurrentSettings.import_sources.include?('gitlab_project')
  325. end
  326. def manifest_import_enabled?
  327. Group.supports_nested_groups? && Gitlab::CurrentSettings.import_sources.include?('manifest')
  328. end
  329. # U2F (universal 2nd factor) devices need a unique identifier for the application
  330. # to perform authentication.
  331. # https://developers.yubico.com/U2F/App_ID.html
  332. def u2f_app_id
  333. request.base_url
  334. end
  335. def set_locale(&block)
  336. Gitlab::I18n.with_user_locale(current_user, &block)
  337. end
  338. def sessionless_sign_in(user)
  339. if user && can?(user, :log_in)
  340. # Notice we are passing store false, so the user is not
  341. # actually stored in the session and a token is needed
  342. # for every request. If you want the token to work as a
  343. # sign in token, you can simply remove store: false.
  344. sign_in(user, store: false, message: :sessionless_sign_in)
  345. end
  346. end
  347. def set_page_title_header
  348. # Per https://tools.ietf.org/html/rfc5987, headers need to be ISO-8859-1, not UTF-8
  349. response.headers['Page-Title'] = URI.escape(page_title('GitLab'))
  350. end
  351. def sessionless_user?
  352. current_user && !session.keys.include?('warden.user.user.key')
  353. end
  354. def peek_request?
  355. request.path.start_with?('/-/peek')
  356. end
  357. def json_request?
  358. request.format.json?
  359. end
  360. def should_enforce_terms?
  361. return false unless Gitlab::CurrentSettings.current_application_settings.enforce_terms
  362. !(peek_request? || devise_controller?)
  363. end
  364. def set_usage_stats_consent_flag
  365. return unless current_user
  366. return if sessionless_user?
  367. return if session.has_key?(:ask_for_usage_stats_consent)
  368. session[:ask_for_usage_stats_consent] = current_user.requires_usage_stats_consent?
  369. if session[:ask_for_usage_stats_consent]
  370. disable_usage_stats
  371. end
  372. end
  373. def disable_usage_stats
  374. application_setting_params = {
  375. usage_ping_enabled: false,
  376. version_check_enabled: false,
  377. skip_usage_stats_user: true
  378. }
  379. settings = Gitlab::CurrentSettings.current_application_settings
  380. ApplicationSettings::UpdateService
  381. .new(settings, current_user, application_setting_params)
  382. .execute
  383. end
  384. end