PageRenderTime 47ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 0ms

/app/controllers/application_controller.rb

https://gitlab.com/iOrange/gitlab-ee
Ruby | 355 lines | 269 code | 69 blank | 17 comment | 41 complexity | 5c61d12d9ee488637e55d11c450bcdb5 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 :abilities, :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?, :gitorious_import_enabled?, :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. protected
  40. # This filter handles both private tokens and personal access tokens
  41. def authenticate_user_from_private_token!
  42. token_string = params[:private_token].presence || request.headers['PRIVATE-TOKEN'].presence
  43. user = User.find_by_authentication_token(token_string) || User.find_by_personal_access_token(token_string)
  44. if user
  45. # Notice we are passing store false, so the user is not
  46. # actually stored in the session and a token is needed
  47. # for every request. If you want the token to work as a
  48. # sign in token, you can simply remove store: false.
  49. sign_in user, store: false
  50. end
  51. end
  52. def authenticate_user!(*args)
  53. if redirect_to_home_page_url?
  54. redirect_to current_application_settings.home_page_url and return
  55. end
  56. super(*args)
  57. end
  58. def log_exception(exception)
  59. application_trace = ActionDispatch::ExceptionWrapper.new(env, exception).application_trace
  60. application_trace.map!{ |t| " #{t}\n" }
  61. logger.error "\n#{exception.class.name} (#{exception.message}):\n#{application_trace.join}"
  62. end
  63. def reject_blocked!
  64. if current_user && current_user.blocked?
  65. sign_out current_user
  66. flash[:alert] = "Your account is blocked. Retry when an admin has unblocked it."
  67. redirect_to new_user_session_path
  68. end
  69. end
  70. def after_sign_in_path_for(resource)
  71. if resource.is_a?(User) && resource.respond_to?(:blocked?) && resource.blocked?
  72. sign_out resource
  73. flash[:alert] = "Your account is blocked. Retry when an admin has unblocked it."
  74. new_user_session_path
  75. else
  76. stored_location_for(:redirect) || stored_location_for(resource) || root_path
  77. end
  78. end
  79. def after_sign_out_path_for(resource)
  80. if Gitlab::Geo.secondary?
  81. Gitlab::Geo.primary_node.oauth_logout_url(@geo_logout_state)
  82. else
  83. current_application_settings.after_sign_out_path.presence || new_user_session_path
  84. end
  85. end
  86. def abilities
  87. Ability.abilities
  88. end
  89. def can?(object, action, subject)
  90. abilities.allowed?(object, action, subject)
  91. end
  92. def access_denied!
  93. render "errors/access_denied", layout: "errors", status: 404
  94. end
  95. def git_not_found!
  96. render "errors/git_not_found.html", layout: "errors", status: 404
  97. end
  98. def render_403
  99. head :forbidden
  100. end
  101. def render_404
  102. render file: Rails.root.join("public", "404"), layout: false, status: "404"
  103. end
  104. def no_cache_headers
  105. response.headers["Cache-Control"] = "no-cache, no-store, max-age=0, must-revalidate"
  106. response.headers["Pragma"] = "no-cache"
  107. response.headers["Expires"] = "Fri, 01 Jan 1990 00:00:00 GMT"
  108. end
  109. def default_headers
  110. headers['X-Frame-Options'] = 'DENY'
  111. headers['X-XSS-Protection'] = '1; mode=block'
  112. headers['X-UA-Compatible'] = 'IE=edge'
  113. headers['X-Content-Type-Options'] = 'nosniff'
  114. # Enabling HSTS for non-standard ports would send clients to the wrong port
  115. if Gitlab.config.gitlab.https and Gitlab.config.gitlab.port == 443
  116. headers['Strict-Transport-Security'] = 'max-age=31536000'
  117. end
  118. end
  119. def validate_user_service_ticket!
  120. return unless signed_in? && session[:service_tickets]
  121. valid = session[:service_tickets].all? do |provider, ticket|
  122. Gitlab::OAuth::Session.valid?(provider, ticket)
  123. end
  124. unless valid
  125. session[:service_tickets] = nil
  126. sign_out current_user
  127. redirect_to new_user_session_path
  128. end
  129. end
  130. def check_password_expiration
  131. if current_user && current_user.password_expires_at && current_user.password_expires_at < Time.now && !current_user.ldap_user?
  132. redirect_to new_profile_password_path and return
  133. end
  134. end
  135. def check_2fa_requirement
  136. if two_factor_authentication_required? && current_user && !current_user.two_factor_enabled? && !skip_two_factor?
  137. redirect_to profile_two_factor_auth_path
  138. end
  139. end
  140. def ldap_security_check
  141. if current_user && current_user.requires_ldap_check?
  142. return unless current_user.try_obtain_ldap_lease
  143. unless Gitlab::LDAP::Access.allowed?(current_user)
  144. sign_out current_user
  145. flash[:alert] = "Access denied for your LDAP account."
  146. redirect_to new_user_session_path
  147. end
  148. end
  149. end
  150. def event_filter
  151. filters = cookies['event_filter'].split(',') if cookies['event_filter'].present?
  152. @event_filter ||= EventFilter.new(filters)
  153. end
  154. def gitlab_ldap_access(&block)
  155. Gitlab::LDAP::Access.open { |access| block.call(access) }
  156. end
  157. # JSON for infinite scroll via Pager object
  158. def pager_json(partial, count)
  159. html = render_to_string(
  160. partial,
  161. layout: false,
  162. formats: [:html]
  163. )
  164. render json: {
  165. html: html,
  166. count: count
  167. }
  168. end
  169. def view_to_html_string(partial, locals = {})
  170. render_to_string(
  171. partial,
  172. locals: locals,
  173. layout: false,
  174. formats: [:html]
  175. )
  176. end
  177. def configure_permitted_parameters
  178. devise_parameter_sanitizer.permit(:sign_in, keys: [:username, :email, :password, :login, :remember_me, :otp_attempt])
  179. end
  180. def hexdigest(string)
  181. Digest::SHA1.hexdigest string
  182. end
  183. def require_email
  184. if current_user && current_user.temp_oauth_email?
  185. redirect_to profile_path, notice: 'Please complete your profile with email address' and return
  186. end
  187. end
  188. def require_ldap_enabled
  189. unless Gitlab.config.ldap.enabled
  190. render_404 and return
  191. end
  192. end
  193. def set_filters_params
  194. set_default_sort
  195. params[:scope] = 'all' if params[:scope].blank?
  196. params[:state] = 'opened' if params[:state].blank?
  197. @sort = params[:sort]
  198. @filter_params = params.dup
  199. if @project
  200. @filter_params[:project_id] = @project.id
  201. elsif @group
  202. @filter_params[:group_id] = @group.id
  203. else
  204. # TODO: this filter ignore issues/mr created in public or
  205. # internal repos where you are not a member. Enable this filter
  206. # or improve current implementation to filter only issues you
  207. # created or assigned or mentioned
  208. # @filter_params[:authorized_only] = true
  209. end
  210. @filter_params
  211. end
  212. def get_issues_collection
  213. set_filters_params
  214. @issuable_finder = IssuesFinder.new(current_user, @filter_params)
  215. @issuable_finder.execute
  216. end
  217. def get_merge_requests_collection
  218. set_filters_params
  219. @issuable_finder = MergeRequestsFinder.new(current_user, @filter_params)
  220. @issuable_finder.execute
  221. end
  222. def import_sources_enabled?
  223. !current_application_settings.import_sources.empty?
  224. end
  225. def github_import_enabled?
  226. current_application_settings.import_sources.include?('github')
  227. end
  228. def github_import_configured?
  229. Gitlab::OAuth::Provider.enabled?(:github)
  230. end
  231. def gitlab_import_enabled?
  232. request.host != 'gitlab.com' && current_application_settings.import_sources.include?('gitlab')
  233. end
  234. def gitlab_import_configured?
  235. Gitlab::OAuth::Provider.enabled?(:gitlab)
  236. end
  237. def bitbucket_import_enabled?
  238. current_application_settings.import_sources.include?('bitbucket')
  239. end
  240. def bitbucket_import_configured?
  241. Gitlab::OAuth::Provider.enabled?(:bitbucket) && Gitlab::BitbucketImport.public_key.present?
  242. end
  243. def gitorious_import_enabled?
  244. current_application_settings.import_sources.include?('gitorious')
  245. end
  246. def google_code_import_enabled?
  247. current_application_settings.import_sources.include?('google_code')
  248. end
  249. def fogbugz_import_enabled?
  250. current_application_settings.import_sources.include?('fogbugz')
  251. end
  252. def git_import_enabled?
  253. current_application_settings.import_sources.include?('git')
  254. end
  255. def gitlab_project_import_enabled?
  256. current_application_settings.import_sources.include?('gitlab_project')
  257. end
  258. def two_factor_authentication_required?
  259. current_application_settings.require_two_factor_authentication
  260. end
  261. def two_factor_grace_period
  262. current_application_settings.two_factor_grace_period
  263. end
  264. def two_factor_grace_period_expired?
  265. date = current_user.otp_grace_period_started_at
  266. date && (date + two_factor_grace_period.hours) < Time.current
  267. end
  268. def skip_two_factor?
  269. session[:skip_tfa] && session[:skip_tfa] > Time.current
  270. end
  271. def redirect_to_home_page_url?
  272. # If user is not signed-in and tries to access root_path - redirect him to landing page
  273. # Don't redirect to the default URL to prevent endless redirections
  274. return false unless current_application_settings.home_page_url.present?
  275. home_page_url = current_application_settings.home_page_url.chomp('/')
  276. root_urls = [Gitlab.config.gitlab['url'].chomp('/'), root_url.chomp('/')]
  277. return false if root_urls.include?(home_page_url)
  278. current_user.nil? && root_path == request.path
  279. end
  280. # U2F (universal 2nd factor) devices need a unique identifier for the application
  281. # to perform authentication.
  282. # https://developers.yubico.com/U2F/App_ID.html
  283. def u2f_app_id
  284. request.base_url
  285. end
  286. end