application_controller.rb 9.5 KB
Newer Older
1 2
require 'gon'

3
class ApplicationController < ActionController::Base
4 5
  include Gitlab::CurrentSettings

6
  before_filter :authenticate_user_from_token!
G
gitlabhq 已提交
7
  before_filter :authenticate_user!
8
  before_filter :reject_blocked!
9
  before_filter :check_password_expiration
10
  before_filter :ldap_security_check
11
  before_filter :default_headers
12
  before_filter :add_gon_variables
D
Dmitriy Zaporozhets 已提交
13
  before_filter :configure_permitted_parameters, if: :devise_controller?
14
  before_filter :require_email, unless: :devise_controller?
15

16
  protect_from_forgery with: :exception
17

18
  helper_method :abilities, :can?, :current_application_settings
D
Douwe Maan 已提交
19
  helper_method :github_import_enabled?, :gitlab_import_enabled?, :bitbucket_import_enabled?
G
gitlabhq 已提交
20

21
  rescue_from Encoding::CompatibilityError do |exception|
R
Riyad Preukschas 已提交
22
    log_exception(exception)
C
Cyril 已提交
23
    render "errors/encoding", layout: "errors", status: 500
24 25
  end

26
  rescue_from ActiveRecord::RecordNotFound do |exception|
R
Riyad Preukschas 已提交
27
    log_exception(exception)
C
Cyril 已提交
28
    render "errors/not_found", layout: "errors", status: 404
G
gitlabhq 已提交
29 30
  end

N
Nihad Abbasov 已提交
31
  protected
G
gitlabhq 已提交
32

33
  # From https://github.com/plataformatec/devise/wiki/How-To:-Simple-Token-Authentication-Example
34
  # https://gist.github.com/josevalim/fb706b1e933ef01e4fb6
35
  def authenticate_user_from_token!
36 37 38 39 40
    user_token = if params[:authenticity_token].presence
                   params[:authenticity_token].presence
                 elsif params[:private_token].presence
                   params[:private_token].presence
                 end
41 42 43 44 45 46 47 48 49 50 51
    user = user_token && User.find_by_authentication_token(user_token.to_s)

    if user
      # 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

52
  def authenticate_user!(*args)
S
Steven Burgart 已提交
53
    # If user is not signed-in and tries to access root_path - redirect him to landing page
54 55 56 57 58 59
    if current_application_settings.home_page_url.present?
      if current_user.nil? && controller_name == 'dashboard' && action_name == 'show'
        redirect_to current_application_settings.home_page_url and return
      end
    end

60
    super(*args)
61 62
  end

R
Riyad Preukschas 已提交
63 64 65 66 67 68
  def log_exception(exception)
    application_trace = ActionDispatch::ExceptionWrapper.new(env, exception).application_trace
    application_trace.map!{ |t| "  #{t}\n" }
    logger.error "\n#{exception.class.name} (#{exception.message}):\n#{application_trace.join}"
  end

69
  def reject_blocked!
70
    if current_user && current_user.blocked?
71
      sign_out current_user
72
      flash[:alert] = "Your account is blocked. Retry when an admin has unblocked it."
73 74 75 76
      redirect_to new_user_session_path
    end
  end

77
  def after_sign_in_path_for(resource)
78
    if resource.is_a?(User) && resource.respond_to?(:blocked?) && resource.blocked?
R
randx 已提交
79
      sign_out resource
80
      flash[:alert] = "Your account is blocked. Retry when an admin has unblocked it."
R
randx 已提交
81 82
      new_user_session_path
    else
83
      stored_location_for(:redirect) || stored_location_for(resource) || root_path
R
randx 已提交
84 85 86
    end
  end

G
gitlabhq 已提交
87
  def abilities
C
Ciro Santilli 已提交
88
    Ability.abilities
G
gitlabhq 已提交
89 90 91 92 93 94
  end

  def can?(object, action, subject)
    abilities.allowed?(object, action, subject)
  end

N
Nihad Abbasov 已提交
95
  def project
96
    unless @project
V
Vinnie Okada 已提交
97
      namespace = params[:namespace_id]
98 99 100 101 102 103 104 105 106 107 108
      id = params[:project_id] || params[:id]

      # Redirect from
      #   localhost/group/project.git
      # to
      #   localhost/group/project
      #
      if id =~ /\.git\Z/
        redirect_to request.original_url.gsub(/\.git\Z/, '') and return
      end

V
Vinnie Okada 已提交
109
      @project = Project.find_with_namespace("#{namespace}/#{id}")
110 111 112 113 114 115 116 117 118 119

      if @project and can?(current_user, :read_project, @project)
        @project
      elsif current_user.nil?
        @project = nil
        authenticate_user!
      else
        @project = nil
        render_404 and return
      end
120
    end
121
    @project
G
gitlabhq 已提交
122 123
  end

D
Dmitriy Zaporozhets 已提交
124 125
  def repository
    @repository ||= project.repository
V
Vinnie Okada 已提交
126 127
  rescue Grit::NoSuchPathError(e)
    log_exception(e)
D
Dmitriy Zaporozhets 已提交
128 129 130
    nil
  end

G
gitlabhq 已提交
131
  def authorize_project!(action)
132
    return access_denied! unless can?(current_user, action, project)
G
gitlabhq 已提交
133 134
  end

D
Drew Blessing 已提交
135 136 137 138 139
  def authorize_labels!
    # Labels should be accessible for issues and/or merge requests
    authorize_read_issue! || authorize_read_merge_request!
  end

G
gitlabhq 已提交
140
  def access_denied!
C
Cyril 已提交
141
    render "errors/access_denied", layout: "errors", status: 404
142 143 144
  end

  def not_found!
C
Cyril 已提交
145
    render "errors/not_found", layout: "errors", status: 404
146 147 148
  end

  def git_not_found!
C
Cyril 已提交
149
    render "errors/git_not_found", layout: "errors", status: 404
G
gitlabhq 已提交
150 151 152 153 154 155 156 157 158
  end

  def method_missing(method_sym, *arguments, &block)
    if method_sym.to_s =~ /^authorize_(.*)!$/
      authorize_project!($1.to_sym)
    else
      super
    end
  end
G
gitlabhq 已提交
159

160 161
  def render_403
    head :forbidden
G
gitlabhq 已提交
162
  end
G
gitlabhq 已提交
163

164 165
  def render_404
    render file: Rails.root.join("public", "404"), layout: false, status: "404"
166 167
  end

G
gitlabhq 已提交
168
  def require_non_empty_project
169
    redirect_to @project if @project.empty_repo?
G
gitlabhq 已提交
170
  end
D
Dmitriy Zaporozhets 已提交
171

D
Dmitriy Zaporozhets 已提交
172 173 174 175 176
  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
D
Dmitriy Zaporozhets 已提交
177

178 179 180
  def default_headers
    headers['X-Frame-Options'] = 'DENY'
    headers['X-XSS-Protection'] = '1; mode=block'
X
xyb 已提交
181
    headers['X-UA-Compatible'] = 'IE=edge'
182
    headers['X-Content-Type-Options'] = 'nosniff'
183
    headers['Strict-Transport-Security'] = 'max-age=31536000' if Gitlab.config.gitlab.https
184
  end
185 186

  def add_gon_variables
187
    gon.default_issues_tracker = Project.new.default_issue_tracker.to_param
188
    gon.api_version = API::API.version
189
    gon.relative_url_root = Gitlab.config.gitlab.relative_url_root
190
    gon.default_avatar_url = URI::join(Gitlab.config.gitlab.url, ActionController::Base.helpers.image_path('no_avatar.png')).to_s
191 192 193 194 195

    if current_user
      gon.current_user_id = current_user.id
      gon.api_token = current_user.private_token
    end
196
  end
197 198

  def check_password_expiration
199
    if current_user && current_user.password_expires_at && current_user.password_expires_at < Time.now  && !current_user.ldap_user?
200 201 202
      redirect_to new_profile_password_path and return
    end
  end
203

204
  def ldap_security_check
205
    if current_user && current_user.requires_ldap_check?
206 207 208 209
      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
210 211 212 213
      end
    end
  end

214 215 216 217
  def event_filter
    filters = cookies['event_filter'].split(',') if cookies['event_filter'].present?
    @event_filter ||= EventFilter.new(filters)
  end
218

219 220
  def gitlab_ldap_access(&block)
    Gitlab::LDAP::Access.open { |access| block.call(access) }
221 222
  end

223 224 225 226 227 228 229 230 231 232 233 234 235
  # JSON for infinite scroll via Pager object
  def pager_json(partial, count)
    html = render_to_string(
      partial,
      layout: false,
      formats: [:html]
    )

    render json: {
      html: html,
      count: count
    }
  end
D
Dmitriy Zaporozhets 已提交
236 237 238 239 240 241 242 243

  def view_to_html_string(partial)
    render_to_string(
      partial,
      layout: false,
      formats: [:html]
    )
  end
D
Dmitriy Zaporozhets 已提交
244 245

  def configure_permitted_parameters
246
    devise_parameter_sanitizer.sanitize(:sign_in) { |u| u.permit(:username, :email, :password, :login, :remember_me) }
D
Dmitriy Zaporozhets 已提交
247
  end
248 249 250 251

  def hexdigest(string)
    Digest::SHA1.hexdigest string
  end
252 253 254 255 256 257

  def require_email
    if current_user && current_user.temp_oauth_email?
      redirect_to profile_path, notice: 'Please complete your profile with email address' and return
    end
  end
258

D
Dmitriy Zaporozhets 已提交
259
  def set_filters_params
260
    params[:sort] ||= 'created_desc'
261 262 263
    params[:scope] = 'all' if params[:scope].blank?
    params[:state] = 'opened' if params[:state].blank?

D
Dmitriy Zaporozhets 已提交
264
    @filter_params = params.dup
265 266

    if @project
D
Dmitriy Zaporozhets 已提交
267
      @filter_params[:project_id] = @project.id
268
    elsif @group
D
Dmitriy Zaporozhets 已提交
269
      @filter_params[:group_id] = @group.id
270
    else
271 272 273 274 275
      # TODO: this filter ignore issues/mr created in public or
      # internal repos where you are not a member. Enable this filter
      # or improve current implementation to filter only issues you
      # created or assigned or mentioned
      #@filter_params[:authorized_only] = true
276
    end
D
Dmitriy Zaporozhets 已提交
277 278

    @filter_params
279 280 281
  end

  def set_filter_values(collection)
282 283 284
    assignee_id = @filter_params[:assignee_id]
    author_id = @filter_params[:author_id]
    milestone_id = @filter_params[:milestone_id]
285

286
    @sort = @filter_params[:sort]
287 288 289 290 291
    @assignees = User.where(id: collection.pluck(:assignee_id))
    @authors = User.where(id: collection.pluck(:author_id))
    @milestones = Milestone.where(id: collection.pluck(:milestone_id))

    if assignee_id.present? && !assignee_id.to_i.zero?
D
Dmitriy Zaporozhets 已提交
292
      @assignee = @assignees.find_by(id: assignee_id)
293 294 295
    end

    if author_id.present? && !author_id.to_i.zero?
D
Dmitriy Zaporozhets 已提交
296
      @author = @authors.find_by(id: author_id)
297 298 299
    end

    if milestone_id.present? && !milestone_id.to_i.zero?
D
Dmitriy Zaporozhets 已提交
300
      @milestone = @milestones.find_by(id: milestone_id)
301 302
    end
  end
D
Dmitriy Zaporozhets 已提交
303 304 305 306 307 308 309 310 311 312 313 314 315 316

  def get_issues_collection
    set_filters_params
    issues = IssuesFinder.new.execute(current_user, @filter_params)
    set_filter_values(issues)
    issues
  end

  def get_merge_requests_collection
    set_filters_params
    merge_requests = MergeRequestsFinder.new.execute(current_user, @filter_params)
    set_filter_values(merge_requests)
    merge_requests
  end
D
Douwe Maan 已提交
317 318 319 320 321 322 323 324 325 326 327 328

  def github_import_enabled?
    OauthHelper.enabled_oauth_providers.include?(:github)
  end

  def gitlab_import_enabled?
    OauthHelper.enabled_oauth_providers.include?(:gitlab)
  end

  def bitbucket_import_enabled?
    OauthHelper.enabled_oauth_providers.include?(:bitbucket) && Gitlab::BitbucketImport.public_key.present?
  end
G
gitlabhq 已提交
329
end