summaryrefslogtreecommitdiff
path: root/app/controllers/concerns/routable_actions.rb
blob: d4ab67824441bb29ad14070ac1ffe35cc95d86bf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
module RoutableActions
  extend ActiveSupport::Concern

  def find_routable!(routable_klass, requested_full_path, extra_authorization_proc: nil)
    routable = routable_klass.find_by_full_path(requested_full_path, follow_redirects: request.get?)

    if routable_authorized?(routable_klass, routable, extra_authorization_proc)
      ensure_canonical_path(routable, requested_full_path)
      routable
    else
      route_not_found
      nil
    end
  end

  def routable_authorized?(routable_klass, routable, extra_authorization_proc)
    action = :"read_#{routable_klass.to_s.underscore}"
    return false unless can?(current_user, action, routable)

    if extra_authorization_proc
      extra_authorization_proc.call(routable)
    else
      true
    end
  end

  def ensure_canonical_path(routable, requested_path)
    return unless request.get?

    canonical_path = routable.full_path
    if canonical_path != requested_path
      if canonical_path.casecmp(requested_path) != 0
        flash[:notice] = "Project '#{requested_path}' was moved to '#{canonical_path}'. Please update any links and bookmarks that may still have the old path."
      end
      redirect_to request.original_url.sub(requested_path, canonical_path)
    end
  end
end