应用程序无法识别用户为管理员

时间:2013-03-15 14:24:28

标签: ruby-on-rails

我已经创建了用户角色,但我的应用却没有认识到我的帐户是管理员。它将角色显示为管理员,但管理员也是零。

来自rails console:

2.0.0-p0 :001 > user = User.find(13)
  User Load (17.4ms)  SELECT `users`.* FROM `users` WHERE `users`.`id` = 13 LIMIT 1
 => #<User id: 13, admin: nil, role: "admin", roles_mask: nil> 
2.0.0-p0 :002 > user.roles
 => [] 
2.0.0-p0 :003 > user.role?(:admin)
 => false 

如果它理解用户角色是管理员,为什么它不接受它作为管理员并给予帐户适当的权限?我需要修复此问题,因为我尝试只允许管理员修改所有配置文件,然后指定常规用户只能修改和访问自己的配置文件。

user.rb:

   class User < ActiveRecord::Base
  has_secure_password
  attr_accessible :password_confirmation, :about_me, :feet, :inches, :password, :birthday, :career, :children, :education, :email, :ethnicity, :gender, :height, :name, :password_digest, :politics, :religion, :sexuality, :user_drink, :user_smoke, :username, :zip_code
  validates_uniqueness_of :email
  validates_presence_of :password, :on => :create
  before_create { generate_token(:auth_token) }

  def send_password_reset
    generate_token(:password_reset_token)
    self.password_reset_sent_at = Time.zone.now
    save!
    UserMailer.password_reset(self).deliver
  end

  def generate_token(column)
    begin
      self[column] = SecureRandom.urlsafe_base64
    end while User.exists?(column => self[column])
  end
end

1 个答案:

答案 0 :(得分:1)

正如我在评论中所说,

user.role
=> admin

因此,您可以在application_controller中添加如下内容:

def admin
  unless current_user.role == 'admin'
    flash[:error] = "Authorisation is required to access this content."
    redirect_to current_user
  end
end

通过这种方式,您可以阻止非管理员用户访问控制器中的某些操作:

before_filter :admin, :only => [:destroy]

这只是一个给你一些方向的例子,我假设你有current_user帮助。

我希望它有所帮助...

相关问题