PageRenderTime 35ms CodeModel.GetById 4ms RepoModel.GetById 0ms app.codeStats 0ms

/app/controllers/application_controller.rb

https://bitbucket.org/terrchen/gitlab-ce
Ruby | 382 lines | 289 code | 76 blank | 17 comment | 33 complexity | 3e9b2d6c2b927ff0d21ef6929982d895 MD5 | raw file
Possible License(s): Apache-2.0, CC0-1.0
  1. require 'gon'
  2. require 'fogbugz'
  3. class ApplicationController < ActionController::Base
  4. include Gitlab::GonHelper
  5. include GitlabRoutingHelper
  6. include PageLayoutHelper
  7. include SafeParamsHelper
  8. include SentryHelper
  9. include WorkhorseHelper
  10. include EnforcesTwoFactorAuthentication
  11. include WithPerformanceBar
  12. before_action :authenticate_sessionless_user!
  13. before_action :authenticate_user!
  14. before_action :enforce_terms!, if: :should_enforce_terms?
  15. before_action :validate_user_service_ticket!
  16. before_action :check_password_expiration
  17. before_action :ldap_security_check
  18. before_action :sentry_context
  19. before_action :default_headers
  20. before_action :add_gon_variables, unless: :peek_request?
  21. before_action :configure_permitted_parameters, if: :devise_controller?
  22. before_action :require_email, unless: :devise_controller?
  23. around_action :set_locale
  24. after_action :set_page_title_header, if: -> { request.format == :json }
  25. protect_from_forgery with: :exception
  26. helper_method :can?
  27. helper_method :import_sources_enabled?, :github_import_enabled?, :gitea_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?
  28. rescue_from Encoding::CompatibilityError do |exception|
  29. log_exception(exception)
  30. render "errors/encoding", layout: "errors", status: 500
  31. end
  32. rescue_from ActiveRecord::RecordNotFound do |exception|
  33. log_exception(exception)
  34. render_404
  35. end
  36. rescue_from(ActionController::UnknownFormat) do
  37. render_404
  38. end
  39. rescue_from Gitlab::Access::AccessDeniedError do |exception|
  40. render_403
  41. end
  42. rescue_from Gitlab::Auth::TooManyIps do |e|
  43. head :forbidden, retry_after: Gitlab::Auth::UniqueIpsLimiter.config.unique_ips_limit_time_window
  44. end
  45. rescue_from Gitlab::Git::Storage::Inaccessible, GRPC::Unavailable, Gitlab::Git::CommandError do |exception|
  46. Raven.capture_exception(exception) if sentry_enabled?
  47. log_exception(exception)
  48. headers['Retry-After'] = exception.retry_after if exception.respond_to?(:retry_after)
  49. render_503
  50. end
  51. def redirect_back_or_default(default: root_path, options: {})
  52. redirect_to request.referer.present? ? :back : default, options
  53. end
  54. def not_found
  55. render_404
  56. end
  57. def route_not_found
  58. if current_user
  59. not_found
  60. else
  61. authenticate_user!
  62. end
  63. end
  64. protected
  65. def append_info_to_payload(payload)
  66. super
  67. payload[:remote_ip] = request.remote_ip
  68. logged_user = auth_user
  69. if logged_user.present?
  70. payload[:user_id] = logged_user.try(:id)
  71. payload[:username] = logged_user.try(:username)
  72. end
  73. end
  74. # Controllers such as GitHttpController may use alternative methods
  75. # (e.g. tokens) to authenticate the user, whereas Devise sets current_user
  76. def auth_user
  77. return current_user if current_user.present?
  78. return try(:authenticated_user)
  79. end
  80. # This filter handles personal access tokens, and atom requests with rss tokens
  81. def authenticate_sessionless_user!
  82. user = Gitlab::Auth::RequestAuthenticator.new(request).find_sessionless_user
  83. sessionless_sign_in(user) if user
  84. end
  85. def log_exception(exception)
  86. Raven.capture_exception(exception) if sentry_enabled?
  87. backtrace_cleaner = Gitlab.rails5? ? env["action_dispatch.backtrace_cleaner"] : env
  88. application_trace = ActionDispatch::ExceptionWrapper.new(backtrace_cleaner, exception).application_trace
  89. application_trace.map! { |t| " #{t}\n" }
  90. logger.error "\n#{exception.class.name} (#{exception.message}):\n#{application_trace.join}"
  91. end
  92. def after_sign_in_path_for(resource)
  93. stored_location_for(:redirect) || stored_location_for(resource) || root_path
  94. end
  95. def after_sign_out_path_for(resource)
  96. Gitlab::CurrentSettings.after_sign_out_path.presence || new_user_session_path
  97. end
  98. def can?(object, action, subject = :global)
  99. Ability.allowed?(object, action, subject)
  100. end
  101. def access_denied!(message = nil)
  102. respond_to do |format|
  103. format.any { head :not_found }
  104. format.html do
  105. render "errors/access_denied",
  106. layout: "errors",
  107. status: 404,
  108. locals: { message: message }
  109. end
  110. end
  111. end
  112. def git_not_found!
  113. render "errors/git_not_found.html", layout: "errors", status: 404
  114. end
  115. def render_403
  116. respond_to do |format|
  117. format.any { head :forbidden }
  118. format.html { render "errors/access_denied", layout: "errors", status: 403 }
  119. end
  120. end
  121. def render_404
  122. respond_to do |format|
  123. format.html { render "errors/not_found", layout: "errors", status: 404 }
  124. # Prevent the Rails CSRF protector from thinking a missing .js file is a JavaScript file
  125. format.js { render json: '', status: :not_found, content_type: 'application/json' }
  126. format.any { head :not_found }
  127. end
  128. end
  129. def respond_422
  130. head :unprocessable_entity
  131. end
  132. def render_503
  133. respond_to do |format|
  134. format.html do
  135. render(
  136. file: Rails.root.join("public", "503"),
  137. layout: false,
  138. status: :service_unavailable
  139. )
  140. end
  141. format.any { head :service_unavailable }
  142. end
  143. end
  144. def no_cache_headers
  145. response.headers["Cache-Control"] = "no-cache, no-store, max-age=0, must-revalidate"
  146. response.headers["Pragma"] = "no-cache"
  147. response.headers["Expires"] = "Fri, 01 Jan 1990 00:00:00 GMT"
  148. end
  149. def default_headers
  150. headers['X-Frame-Options'] = 'DENY'
  151. headers['X-XSS-Protection'] = '1; mode=block'
  152. headers['X-UA-Compatible'] = 'IE=edge'
  153. headers['X-Content-Type-Options'] = 'nosniff'
  154. end
  155. def validate_user_service_ticket!
  156. return unless signed_in? && session[:service_tickets]
  157. valid = session[:service_tickets].all? do |provider, ticket|
  158. Gitlab::Auth::OAuth::Session.valid?(provider, ticket)
  159. end
  160. unless valid
  161. session[:service_tickets] = nil
  162. sign_out current_user
  163. redirect_to new_user_session_path
  164. end
  165. end
  166. def check_password_expiration
  167. return if session[:impersonator_id] || !current_user&.allow_password_authentication?
  168. password_expires_at = current_user&.password_expires_at
  169. if password_expires_at && password_expires_at < Time.now
  170. return redirect_to new_profile_password_path
  171. end
  172. end
  173. def ldap_security_check
  174. if current_user && current_user.requires_ldap_check?
  175. return unless current_user.try_obtain_ldap_lease
  176. unless Gitlab::Auth::LDAP::Access.allowed?(current_user)
  177. sign_out current_user
  178. flash[:alert] = "Access denied for your LDAP account."
  179. redirect_to new_user_session_path
  180. end
  181. end
  182. end
  183. def event_filter
  184. # Split using comma to maintain backward compatibility Ex/ "filter1,filter2"
  185. filters = cookies['event_filter'].split(',')[0] if cookies['event_filter'].present?
  186. @event_filter ||= EventFilter.new(filters)
  187. end
  188. # JSON for infinite scroll via Pager object
  189. def pager_json(partial, count, locals = {})
  190. html = render_to_string(
  191. partial,
  192. locals: locals,
  193. layout: false,
  194. formats: [:html]
  195. )
  196. render json: {
  197. html: html,
  198. count: count
  199. }
  200. end
  201. def view_to_html_string(partial, locals = {})
  202. render_to_string(
  203. partial,
  204. locals: locals,
  205. layout: false,
  206. formats: [:html]
  207. )
  208. end
  209. def configure_permitted_parameters
  210. devise_parameter_sanitizer.permit(:sign_in, keys: [:username, :email, :password, :login, :remember_me, :otp_attempt])
  211. end
  212. def hexdigest(string)
  213. Digest::SHA1.hexdigest string
  214. end
  215. def require_email
  216. if current_user && current_user.temp_oauth_email? && session[:impersonator_id].nil?
  217. return redirect_to profile_path, notice: 'Please complete your profile with email address'
  218. end
  219. end
  220. def enforce_terms!
  221. return unless current_user
  222. return if current_user.terms_accepted?
  223. if sessionless_user?
  224. render_403
  225. else
  226. # Redirect to the destination if the request is a get.
  227. # Redirect to the source if it was a post, so the user can re-submit after
  228. # accepting the terms.
  229. redirect_path = if request.get?
  230. request.fullpath
  231. else
  232. URI(request.referer).path if request.referer
  233. end
  234. flash[:notice] = _("Please accept the Terms of Service before continuing.")
  235. redirect_to terms_path(redirect: redirect_path), status: :found
  236. end
  237. end
  238. def import_sources_enabled?
  239. !Gitlab::CurrentSettings.import_sources.empty?
  240. end
  241. def github_import_enabled?
  242. Gitlab::CurrentSettings.import_sources.include?('github')
  243. end
  244. def gitea_import_enabled?
  245. Gitlab::CurrentSettings.import_sources.include?('gitea')
  246. end
  247. def github_import_configured?
  248. Gitlab::Auth::OAuth::Provider.enabled?(:github)
  249. end
  250. def gitlab_import_enabled?
  251. request.host != 'gitlab.com' && Gitlab::CurrentSettings.import_sources.include?('gitlab')
  252. end
  253. def gitlab_import_configured?
  254. Gitlab::Auth::OAuth::Provider.enabled?(:gitlab)
  255. end
  256. def bitbucket_import_enabled?
  257. Gitlab::CurrentSettings.import_sources.include?('bitbucket')
  258. end
  259. def bitbucket_import_configured?
  260. Gitlab::Auth::OAuth::Provider.enabled?(:bitbucket)
  261. end
  262. def google_code_import_enabled?
  263. Gitlab::CurrentSettings.import_sources.include?('google_code')
  264. end
  265. def fogbugz_import_enabled?
  266. Gitlab::CurrentSettings.import_sources.include?('fogbugz')
  267. end
  268. def git_import_enabled?
  269. Gitlab::CurrentSettings.import_sources.include?('git')
  270. end
  271. def gitlab_project_import_enabled?
  272. Gitlab::CurrentSettings.import_sources.include?('gitlab_project')
  273. end
  274. # U2F (universal 2nd factor) devices need a unique identifier for the application
  275. # to perform authentication.
  276. # https://developers.yubico.com/U2F/App_ID.html
  277. def u2f_app_id
  278. request.base_url
  279. end
  280. def set_locale(&block)
  281. Gitlab::I18n.with_user_locale(current_user, &block)
  282. end
  283. def sessionless_sign_in(user)
  284. if user && can?(user, :log_in)
  285. # Notice we are passing store false, so the user is not
  286. # actually stored in the session and a token is needed
  287. # for every request. If you want the token to work as a
  288. # sign in token, you can simply remove store: false.
  289. sign_in user, store: false
  290. end
  291. end
  292. def set_page_title_header
  293. # Per https://tools.ietf.org/html/rfc5987, headers need to be ISO-8859-1, not UTF-8
  294. response.headers['Page-Title'] = URI.escape(page_title('GitLab'))
  295. end
  296. def sessionless_user?
  297. current_user && !session.keys.include?('warden.user.user.key')
  298. end
  299. def peek_request?
  300. request.path.start_with?('/-/peek')
  301. end
  302. def should_enforce_terms?
  303. return false unless Gitlab::CurrentSettings.current_application_settings.enforce_terms
  304. !(peek_request? || devise_controller?)
  305. end
  306. end