RSS    

   Дипломная работа: Методика обучения технологии web 2.0 на примере создания школьного сайта спортивной тематики

Листинг 2.2 Подключаемый модуль CustomControllerAclManager, проверяющий допуски перед отправкой запроса на обработку

(файл CustomControllerAclManager.php)

<?php

class CustomControllerAclManager extends Zend_Controller_Plugin_Abstract

{

// роль по умолчанию, если не вошел (или роль не определена)

private $_defaultRole = 'guest';

// выполнить операцию, если у пользователя не хватает привилегий

private $_authController = array('controller' => 'account',

'action' => 'login');

public function __construct(Zend_Auth $auth)

{

$this->auth = $auth;

$this->acl = new Zend_Acl();

// добаляем новые роли

$this->acl->addRole(new Zend_Acl_Role($this->_defaultRole));

$this->acl->addRole(new Zend_Acl_Role('member'));

$this->acl->addRole(new Zend_Acl_Role('administrator'), 'member');

// добавляем контролируемые ресурсы

$this->acl->add(new Zend_Acl_Resource('account'));

$this->acl->add(new Zend_Acl_Resource('admin'));

// по умолчанию даем всемпользователям доступ ко всему

// кроме управления учетными записями и администрированием

$this->acl->allow();

$this->acl->deny(null, 'account');

$this->acl->deny(null, 'admin');

// добавляем исключение. чтобы гости могли войти или

// зарегистрироваться, если нет привилегий

$this->acl->allow('guest', 'account', array('login',

'fetchpassword',

'register',

'registercomplete'));

// позволяем зарегистрированным пользователям доступ к управлению учетными записями

$this->acl->allow('member', 'account');

// даем администраторам доступ в область администрирования

$this->acl->allow('administrator', 'admin');

}

/**

* preDispatch

*

* Прежде, чем отправлять запрос на обработку, проверяет есть ли у пользователя

* нужные привелегии. Если нет, инициирует операцию по умолчанию

*

*

* @param Zend_Controller_Request_Abstract $request

*/

public function preDispatch(Zend_Controller_Request_Abstract $request)

{

// проверка, вошел ли пользователь и имеет ли нужную роль

// если нет, то назначается роль по умолчанию (гость)

if ($this->auth->hasIdentity())

$role = $this->auth->getIdentity()->user_type;

else

$role = $this->_defaultRole;

if (!$this->acl->hasRole($role))

$role = $this->_defaultRole;

// контролируемый ресурс - имя запрашиваемого контроллера

$resource = $request->controller;

// привилегия - имя запрашиваемой операции

$privilege = $request->action;

// если ресурс не определен явно. проверить

// глобальные допуски по умолчанию

if (!$this->acl->has($resource))

$resource = null;

// в допуске отказано. Выполняется операция по умолчанию

if (!$this->acl->isAllowed($role, $resource, $privilege)) {

$request->setControllerName($this->_authController['controller']);

$request->setActionName($this->_authController['action']);

}

}

}

?>

Листинг 2.3 Первоначальная версия класса DatabaseObject_User

(файл user.php)

<?

class DatabaseObject_User extends DatabaseObject

{

static $userTypes = array('member' => 'Member',

'administrator' => 'Administrator');

public $profile = null;

public $_newPassword = null;

public function __construct($db)

{

parent::__construct($db, 'users', 'user_id');

$this->add('username');

$this->add('password');

$this->add('user_type', 'member');

$this->add('ts_created', time(), self::TYPE_TIMESTAMP);

$this->add('ts_last_login', null, self::TYPE_TIMESTAMP);

}

}

?>

Листинг 2.4 Полный текст класса FormProcessor_UserRegistration

(файл UserRegistration.php)

<?php

 class FormProcessor_UserRegistration extends FormProcessor

{

protected $db = null;

public $user = null;

public function __construct($db)

{

parent::__construct();

$this->db = $db;

$this->user = new DatabaseObject_User($db);

$this->user->type = 'member';

}

public function process(Zend_Controller_Request_Abstract $request)

{

// проверка правильности имени

$this->username = trim($request->getPost('username'));

if (strlen($this->username) == 0)

$this->addError('username', 'Please enter a username');

else if (!DatabaseObject_User::IsValidUsername($this->username))

$this->addError('username', 'Please enter a valid username');

else if ($this->user->usernameExists($this->username))

$this->addError('username', 'The selected username already exists');

else

$this->user->username = $this->username;

// проверка имени и фамилии

$this->first_name = $this->sanitize($request->getPost('first_name'));

if (strlen($this->first_name) == 0)

$this->addError('first_name', 'Please enter your first name');

else

$this->user->profile->first_name = $this->first_name;

$this->last_name = $this->sanitize($request->getPost('last_name'));

if (strlen($this->last_name) == 0)

$this->addError('last_name', 'Please enter your last name');

else

$this->user->profile->last_name = $this->last_name;

// проверка адреса электронной почты

$this->email = $this->sanitize($request->getPost('email'));

$validator = new Zend_Validate_EmailAddress();

if (strlen($this->email) == 0)

$this->addError('email', 'Please enter your e-mail address');

else if (!$validator->isValid($this->email))

$this->addError('email', 'Please enter a valid e-mail address');

else

$this->user->profile->email = $this->email;

$session = new Zend_Session_Namespace('captcha');

$this->captcha = $this->sanitize($request->getPost('captcha'));

if ($this->captcha != $session->phrase)

$this->addError('captcha', 'Please enter the correct phrase');

// если ошибок нет, сохранить данные пользоваетля

if (!$this->hasError()) {

$this->user->save();

unset($session->phrase);

}

// возврат true, если нет ошибок

return !$this->hasError();

}

}

Листинг 2.5 Шаблон HTML для формы регистрации пользователей

(файл register.tpl)

{include file='header.tpl'}

<form method="post" action="/account/register">

<fieldset>

<legend>Создание аккаунта</legend>

<div class="error"{if !$fp->hasError()} style="display: none"{/if}>

Заполните поля

</div>

<div class="row" id="form_username_container">

<label for="form_username">Логин:</label>

<input type="text" id="form_username"

name="username" value="escape" />

{include file='lib/error.tpl' error=$fp->getError('username')}

</div>

<div class="row" id="form_email_container">

<label for="form_email">E-mail:</label>

<input type="text" id="form_email"

name="email" value="$fp->email" />

{include file='lib/error.tpl' error=$fp->getError('email')}

</div>

<div class="row" id="form_first_name_container">

<label for="form_first_name">Имя:</label>

<input type="text" id="form_first_name"

name="first_name" value="$fp->first_name" />

{include file='lib/error.tpl' error=$fp->getError('first_name')}

</div>

<div class="row" id="form_last_name_container">

<label for="form_last_name">Фамилия:</label>

<input type="text" id="form_last_name"

name="last_name" value="$fp->last_name" />

{include file='lib/error.tpl' error=$fp->getError('last_name')}

</div>

<div class="captcha">

<img src="/utility/captcha" alt="CAPTCHA image" />

</div>

<div class="row" id="form_captcha_container">

<label for="form_captcha">Введите символы, изображенные на картинке:</label>

<input type="text" id="form_captcha"

name="captcha" value="escape" />

{include file='lib/error.tpl' error=$fp->getError('captcha')}

</div>

<div class="submit">

<input type="submit" value="Register" />

</div>

</fieldset>

</form>

{include file='footer.tpl'}

Листинг 2.6 Форма входа на сайт (файл login.tpl)

{include file='header.tpl'}

<form method="post" action="/account/login">

<fieldset>

Страницы: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14


Новости


Быстрый поиск

Группа вКонтакте: новости

Пока нет

Новости в Twitter и Facebook

                   

Новости

© 2010.