为什么我的普通用户拥有与管理员用户相同的权限?

时间:2016-12-09 02:29:31

标签: ruby-on-rails ruby

我在views / welcome / index.html.erb中使用此命令:

<% if current_user.admin? %>
<%= link_to 'Post New Load Data!', new_article_path %>
<% else %>
<% end %>

今天早些时候,这只允许我的管理员用户查看此路径 几个小时前我安装了Devise,但结果并不喜欢它。所以我已经完成并删除了我认为它创建的每个文件。

早些时候,如果我想让普通用户看到路径,我会使用...

<% if current_user %> 

而不是

<% if current_user && current_user.admin? %>

如果这就是造成问题的原因,我不知道。我的迁移确实搞砸了,所以我不得不重置所有内容,并在db / migrate / 20161209013349_create_users.rb下创建了新的迁移:

class CreateUsers < ActiveRecord::Migration[5.0]
  def change
    create_table :users do |t|
      t.string :name
      t.string :email
      t.string :password_digest
      t.string :admin, :boolean, null: false, default: false

      t.timestamps
    end
  end
end

我检查了我的MySQL用户表,非管理员用户在admin列下有一个0。我的管理员用户在admin列下有1。普通用户和管理员的布尔列下都有一个0。

我的application_controller.rb:

class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception

  def current_user
    @current_user ||= User.find(session[:user_id]) if session[:user_id]
  end
  helper_method :current_user

  def authorize
    redirect_to '/login' unless current_user
  end

end

users_controller.rb:

class UsersController < ApplicationController

  def new

  end

  def create
    if User.exists?(email: params[:user][:email])
      redirect_to '/articles?user_or_pass_already_exists'
    else
      user = User.new(user_params)
      if user.save
        session[:user_id] = user.id
        redirect_to '/'
      else
        redirect_to '/signup'
      end
    end
end

private

  def user_params
    params.require(:user).permit(:name, :email, :password, :password_confirmation)
  end
end

关于导致这种情况的任何想法?

我认为这是我设置此模型的方式。

修改

我还在/app/models/user.rb中为我的管理员创建了这个方法:

class User < ApplicationRecord
  has_secure_password

  # convienience method to access the vaulue of admin:
  def admin?
    admin
  end

  # this makes sure the same email and user can't be registered twice
  # this only works well if you are only wanting to validate one field such as name
#validates :email, uniqueness: true

end

这就是我使用admin的原因?在我的current_user.admin?

1 个答案:

答案 0 :(得分:0)

首先,您必须明白,即使您隐藏了来自用户的链接您需要在每个操作之前进行服务器端检查(授权)。 cancancan gem会帮助你。

现在,对于你的问题,

def admin?
    admin
  end

此方法将返回admin列的值。

根据迁移中的这一行

t.string :admin, :boolean, null: false, default: false

我的猜测是数据库中admin列的列类型为string。它应该是boolean类型。 ruby中的所有字符串值都为true。

2.2.0 :004 > if "0"
2.2.0 :005?>   puts "I am true"
2.2.0 :006?>   end
(irb):6: warning: string literal in condition
I am true

因此,要么将列类型更改为boolean,要么更改user.rb中的方法

def admin?
  admin == "1"
end