PageRenderTime 39ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 1ms

/app/controllers/application_controller.rb

https://gitlab.com/mahcsig/gitlab-ce
Ruby | 338 lines | 257 code | 70 blank | 11 comment | 26 complexity | 53f65e7665c0fe2bd4c4b977fd98668c 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. include EnforcesTwoFactorAuthentication
  11. include WithPerformanceBar
  12. before_action :authenticate_user_from_private_token!
  13. before_action :authenticate_user_from_rss_token!
  14. before_action :authenticate_user!
  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: -> { request.path.start_with?('/-/peek') }
  21. before_action :configure_permitted_parameters, if: :devise_controller?
  22. before_action :require_email, unless: :devise_controller?
  23. around_action :set_locale
  24. protect_from_forgery with: :exception
  25. helper_method :can?, :current_application_settings
  26. 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?
  27. rescue_from Encoding::CompatibilityError do |exception|
  28. log_exception(exception)
  29. render "errors/encoding", layout: "errors", status: 500
  30. end
  31. rescue_from ActiveRecord::RecordNotFound do |exception|
  32. log_exception(exception)
  33. render_404
  34. end
  35. rescue_from(ActionController::UnknownFormat) do
  36. render_404
  37. end
  38. rescue_from Gitlab::Access::AccessDeniedError do |exception|
  39. render_403
  40. end
  41. rescue_from Gitlab::Auth::TooManyIps do |e|
  42. head :forbidden, retry_after: Gitlab::Auth::UniqueIpsLimiter.config.unique_ips_limit_time_window
  43. end
  44. rescue_from Gitlab::Git::Storage::Inaccessible, GRPC::Unavailable, Gitlab::Git::CommandError do |exception|
  45. Raven.capture_exception(exception) if sentry_enabled?
  46. log_exception(exception)
  47. headers['Retry-After'] = exception.retry_after if exception.respond_to?(:retry_after)
  48. render_503
  49. end
  50. def redirect_back_or_default(default: root_path, options: {})
  51. redirect_to request.referer.present? ? :back : default, options
  52. end
  53. def not_found
  54. render_404
  55. end
  56. def route_not_found
  57. if current_user
  58. not_found
  59. else
  60. authenticate_user!
  61. end
  62. end
  63. protected
  64. def append_info_to_payload(payload)
  65. super
  66. payload[:remote_ip] = request.remote_ip
  67. if current_user.present?
  68. payload[:user_id] = current_user.id
  69. payload[:username] = current_user.username
  70. end
  71. end
  72. # This filter handles both private tokens and personal access tokens
  73. def authenticate_user_from_private_token!
  74. token = params[:private_token].presence || request.headers['PRIVATE-TOKEN'].presence
  75. return unless token.present?
  76. user = User.find_by_authentication_token(token) || User.find_by_personal_access_token(token)
  77. sessionless_sign_in(user)
  78. end
  79. # This filter handles authentication for atom request with an rss_token
  80. def authenticate_user_from_rss_token!
  81. return unless request.format.atom?
  82. token = params[:rss_token].presence
  83. return unless token.present?
  84. user = User.find_by_rss_token(token)
  85. sessionless_sign_in(user)
  86. end
  87. def log_exception(exception)
  88. Raven.capture_exception(exception) if sentry_enabled?
  89. application_trace = ActionDispatch::ExceptionWrapper.new(env, exception).application_trace
  90. application_trace.map! { |t| " #{t}\n" }
  91. logger.error "\n#{exception.class.name} (#{exception.message}):\n#{application_trace.join}"
  92. end
  93. def after_sign_in_path_for(resource)
  94. stored_location_for(:redirect) || stored_location_for(resource) || root_path
  95. end
  96. def after_sign_out_path_for(resource)
  97. current_application_settings.after_sign_out_path.presence || new_user_session_path
  98. end
  99. def can?(object, action, subject = :global)
  100. Ability.allowed?(object, action, subject)
  101. end
  102. def access_denied!
  103. respond_to do |format|
  104. format.json { head :not_found }
  105. format.any { render "errors/access_denied", layout: "errors", status: 404 }
  106. end
  107. end
  108. def git_not_found!
  109. render "errors/git_not_found.html", layout: "errors", status: 404
  110. end
  111. def render_403
  112. head :forbidden
  113. end
  114. def render_404
  115. respond_to do |format|
  116. format.html do
  117. render file: Rails.root.join("public", "404"), layout: false, status: "404"
  118. end
  119. format.any { head :not_found }
  120. end
  121. end
  122. def respond_422
  123. head :unprocessable_entity
  124. end
  125. def render_503
  126. respond_to do |format|
  127. format.html do
  128. render(
  129. file: Rails.root.join("public", "503"),
  130. layout: false,
  131. status: :service_unavailable
  132. )
  133. end
  134. format.any { head :service_unavailable }
  135. end
  136. end
  137. def no_cache_headers
  138. response.headers["Cache-Control"] = "no-cache, no-store, max-age=0, must-revalidate"
  139. response.headers["Pragma"] = "no-cache"
  140. response.headers["Expires"] = "Fri, 01 Jan 1990 00:00:00 GMT"
  141. end
  142. def default_headers
  143. headers['X-Frame-Options'] = 'DENY'
  144. headers['X-XSS-Protection'] = '1; mode=block'
  145. headers['X-UA-Compatible'] = 'IE=edge'
  146. headers['X-Content-Type-Options'] = 'nosniff'
  147. end
  148. def validate_user_service_ticket!
  149. return unless signed_in? && session[:service_tickets]
  150. valid = session[:service_tickets].all? do |provider, ticket|
  151. Gitlab::OAuth::Session.valid?(provider, ticket)
  152. end
  153. unless valid
  154. session[:service_tickets] = nil
  155. sign_out current_user
  156. redirect_to new_user_session_path
  157. end
  158. end
  159. def check_password_expiration
  160. if current_user && current_user.password_expires_at && current_user.password_expires_at < Time.now && current_user.allow_password_authentication?
  161. return redirect_to new_profile_password_path
  162. end
  163. end
  164. def ldap_security_check
  165. if current_user && current_user.requires_ldap_check?
  166. return unless current_user.try_obtain_ldap_lease
  167. unless Gitlab::LDAP::Access.allowed?(current_user)
  168. sign_out current_user
  169. flash[:alert] = "Access denied for your LDAP account."
  170. redirect_to new_user_session_path
  171. end
  172. end
  173. end
  174. def event_filter
  175. # Split using comma to maintain backward compatibility Ex/ "filter1,filter2"
  176. filters = cookies['event_filter'].split(',')[0] if cookies['event_filter'].present?
  177. @event_filter ||= EventFilter.new(filters)
  178. end
  179. def gitlab_ldap_access(&block)
  180. Gitlab::LDAP::Access.open { |access| yield(access) }
  181. end
  182. # JSON for infinite scroll via Pager object
  183. def pager_json(partial, count, locals = {})
  184. html = render_to_string(
  185. partial,
  186. locals: locals,
  187. layout: false,
  188. formats: [:html]
  189. )
  190. render json: {
  191. html: html,
  192. count: count
  193. }
  194. end
  195. def view_to_html_string(partial, locals = {})
  196. render_to_string(
  197. partial,
  198. locals: locals,
  199. layout: false,
  200. formats: [:html]
  201. )
  202. end
  203. def configure_permitted_parameters
  204. devise_parameter_sanitizer.permit(:sign_in, keys: [:username, :email, :password, :login, :remember_me, :otp_attempt])
  205. end
  206. def hexdigest(string)
  207. Digest::SHA1.hexdigest string
  208. end
  209. def require_email
  210. if current_user && current_user.temp_oauth_email? && session[:impersonator_id].nil?
  211. return redirect_to profile_path, notice: 'Please complete your profile with email address'
  212. end
  213. end
  214. def import_sources_enabled?
  215. !current_application_settings.import_sources.empty?
  216. end
  217. def github_import_enabled?
  218. current_application_settings.import_sources.include?('github')
  219. end
  220. def gitea_import_enabled?
  221. current_application_settings.import_sources.include?('gitea')
  222. end
  223. def github_import_configured?
  224. Gitlab::OAuth::Provider.enabled?(:github)
  225. end
  226. def gitlab_import_enabled?
  227. request.host != 'gitlab.com' && current_application_settings.import_sources.include?('gitlab')
  228. end
  229. def gitlab_import_configured?
  230. Gitlab::OAuth::Provider.enabled?(:gitlab)
  231. end
  232. def bitbucket_import_enabled?
  233. current_application_settings.import_sources.include?('bitbucket')
  234. end
  235. def bitbucket_import_configured?
  236. Gitlab::OAuth::Provider.enabled?(:bitbucket)
  237. end
  238. def google_code_import_enabled?
  239. current_application_settings.import_sources.include?('google_code')
  240. end
  241. def fogbugz_import_enabled?
  242. current_application_settings.import_sources.include?('fogbugz')
  243. end
  244. def git_import_enabled?
  245. current_application_settings.import_sources.include?('git')
  246. end
  247. def gitlab_project_import_enabled?
  248. current_application_settings.import_sources.include?('gitlab_project')
  249. end
  250. # U2F (universal 2nd factor) devices need a unique identifier for the application
  251. # to perform authentication.
  252. # https://developers.yubico.com/U2F/App_ID.html
  253. def u2f_app_id
  254. request.base_url
  255. end
  256. def set_locale(&block)
  257. Gitlab::I18n.with_user_locale(current_user, &block)
  258. end
  259. def sessionless_sign_in(user)
  260. if user && can?(user, :log_in)
  261. # Notice we are passing store false, so the user is not
  262. # actually stored in the session and a token is needed
  263. # for every request. If you want the token to work as a
  264. # sign in token, you can simply remove store: false.
  265. sign_in user, store: false
  266. end
  267. end
  268. end