Authentication using Jelly and Jelly-Auth. Part 2

Просмотров: 4469Комментарии: 0
Web frameworks

Russian version "Аутентификация с использованием Jelly и Jelly-Auth -- часть 2"

Previous part of the tutorial

In this part of Kohana 3 tutorial I'll add auto-login and make some using of the role system, presented in Jelly-Auth Kohana 3 module. But at first some updates for previous part needed. 

1. Instead of
[code lang="php"]$this->auth = Jelly_Auth::instance();[/code]
it would be better to use
[code lang="php"]$this->auth = Auth::instance();[/code]
to retain some code flexibilty. Thanks SpadXIII

2. The Kohana 3 ORM module is really useless here and can be unplugged. Thanks to Sezarin.

3. Additional Controller_admin::$user property assigned in before() can be handy to use in controller:
[code lang="php"]$this->user = $this->auth->get_user();[/code]

3. In Meta fields description of Jelly-Auth user model 'email' field is defined as unique but not checked for non-emptiness. So it can accept empty 'email' field first time but if someone else makes his email empty -- Database Exception is being thrown (because in DB 'email' field is under UNIQUE index). And this exception can not be caught because controller looks for Validation Exception only (this makes me dislike validation using exceptions). I've fixed that by extending Jelly-Auth User model with overloading of initialize() method:

[code lang="php"]public static function initialize(Jelly_Meta $meta)


$meta->fields = array(

'email' => new Field_Email(array(

'unique' => TRUE,

'rules' => array(

'not_empty' => array(TRUE),







Finally, I fixed some validation errors messaging in my code.

Now we can start with adding some features.

To add auto-login, I need to:
A) modify login form by adding checkbox "Remember me"

B) add this checkbox processing to the Controller_admin::acton_login() metod

[code lang="php"]

// try to login

if ($_POST)


$username = $_POST['username'];

$password = $_POST['password'];

$remember = isset($_POST['remember']) ? TRUE : FALSE;

if ($this->auth->login($username, $password, $remember))



} else {

$errors = array('Login or password incorrect');




C) rewrite 'restricted access' methods considering possible auto-login -- for my code it was easy. Only check page access using $this->auth->logged_in('login'), that automatically tries to auto-login a visitor.

Jelly-Auth module has a possibility to make a role system. This possibility can be realized by assigning some initially determined roles to registered users and checking users to have needed roles by Model_User::has_role($role) method. For example, we can allow adding new users only for people having 'admin' role:

To allow role assigning in user profile:
A) in Controller_admin::action_users() method's 'edit' branch I have to get all system roles (Jelly::select('roles')->execute()) and user roles ($user->roles) then put them into 'edit user profile' template:

[code lang="php"]

$roles = Jelly::select('roles')



if ($is_saved)


$this->template->content = 'User profile was updated';

} else {

// output user profile form

$this->template->content = $content

->set('id', $user->id)

->set('username', $user->username)

->set('email', $user->email)

->set('user_roles', $user->roles->as_array())

->set('roles', $roles);



B) in 'edit user profile' form ('views/admin/edit_user') add role checkboxes like

[code lang="php"]


<span>Assigned roles</span>

<ul style="list-style-type: none;">


$role_ids = array();

foreach ($user_roles as $ur)


$role_ids[] = $ur['id'];


foreach ($roles as $role)





echo Form::checkbox('roles[]', $role['id'], in_array($role['id'], $role_ids), array('id' => 'roles_'.$role['id'])).' '

.Form::label('roles_'.$role['id'], $role['name'].'<br />'.$role['description']);









C) Finally, I should process roles array from POST (after user profile editing):

[code lang="php"]$user->roles = isset($_POST['roles']) ? $_POST['roles'] : array();[/code]
And all checked roles as well as qther fields will be assigned in $user->save() method.

After that role assigning I can allow, for example, to add a new user only for 'admin' roled users.

[code lang="php"]if ($this->user->has_role('admin'))



Unfortunately, storing user data in session leads to applying profile changes only after re-login (in case he was logged in during profile changes).

That role system itself is very simple and can be useful only for simple applications. In other cases we'll need to do something different. 

Скачать / Download 80 (zipped ~11 KiB)

Оставьте комментарий!

Используйте нормальные имена.



Если вы уже зарегистрированы как комментатор или хотите зарегистрироваться, укажите пароль и свой действующий email. При регистрации на указанный адрес придет письмо с кодом активации и ссылкой на ваш персональный аккаунт, где вы сможете изменить свои данные, включая адрес сайта, ник, описание, контакты и т.д., а также подписку на новые комментарии.

MaxSiteAuth. Войти через loginza