application_controller.rb 9.61 KB
Newer Older
1
require 'gon'
Jared Szechy's avatar
Jared Szechy committed
2
require 'fogbugz'
3

4
class ApplicationController < ActionController::Base
5
  include Gitlab::GonHelper
6 7
  include GitlabRoutingHelper
  include PageLayoutHelper
Stan Hu's avatar
Stan Hu committed
8
  include SentryHelper
9
  include WorkhorseHelper
10
  include EnforcesTwoFactorAuthentication
11
  include WithPerformanceBar
12

Michael Kozono's avatar
Michael Kozono committed
13
  before_action :authenticate_sessionless_user!
14
  before_action :authenticate_user!
tduehr's avatar
tduehr committed
15
  before_action :validate_user_service_ticket!
16 17
  before_action :check_password_expiration
  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 22
  before_action :configure_permitted_parameters, if: :devise_controller?
  before_action :require_email, unless: :devise_controller?
23

24 25
  around_action :set_locale

26 27
  after_action :set_page_title_header, if: -> { request.format == :json }

28
  protect_from_forgery with: :exception
29

30
  helper_method :can?
31
  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?
gitlabhq's avatar
gitlabhq committed
32

33
  rescue_from Encoding::CompatibilityError do |exception|
Riyad Preukschas's avatar
Riyad Preukschas committed
34
    log_exception(exception)
Cyril's avatar
Cyril committed
35
    render "errors/encoding", layout: "errors", status: 500
36 37
  end

38
  rescue_from ActiveRecord::RecordNotFound do |exception|
Riyad Preukschas's avatar
Riyad Preukschas committed
39
    log_exception(exception)
40
    render_404
gitlabhq's avatar
gitlabhq committed
41 42
  end

43 44 45 46
  rescue_from(ActionController::UnknownFormat) do
    render_404
  end

47 48 49 50
  rescue_from Gitlab::Access::AccessDeniedError do |exception|
    render_403
  end

51
  rescue_from Gitlab::Auth::TooManyIps do |e|
52
    head :forbidden, retry_after: Gitlab::Auth::UniqueIpsLimiter.config.unique_ips_limit_time_window
53 54
  end

55
  rescue_from Gitlab::Git::Storage::Inaccessible, GRPC::Unavailable, Gitlab::Git::CommandError do |exception|
56 57 58 59 60 61 62 63
    Raven.capture_exception(exception) if sentry_enabled?
    log_exception(exception)

    headers['Retry-After'] = exception.retry_after if exception.respond_to?(:retry_after)

    render_503
  end

64 65 66 67
  def redirect_back_or_default(default: root_path, options: {})
    redirect_to request.referer.present? ? :back : default, options
  end

68 69 70 71
  def not_found
    render_404
  end

72 73 74 75
  def route_not_found
    if current_user
      not_found
    else
76
      authenticate_user!
77 78 79
    end
  end

Nihad Abbasov's avatar
Nihad Abbasov committed
80
  protected
gitlabhq's avatar
gitlabhq committed
81

82 83 84 85
  def append_info_to_payload(payload)
    super
    payload[:remote_ip] = request.remote_ip

86 87 88 89 90
    logged_user = auth_user

    if logged_user.present?
      payload[:user_id] = logged_user.try(:id)
      payload[:username] = logged_user.try(:username)
91 92 93
    end
  end

94 95 96 97
  # Controllers such as GitHttpController may use alternative methods
  # (e.g. tokens) to authenticate the user, whereas Devise sets current_user
  def auth_user
    return current_user if current_user.present?
98

99 100 101
    return try(:authenticated_user)
  end

102
  # This filter handles personal access tokens, and atom requests with rss tokens
Michael Kozono's avatar
Michael Kozono committed
103
  def authenticate_sessionless_user!
104
    user = Gitlab::Auth::RequestAuthenticator.new(request).find_sessionless_user
Michael Kozono's avatar
Michael Kozono committed
105 106

    sessionless_sign_in(user) if user
107 108
  end

Riyad Preukschas's avatar
Riyad Preukschas committed
109
  def log_exception(exception)
Stan Hu's avatar
Stan Hu committed
110 111
    Raven.capture_exception(exception) if sentry_enabled?

Riyad Preukschas's avatar
Riyad Preukschas committed
112
    application_trace = ActionDispatch::ExceptionWrapper.new(env, exception).application_trace
113
    application_trace.map! { |t| "  #{t}\n" }
Riyad Preukschas's avatar
Riyad Preukschas committed
114 115 116
    logger.error "\n#{exception.class.name} (#{exception.message}):\n#{application_trace.join}"
  end

117
  def after_sign_in_path_for(resource)
118
    stored_location_for(:redirect) || stored_location_for(resource) || root_path
randx's avatar
randx committed
119 120
  end

121
  def after_sign_out_path_for(resource)
122
    Gitlab::CurrentSettings.after_sign_out_path.presence || new_user_session_path
123 124
  end

125
  def can?(object, action, subject = :global)
126
    Ability.allowed?(object, action, subject)
gitlabhq's avatar
gitlabhq committed
127 128
  end

129
  def access_denied!(message = nil)
Fatih Acet's avatar
Fatih Acet committed
130
    respond_to do |format|
131 132 133 134 135 136 137
      format.any { head :not_found }
      format.html do
        render "errors/access_denied",
               layout: "errors",
               status: 404,
               locals: { message: message }
      end
Fatih Acet's avatar
Fatih Acet committed
138
    end
139 140 141
  end

  def git_not_found!
142
    render "errors/git_not_found.html", layout: "errors", status: 404
gitlabhq's avatar
gitlabhq committed
143 144
  end

145 146
  def render_403
    head :forbidden
gitlabhq's avatar
gitlabhq committed
147
  end
gitlabhq's avatar
gitlabhq committed
148

149
  def render_404
150
    respond_to do |format|
Sean McGivern's avatar
Sean McGivern committed
151
      format.html do
152 153
        render file: Rails.root.join("public", "404"), layout: false, status: "404"
      end
154 155
      # Prevent the Rails CSRF protector from thinking a missing .js file is a JavaScript file
      format.js { render json: '', status: :not_found, content_type: 'application/json' }
Sean McGivern's avatar
Sean McGivern committed
156
      format.any { head :not_found }
157
    end
158 159
  end

160 161 162 163
  def respond_422
    head :unprocessable_entity
  end

164 165 166 167 168 169 170 171 172 173 174 175 176
  def render_503
    respond_to do |format|
      format.html do
        render(
          file: Rails.root.join("public", "503"),
          layout: false,
          status: :service_unavailable
        )
      end
      format.any { head :service_unavailable }
    end
  end

177 178 179 180 181
  def no_cache_headers
    response.headers["Cache-Control"] = "no-cache, no-store, max-age=0, must-revalidate"
    response.headers["Pragma"] = "no-cache"
    response.headers["Expires"] = "Fri, 01 Jan 1990 00:00:00 GMT"
  end
182

183 184 185
  def default_headers
    headers['X-Frame-Options'] = 'DENY'
    headers['X-XSS-Protection'] = '1; mode=block'
xyb's avatar
xyb committed
186
    headers['X-UA-Compatible'] = 'IE=edge'
187
    headers['X-Content-Type-Options'] = 'nosniff'
188
  end
189

tduehr's avatar
tduehr committed
190 191 192 193 194 195 196 197 198 199 200 201 202 203
  def validate_user_service_ticket!
    return unless signed_in? && session[:service_tickets]

    valid = session[:service_tickets].all? do |provider, ticket|
      Gitlab::OAuth::Session.valid?(provider, ticket)
    end

    unless valid
      session[:service_tickets] = nil
      sign_out current_user
      redirect_to new_user_session_path
    end
  end

204
  def check_password_expiration
205
    return if session[:impersonator_id] || !current_user&.allow_password_authentication?
206 207 208 209

    password_expires_at = current_user&.password_expires_at

    if password_expires_at && password_expires_at < Time.now
Douwe Maan's avatar
Douwe Maan committed
210
      return redirect_to new_profile_password_path
211 212
    end
  end
213

214
  def ldap_security_check
215
    if current_user && current_user.requires_ldap_check?
Jacob Vosmaer's avatar
Jacob Vosmaer committed
216
      return unless current_user.try_obtain_ldap_lease
217

218 219 220 221
      unless Gitlab::LDAP::Access.allowed?(current_user)
        sign_out current_user
        flash[:alert] = "Access denied for your LDAP account."
        redirect_to new_user_session_path
222 223 224 225
      end
    end
  end

226
  def event_filter
227 228
    # Split using comma to maintain backward compatibility Ex/ "filter1,filter2"
    filters = cookies['event_filter'].split(',')[0] if cookies['event_filter'].present?
229 230
    @event_filter ||= EventFilter.new(filters)
  end
231

232
  def gitlab_ldap_access(&block)
233
    Gitlab::LDAP::Access.open { |access| yield(access) }
234 235
  end

236
  # JSON for infinite scroll via Pager object
237
  def pager_json(partial, count, locals = {})
238 239
    html = render_to_string(
      partial,
240
      locals: locals,
241 242 243 244 245 246 247 248 249
      layout: false,
      formats: [:html]
    )

    render json: {
      html: html,
      count: count
    }
  end
250

Josh Frye's avatar
Josh Frye committed
251
  def view_to_html_string(partial, locals = {})
252
    render_to_string(
Josh Frye's avatar
Josh Frye committed
253
      partial,
254
      locals: locals,
255 256 257 258
      layout: false,
      formats: [:html]
    )
  end
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
259 260

  def configure_permitted_parameters
261
    devise_parameter_sanitizer.permit(:sign_in, keys: [:username, :email, :password, :login, :remember_me, :otp_attempt])
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
262
  end
263 264 265 266

  def hexdigest(string)
    Digest::SHA1.hexdigest string
  end
267 268

  def require_email
269
    if current_user && current_user.temp_oauth_email? && session[:impersonator_id].nil?
Douwe Maan's avatar
Douwe Maan committed
270
      return redirect_to profile_path, notice: 'Please complete your profile with email address'
271 272
    end
  end
273

274
  def import_sources_enabled?
275
    !Gitlab::CurrentSettings.import_sources.empty?
276 277
  end

278
  def github_import_enabled?
279
    Gitlab::CurrentSettings.import_sources.include?('github')
280 281
  end

282
  def gitea_import_enabled?
283
    Gitlab::CurrentSettings.import_sources.include?('gitea')
Kim "BKC" Carlbäcker's avatar
Kim "BKC" Carlbäcker committed
284 285
  end

286
  def github_import_configured?
287
    Gitlab::OAuth::Provider.enabled?(:github)
288 289 290
  end

  def gitlab_import_enabled?
291
    request.host != 'gitlab.com' && Gitlab::CurrentSettings.import_sources.include?('gitlab')
292 293 294
  end

  def gitlab_import_configured?
295
    Gitlab::OAuth::Provider.enabled?(:gitlab)
296 297 298
  end

  def bitbucket_import_enabled?
299
    Gitlab::CurrentSettings.import_sources.include?('bitbucket')
300 301 302
  end

  def bitbucket_import_configured?
303
    Gitlab::OAuth::Provider.enabled?(:bitbucket)
304
  end
305 306

  def google_code_import_enabled?
307
    Gitlab::CurrentSettings.import_sources.include?('google_code')
308 309
  end

Jared Szechy's avatar
Jared Szechy committed
310
  def fogbugz_import_enabled?
311
    Gitlab::CurrentSettings.import_sources.include?('fogbugz')
Jared Szechy's avatar
Jared Szechy committed
312 313
  end

314
  def git_import_enabled?
315
    Gitlab::CurrentSettings.import_sources.include?('git')
316
  end
317

318
  def gitlab_project_import_enabled?
319
    Gitlab::CurrentSettings.import_sources.include?('gitlab_project')
320 321
  end

322 323 324 325 326 327
  # U2F (universal 2nd factor) devices need a unique identifier for the application
  # to perform authentication.
  # https://developers.yubico.com/U2F/App_ID.html
  def u2f_app_id
    request.base_url
  end
328

329 330
  def set_locale(&block)
    Gitlab::I18n.with_user_locale(current_user, &block)
331
  end
332 333 334 335 336 337 338 339 340 341

  def sessionless_sign_in(user)
    if user && can?(user, :log_in)
      # Notice we are passing store false, so the user is not
      # actually stored in the session and a token is needed
      # for every request. If you want the token to work as a
      # sign in token, you can simply remove store: false.
      sign_in user, store: false
    end
  end
342 343

  def set_page_title_header
344
    # Per https://tools.ietf.org/html/rfc5987, headers need to be ISO-8859-1, not UTF-8
345
    response.headers['Page-Title'] = URI.escape(page_title('GitLab'))
346
  end
gitlabhq's avatar
gitlabhq committed
347
end