Reputation: 1395
I need help with defining user roles. I have created my own authentication and am working on a custom authorization. However I need to define user roles. I have my roles created but I don't believe they have any true value with exactly what they should do.
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) }
ROLES = %w[admin user guest banned]
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
Upvotes: 0
Views: 387
Reputation: 3371
You can do something like that on your controllers :
class ResourcesController < ApplicationController
before_filter :check_current_user_is_admin, :only => [:new,...]
...
private
def check_current_user_is_admin
return if current_user.role == 'admin'
redirect_to error_page
end
end
It's an example, you can do what you want...
Upvotes: 0
Reputation: 365
U can place a boolean field for each of your roles in your db so that you can directly call
if user.admin?
// your authorization logic goes here
end
Upvotes: 2
Reputation: 479
I would take a look at rolify
and cancan
.
rolify
allows you to easily define roles for your users:
user = User.find(1)
user.add_role :admin
Define roles on a specific class:
user.add_role :moderator, Forum
Define roles on specific instances:
user.add_role :moderator, Forum.first
cancan
then allows you to define abilities, i.e. what a user
can do. It works really well with rolify
:
if user.has_role? :admin, User
can :manage, :all
else
can :manage, User, :id => user.id
end
The first ability definition defines that admins can manage (that is read
, create
, update
, and destroy
) everything.
The second ability definition says that non-admins can only manage themselves. i.e. I can only edit my own email address; I can't even view your user record!
The READMEs for both gems
are excellent and link to further reading. I'm also going to be blogging about a fairly complete example that involves rolify
, cancan
, aasm
, omniauth
and Rails Observers in the next few days. The example will show how to create a state-machine (aasm
) based email confirmation model, using rolify
and cancan
for permissions
Upvotes: 1