]> git.openstreetmap.org Git - rails.git/blob - app/controllers/user_roles_controller.rb
Merge remote-tracking branch 'upstream/pull/2038'
[rails.git] / app / controllers / user_roles_controller.rb
1 class UserRolesController < ApplicationController
2   layout "site"
3
4   before_action :authorize_web
5   before_action :require_user
6   before_action :lookup_user
7   before_action :require_administrator
8   before_action :require_valid_role
9   before_action :not_in_role, :only => [:grant]
10   before_action :in_role, :only => [:revoke]
11
12   def grant
13     @user.roles.create(:role => @role, :granter => current_user)
14     redirect_to user_path(@user)
15   end
16
17   def revoke
18     # checks that administrator role is not revoked from current user
19     if current_user == @user && @role == "administrator"
20       flash[:error] = t("user_role.filter.not_revoke_admin_current_user")
21     else
22       UserRole.where(:user_id => @user.id, :role => @role).delete_all
23     end
24     redirect_to user_path(@user)
25   end
26
27   private
28
29   ##
30   # require that the user is an administrator, or fill out a helpful error message
31   # and return them to theuser page.
32   def require_administrator
33     unless current_user.administrator?
34       flash[:error] = t "user_role.filter.not_an_administrator"
35       redirect_to user_path(@user)
36     end
37   end
38
39   ##
40   # require that the given role is valid. the role is a URL
41   # parameter, so should always be present.
42   def require_valid_role
43     @role = params[:role]
44     unless UserRole::ALL_ROLES.include?(@role)
45       flash[:error] = t("user_role.filter.not_a_role", :role => @role)
46       redirect_to user_path(@user)
47     end
48   end
49
50   ##
51   # checks that the user doesn't already have this role
52   def not_in_role
53     if @user.has_role? @role
54       flash[:error] = t("user_role.filter.already_has_role", :role => @role)
55       redirect_to user_path(@user)
56     end
57   end
58
59   ##
60   # checks that the user already has this role
61   def in_role
62     unless @user.has_role? @role
63       flash[:error] = t("user_role.filter.doesnt_have_role", :role => @role)
64       redirect_to user_path(@user)
65     end
66   end
67 end