More about Typus Authentication

In Device the easiest way to support an admin role is to simply add an attribute that can be used to identify administrators, which doesn’t involve any migration. So after following Lorien’s post, I set @admin_user to a Device user model and made sure it had all the required Typus attributes.
Below are the steps I followed:

1) Add admin attribute
[sourcecode language="ruby"]
$rails generate migration add_admin_to_user admin:boolean
[/sourcecode]

[sourcecode language="ruby"]
class AddAdminRoleToUsers < ActiveRecord::Migration
def self.up
add_column :users, :admin, :boolean, :default => false
end

def self.down
remove_column :users, :admin
end
end

[/sourcecode]

2) Add required Typus attributes.

[sourcecode language="ruby"]
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable,
:confirmable
……
#typus authentication. Need this attributes to simulate typus’s admin_user
def locale
::I18n.locale
end

def application(name)
Typus.application(name)
end

def can?(*args)
true
end

def cannot?(*args)
!can?(*args)
end

def applications
Typus.applications
end
end
[/sourcecode]

3) Set @admin_user
[sourcecode language="ruby"]
module Typus
module Authentication
module Devise
protected
include Base
def authenticate

#call devise auth
authenticate_user!
end

# Set the admin user.
def admin_user
@admin_user = current_user if current_user && current_user.admin?
end
end
end
end

[/sourcecode]

You could also use table inheritance, which is a software pattern described by Martin Fowler. The basic idea is that another field in the base database table is used to store the type of the object. But you will have to twist it around to make it work.

*Note
We have implemented this way before Francesc Esplugas’s devise support to typus.

Post a Comment

Your email is never shared. Required fields are marked *

*
*