summaryrefslogtreecommitdiff
path: root/app/controllers/concerns/membership_actions.rb
blob: 8d07780f6c2f32e8565c3a92a0c87f3b6ed7f0f4 (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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
module MembershipActions
  extend ActiveSupport::Concern

  def create
    create_params = params.permit(:user_ids, :access_level, :expires_at)
    result = Members::CreateService.new(membershipable, current_user, create_params).execute

    redirect_url = members_page_url

    if result[:status] == :success
      redirect_to redirect_url, notice: 'Users were successfully added.'
    else
      redirect_to redirect_url, alert: result[:message]
    end
  end

  def destroy
    Members::DestroyService.new(membershipable, current_user, params).
      execute(:all)

    respond_to do |format|
      format.html do
        message = "User was successfully removed from #{source_type}."
        redirect_to members_page_url, notice: message
      end

      format.js { head :ok }
    end
  end

  def request_access
    membershipable.request_access(current_user)

    redirect_to polymorphic_path(membershipable),
                notice: 'Your request for access has been queued for review.'
  end

  def approve_access_request
    Members::ApproveAccessRequestService.new(membershipable, current_user, params).execute

    redirect_to members_page_url
  end

  def leave
    member = Members::DestroyService.new(membershipable, current_user, user_id: current_user.id).
      execute(:all)

    notice =
      if member.request?
        "Your access request to the #{source_type} has been withdrawn."
      else
        "You left the \"#{membershipable.human_name}\" #{source_type}."
      end

    respond_to do |format|
      format.html do
        redirect_path = member.request? ? member.source : [:dashboard, membershipable.class.to_s.tableize]
        redirect_to redirect_path, notice: notice
      end

      format.json { render json: { notice: notice } }
    end
  end

  protected

  def membershipable
    raise NotImplementedError
  end

  def members_page_url
    if membershipable.is_a?(Project)
      project_settings_members_path(membershipable)
    else
      polymorphic_url([membershipable, :members])
    end
  end

  def source_type
    @source_type ||= membershipable.class.to_s.humanize(capitalize: false)
  end
end