Bläddra i källkod

Admins can deactivate user accounts

Dominik Sander 9 år sedan
förälder
incheckning
8508928943

+ 19 - 1
app/controllers/admin/users_controller.rb

@@ -1,7 +1,7 @@
 class Admin::UsersController < ApplicationController
   before_action :authenticate_admin!
 
-  before_action :find_user, only: [:edit, :destroy, :update]
+  before_action :find_user, only: [:edit, :destroy, :update, :deactivate, :activate]
 
   helper_method :resource
 
@@ -64,6 +64,24 @@ class Admin::UsersController < ApplicationController
     end
   end
 
+  def deactivate
+    @user.deactivate!
+
+    respond_to do |format|
+      format.html { redirect_to admin_users_path, notice: "User '#{@user.username}' was deactivated." }
+      format.json { render json: @user, status: :ok, location: admin_users_path(@user) }
+    end
+  end
+
+  def activate
+    @user.activate!
+
+    respond_to do |format|
+      format.html { redirect_to admin_users_path, notice: "User '#{@user.username}' was activated." }
+      format.json { render json: @user, status: :ok, location: admin_users_path(@user) }
+    end
+  end
+
   private
 
   def find_user

+ 13 - 0
app/helpers/users_helper.rb

@@ -0,0 +1,13 @@
+module UsersHelper
+  def user_account_state(user)
+    if !user.active?
+      content_tag :span, 'inactive', class: 'label label-danger'
+    elsif user.access_locked?
+      content_tag :span, 'locked', class: 'label label-danger'
+    elsif ENV['REQUIRE_CONFIRMED_EMAIL'] == 'true' && !user.confirmed?
+      content_tag :span, 'unconfirmed', class: 'label label-warning'
+    else
+      content_tag :span, 'active', class: 'label label-success'
+    end
+  end
+end

+ 4 - 4
app/models/agent.rb

@@ -61,8 +61,8 @@ class Agent < ActiveRecord::Base
   has_many :scenario_memberships, :dependent => :destroy, :inverse_of => :agent
   has_many :scenarios, :through => :scenario_memberships, :inverse_of => :agents
 
-  scope :active,   -> { where(disabled: false) }
-  scope :inactive, -> { where(disabled: true) }
+  scope :active,   -> { where(disabled: false, deactivated: false) }
+  scope :inactive, -> { where(['disabled = ? OR deactivated = ?', true, true]) }
 
   scope :of_type, lambda { |type|
     type = case type
@@ -381,7 +381,7 @@ class Agent < ActiveRecord::Base
                 joins("JOIN links ON (links.receiver_id = agents.id)").
                 joins("JOIN agents AS sources ON (links.source_id = sources.id)").
                 joins("JOIN events ON (events.agent_id = sources.id AND events.id > links.event_id_at_creation)").
-                where("NOT agents.disabled AND (agents.last_checked_event_id IS NULL OR events.id > agents.last_checked_event_id)")
+                where("NOT agents.disabled AND NOT agents.deactivated AND (agents.last_checked_event_id IS NULL OR events.id > agents.last_checked_event_id)")
         if options[:only_receivers].present?
           scope = scope.where("agents.id in (?)", options[:only_receivers])
         end
@@ -432,7 +432,7 @@ class Agent < ActiveRecord::Base
     # per type of agent, so you can override this to define custom bulk check behavior for your custom Agent type.
     def bulk_check(schedule)
       raise "Call #bulk_check on the appropriate subclass of Agent" if self == Agent
-      where("agents.schedule = ? and disabled = false", schedule).pluck("agents.id").each do |agent_id|
+      where("NOT disabled AND NOT deactivated AND schedule = ?", schedule).pluck("agents.id").each do |agent_id|
         async_check(agent_id)
       end
     end

+ 26 - 0
app/models/user.rb

@@ -43,6 +43,32 @@ class User < ActiveRecord::Base
     end
   end
 
+  def active?
+    !deactivated_at
+  end
+
+  def deactivate!
+    User.transaction do
+      agents.update_all(deactivated: true)
+      update_attribute(:deactivated_at, Time.now)
+    end
+  end
+
+  def activate!
+    User.transaction do
+      agents.update_all(deactivated: false)
+      update_attribute(:deactivated_at, nil)
+    end
+  end
+
+  def active_for_authentication?
+    super && active?
+  end
+
+  def inactive_message
+    active? ? super : :deactivated_account
+  end
+
   def self.using_invitation_code?
     ENV['SKIP_INVITATION_CODE'] != 'true'
   end

+ 7 - 2
app/views/admin/users/index.html.erb

@@ -14,7 +14,7 @@
             <th>Email</th>
             <th>State</th>
             <th>Active agents</th>
-            <th>Inactive agents</th>
+            <th>Deactivated agents</th>
             <th>Registered since</th>
             <th>Options</th>
           </tr>
@@ -23,12 +23,17 @@
             <tr>
               <td><%= link_to user.username, edit_admin_user_path(user) %></td>
               <td><%= user.email %></td>
-              <td>state</td>
+              <td><%= user_account_state(user) %></td>
               <td><%= user.agents.active.count %></td>
               <td><%= user.agents.inactive.count %></td>
               <td title='<%= user.created_at %>'><%= time_ago_in_words user.created_at %> ago</td>
               <td>
                 <div class="btn-group btn-group-xs">
+                  <% if user.active? %>
+                    <%= link_to 'Deactivate', deactivate_admin_user_path(user), method: :put, class: "btn btn-default" %>
+                  <% else %>
+                    <%= link_to 'Activate', activate_admin_user_path(user), method: :put, class: "btn btn-default" %>
+                  <% end %>
                   <%= link_to 'Delete', admin_user_path(user), method: :delete, data: { confirm: 'Are you sure? This can not be undone.' }, class: "btn btn-default" %>
                 </div>
               </td>

+ 3 - 0
config/locales/en.yml

@@ -2,6 +2,9 @@
 # See https://github.com/svenfuchs/rails-i18n/tree/master/rails%2Flocale for starting points.
 
 en:
+  devise:
+    failure:
+      deactivated_account: "Your account has been deactivated by an administrator."
   datetime:
     distance_in_words:
       half_a_minute: "half a minute"

+ 6 - 1
config/routes.rb

@@ -67,7 +67,12 @@ Huginn::Application.routes.draw do
   end
 
   namespace :admin do
-    resources :users, except: :show
+    resources :users, except: :show do
+      member do
+        put :deactivate
+        put :activate
+      end
+    end
   end
 
   get "/worker_status" => "worker_status#show"

+ 7 - 0
db/migrate/20160302095413_add_deactivated_at_to_users.rb

@@ -0,0 +1,7 @@
+class AddDeactivatedAtToUsers < ActiveRecord::Migration
+  def change
+    add_column :users, :deactivated_at, :datetime
+
+    add_index :users, :deactivated_at
+  end
+end

+ 6 - 0
db/migrate/20160307084729_add_deactivated_to_agents.rb

@@ -0,0 +1,6 @@
+class AddDeactivatedToAgents < ActiveRecord::Migration
+  def change
+    add_column :agents, :deactivated, :boolean, default: false
+    add_index :agents, [:disabled, :deactivated]
+  end
+end

+ 20 - 0
spec/features/admin_users_spec.rb

@@ -78,5 +78,25 @@ describe Admin::UsersController do
         expect(page).to have_text("Password confirmation doesn't match")
       end
     end
+
+    context "(de)activating users" do
+      it "deactivates an existing user" do
+        visit admin_users_path
+        expect(page).not_to have_text('inactive')
+        find(:css, "a[href='/admin/users/#{users(:bob).id}/deactivate']").click
+        expect(page).to have_text('inactive')
+        users(:bob).reload
+        expect(users(:bob)).not_to be_active
+      end
+
+      it "deactivates an existing user" do
+        users(:bob).deactivate!
+        visit admin_users_path
+        find(:css, "a[href='/admin/users/#{users(:bob).id}/activate']").click
+        expect(page).not_to have_text('inactive')
+        users(:bob).reload
+        expect(users(:bob)).to be_active
+      end
+    end
   end
 end

+ 41 - 0
spec/models/agent_spec.rb

@@ -3,6 +3,34 @@ require 'rails_helper'
 describe Agent do
   it_behaves_like WorkingHelpers
 
+  describe '.active/inactive' do
+    let(:agent) { agents(:jane_website_agent) }
+
+    it 'is active per default' do
+      expect(Agent.active).to include(agent)
+      expect(Agent.inactive).not_to include(agent)
+    end
+
+    it 'is not active when disabled' do
+      agent.update_attribute(:disabled, true)
+      expect(Agent.active).not_to include(agent)
+      expect(Agent.inactive).to include(agent)
+    end
+
+    it 'is not active when deactivated' do
+      agent.update_attribute(:deactivated, true)
+      expect(Agent.active).not_to include(agent)
+      expect(Agent.inactive).to include(agent)
+    end
+
+    it 'is not active when disabled and deactivated' do
+      agent.update_attribute(:disabled, true)
+      agent.update_attribute(:deactivated, true)
+      expect(Agent.active).not_to include(agent)
+      expect(Agent.inactive).to include(agent)
+    end
+  end
+
   describe ".bulk_check" do
     before do
       @weather_agent_count = Agents::WeatherAgent.where(:schedule => "midnight", :disabled => false).count
@@ -18,6 +46,12 @@ describe Agent do
       mock(Agents::WeatherAgent).async_check(anything).times(@weather_agent_count - 1)
       Agents::WeatherAgent.bulk_check("midnight")
     end
+
+    it "should skip agents of deactivated accounts" do
+      agents(:bob_weather_agent).user.deactivate!
+      mock(Agents::WeatherAgent).async_check(anything).times(@weather_agent_count - 1)
+      Agents::WeatherAgent.bulk_check("midnight")
+    end
   end
 
   describe ".run_schedule" do
@@ -335,6 +369,13 @@ describe Agent do
           Agent.receive! # and we receive it
         }.to change { agents(:bob_rain_notifier_agent).reload.last_checked_event_id }
       end
+
+      it "should not run agents of deactivated accounts" do
+        agents(:bob_weather_agent).user.deactivate!
+        Agent.async_check(agents(:bob_weather_agent).id)
+        mock(Agent).async_receive(agents(:bob_rain_notifier_agent).id, anything).times(0)
+        Agent.receive!
+      end
     end
 
     describe ".async_receive" do

+ 24 - 0
spec/models/users_spec.rb

@@ -40,4 +40,28 @@ describe User do
       end
     end
   end
+
+  context '#deactivate!' do
+    it "deactivates the user and all her agents" do
+      agent = agents(:jane_website_agent)
+      users(:jane).deactivate!
+      agent.reload
+      expect(agent.deactivated).to be_truthy
+      expect(users(:jane).deactivated_at).not_to be_nil
+    end
+  end
+
+  context '#activate!' do
+    before do
+      users(:bob).deactivate!
+    end
+
+    it 'activates the user and all his agents' do
+      agent = agents(:bob_website_agent)
+      users(:bob).activate!
+      agent.reload
+      expect(agent.deactivated).to be_falsy
+      expect(users(:bob).deactivated_at).to be_nil
+    end
+  end
 end