簡體   English   中英

在rails上的ruby中禁用除admin之外的所有登錄

[英]disable all logins except admin in ruby on rails

在做管理工作時,我想禁用用戶登錄 - 有沒有辦法使用設計 - 我不認為這適合rolify - 因為這是暫時的禁用 - 提前感謝任何幫助,瑞克

這是我要做的:

1.為您的用戶模型創建方法。 它可能類似於activeable_to_login

2.將此屬性設置為:boolean

3.使用rails console 使用控制台將活動方法設置為truefalse ,啟用或禁用用戶訪問您的應用程序:

user = User.all
   user.each do |u|
     u.active = false # or
     u.able_to_login = false
     u.save
   end

我不認為這是最好的方法,但它應該工作,而無需安裝另一個寶石或重型代碼。

在/models/user.rb中添加此方法

def active_for_authentication? 
  super && is_admin?
end

def is_admin?
  # returns true if user is admin
end

這是這樣做的“設計方式”:)

后端

如果你想創建一個“維護”模式,你最好做這樣的事情:

#app/models/user.rb
class User < ActiveRecord::Base
end

#app/models/admin.rb
class Admin < User
   def maintainance!
     self.toggle! :maintainance
   end
end

這將需要maintenance在列users表,並且你必須添加一個type在列users表了。

您可以在User模型中保留此信息,但是,您需要一些條件來確定用戶是否為管理員。 既然你沒有說明你的差異化,那么我們就是這樣做的。

-

你可以像這樣調用它:

#app/controllers/users_controller.rb
class SettingsController < ApplicationController
   before_action :authenticate_user!
   def maintenance
      current_user.maintenance! #-> toggles so you'll just be able to call this as you need.
   end
end

#config/routes.rb
resources :settings, only: [] do
    put :maintenance #-> url.com/settings/maintenance (considering current_user present)
end

這將允許您通過user設置區域設置 “維護”模式。 如果您沒有,您將能夠使用上述代碼使其正常工作。


前端

隨着后端到位,您將能夠管理前端。

為此,您需要一個幫助程序來確定是否有用戶設置了“維護”模式...

#app/helpers/application_helper.rb
class ApplicationHelper
   def maintenance_mode?
      Admin.exists? maintenance: true
   end
end

這將允許您使用此幫助程序來確定是否應允許Devise接受登錄:

#app/views/devise/sessions/new.html.erb
<% unless maintenance_mode? %>
  ... devise form ...
<% end %>

助手將執行一個數據庫請求,但保持它在devise領域唯一的 (即它不是“全站”),應該讓好的。

#app/controllers/devise/sessions_controller.rb
class SessionsController < Devise::SessionsController
   before_action :check_maintenance

   private

   def check_maintenance 
       redirect_to root_path, notice: "Sorry, maintenance mode is in effect; no logins." if maintenance_mode?
   end
end

這將阻止任何基於控制器的操作觸發。

最后,如果你想擺脫任何登錄用戶 ,你需要做一些古怪的事情,比如重置會話或類似的事情:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM