Skip to content

Instantly share code, notes, and snippets.

@zorgsoft

zorgsoft/auth.php

Created Feb 15, 2012
Embed
What would you like to do?
Authorization library and models for Codeigniter adn Doctrine ORM
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
// Auth Library
class Auth {
public function login($login, $password){
// Login user
$login_user = Doctrine::getTable('users')->findOneBy('login', $login);
if($login_user != NULL and $login_user->password == md5($password) ){
$this->session->set_userdata('isAuthorized', TRUE);
$this->session->set_userdata($login_user);
return TRUE;
} else {
$this->session->set_userdata('isAuthorized', FALSE);
return FALSE;
}
}
public function isAuthorized(){
return $this->session->userdata('isAuthorized');
}
public function logout($redirect_url = NULL){
$this->session->sess_destroy();
if($redirect_url!=NULL)
redirect($redirect_url);
}
public function user(){
// Return user object
if(self::isAuthorized()){
$obj_user = (object) array(
'name' => $this->session->userdata('name'),
'login' => $this->session->userdata('login'),
'email' => $this->session->userdata('email'),
'phone' => $this->session->userdata('phone'),
'comment' => $this->session->userdata('comment'),
'created' => $this->session->userdata('created_at'),
'updated' => $this->session->userdata('updated_at')
);
return $obj_user;
} else {
return NULL;
}
}
public function getUserId() {
if(Auth::isAuthorized())
return $this->session->userdata('id');
else
return 0;
}
public function canAccess($rule_name){
// Return TRUE or FALSE for loggedin user by rule name
$canAccess = FALSE;
if(self::isAuthorized()){
$user_data = Doctrine::getTable('users')->findOneBy('id', $this->session->userdata('id'));
$rule_data = Doctrine::getTable('access_rights')->findOneBy('name', $rule_name);
if($user_data != NULL and $rule_data != NULL and $user_data->roles_id>0){
$roles_rights_q = Doctrine_Query::create()
->select('*')
->from('roles_rights')
->where('roles_id = ?', $user_data->roles_id)
->andWhere('access_rights_id = ?', $rule_data->id)
->limit(1);
$roles_rights = $roles_rights_q->execute();
if ($roles_rights->count()>0)
$canAccess = TRUE;
}
}
if(self::isSuperAdmin())
$canAccess = TRUE;
return $canAccess;
}
public function isSuperAdmin(){
// Return TRUE if userhas super admin right
// HC_SUPER_ADMIN_NAME
$isSuperAdmin = FALSE;
if(self::isAuthorized()){
$user_data = Doctrine::getTable('users')->findOneBy('id', $this->session->userdata('id'));
$rule_data = Doctrine::getTable('access_rights')->findOneBy('name', HC_SUPER_ADMIN_NAME);
if($user_data != NULL and $rule_data != NULL and $user_data->roles_id>0){
$roles_rights_q = Doctrine_Query::create()
->select('*')
->from('roles_rights')
->where('roles_id = ?', $user_data->roles_id)
->andWhere('access_rights_id = ?', $rule_data->id)
->limit(1);
$roles_rights = $roles_rights_q->execute();
if ($roles_rights->count()>0)
$isSuperAdmin = TRUE;
}
}
return $isSuperAdmin;
}
public function register($reg_user_data = object){
// Function for register new users, get data from object and return true is done
// or false if error
$user_data_q = Doctrine_Query::create()
->select('*')
->from('users')
->where('login = ?', $reg_user_data->login)
->orWhere('email = ?', $reg_user_data->email)
->limit(1);
$user_data = $user_data_q->execute();
if($user_data->count()>0){
return E_USER_REG_EXISTS;
} else {
if(($def_user_rule = Doctrine::getTable('access_rights')->findOneBy('name', HC_DEF_USER_RULE_NAME)) == NULL){
$def_user_rule = new Access_rights();
$def_user_rule->name = HC_DEF_USER_RULE_NAME;
$def_user_rule->description = 'Обычный зарегистрированный пользователь с минимальными правами';
$def_user_rule->save();
$user_role_data = Dctrine::getTable('access_rights')->findOneBy('id', HC_DEF_USER_ROLE_ID);
if($user_role_data != null){
$roles_rights_data = new Rolse_rights();
$roles_rights_data->roles_id = HC_DEF_USER_ROLE_ID;
$roles_rights_data->access_rights_id = $def_user_rule->id;
$roles_rights_data->save();
}
}
$user_data = new Users();
$user_data->login = $reg_user_data->login;
$user_data->email = $reg_user_data->email;
$user_data->password = $reg_user_data->password;
$user_data->name = $reg_user_data->name;
$user_data->phone = $reg_user_data->phone;
$user_data->comment = $reg_user_data->comment;
// TODO:: Change roles_id to get ID from configuraton, from base
$user_data->roles_id = HC_DEF_USER_ROLE_ID;
$user_data->save();
return E_USER_REG_DONE;
}
}
}
?>
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
Roles table (Model), descript a role name and have connection to
Users table with list of users with this role,
and have connection to many roles_rights table, named by Rights
If this role deleted, users who habe this role, roles_id set to null
*/
class Roles extends Doctrine_Record{
public function setTableDefinition() {
$this->hasColumn('name', 'string', 128);
$this->hasColumn('description', 'string', 256);
}
public function setUp() {
$this->setTableName('roles');
$this->actAs('Timestampable');
$this->hasMany('roles_rights as Rights', array(
'local' => 'id',
'foreign' => 'roles_id',
'cascade' => array('delete')
));
$this->hasMany('users as Users', array(
'local' => 'id',
'foreign' => 'roles_id',
'onDelete' => 'SET NULL'
));
}
}
?>
-- phpMyAdmin SQL Dump
-- version 3.4.5
-- http://www.phpmyadmin.net
--
-- Хост: localhost
-- Время создания: Фев 15 2012 г., 13:41
-- Версия сервера: 5.5.16
-- Версия PHP: 5.3.8
SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
--
-- База данных: `***********`
--
-- --------------------------------------------------------
--
-- Структура таблицы `roles`
--
CREATE TABLE IF NOT EXISTS `roles` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(128) DEFAULT NULL,
`description` text,
`created_at` datetime NOT NULL,
`updated_at` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ;
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
Roles_rights a table (Model) with links roles to access_rights
THis have a connection named Role and Access_right
*/
class Roles_rights extends Doctrine_Record{
public function setTableDefinition(){
$this->hasColumn('roles_id', 'boolean', null, array('default' => '0'));
$this->hasColumn('access_rights_id', 'boolean', null, array('default' => '0'));
}
public function setUp(){
$this->setTableName('roles_rights');
$this->hasOne('roles as Role', array(
'local' => 'roles_id',
'foreign' => 'id'
));
$this->hasOne('access_rights as Access_right', array(
'local' => 'access_rights_id',
'foreign' => 'id'
));
}
}
?>
-- phpMyAdmin SQL Dump
-- version 3.4.5
-- http://www.phpmyadmin.net
--
-- Хост: localhost
-- Время создания: Фев 15 2012 г., 13:42
-- Версия сервера: 5.5.16
-- Версия PHP: 5.3.8
SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
--
-- База данных: `hardkor`
--
-- --------------------------------------------------------
--
-- Структура таблицы `roles_rights`
--
CREATE TABLE IF NOT EXISTS `roles_rights` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`roles_id` tinyint(1) DEFAULT '0',
`access_rights_id` tinyint(1) DEFAULT '0',
PRIMARY KEY (`id`),
KEY `roles_id_idx` (`roles_id`),
KEY `access_rights_id_idx` (`access_rights_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=2 ;
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
Users table (Model)
Users has connection with role, named link Role
*/
class Users extends Doctrine_Record{
public function setTableDefinition(){
$this->hasColumn('login', 'string', 128, array('unique' => 'true'));
$this->hasColumn('password', 'string', 128);
$this->hasColumn('name', 'string', 256);
$this->hasColumn('email', 'string', 128, array('email' => 'true', 'unique' => 'true'));
$this->hasColumn('phone', 'string', 128);
$this->hasColumn('comment', 'string');
$this->hasColumn('roles_id', 'boolean', null, array('default' => '0'));
}
public function setUp() {
$this->setTableName('users');
$this->actAs('Timestampable');
$this->hasMutator('password', 'md5Password');
$this->hasOne('roles as Role', array(
'local' => 'roles_id',
'foreign' => 'id'));
}
protected function md5Password($value) {
$this->_set('password', md5($value));
}
}
?>
-- phpMyAdmin SQL Dump
-- version 3.4.5
-- http://www.phpmyadmin.net
--
-- Хост: localhost
-- Время создания: Фев 15 2012 г., 13:40
-- Версия сервера: 5.5.16
-- Версия PHP: 5.3.8
SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
--
-- База данных: `***********`
--
-- --------------------------------------------------------
--
-- Структура таблицы `users`
--
CREATE TABLE IF NOT EXISTS `users` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`login` varchar(128) DEFAULT NULL,
`password` varchar(128) DEFAULT NULL,
`name` text,
`email` varchar(128) DEFAULT NULL,
`phone` varchar(128) DEFAULT NULL,
`comment` text,
`roles_id` tinyint(1) DEFAULT '0',
`created_at` datetime NOT NULL,
`updated_at` datetime NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `login` (`login`),
UNIQUE KEY `email` (`email`),
KEY `roles_id_idx` (`roles_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=11 ;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.