|  | 目前为止的 Tor
在第 1 部分的末尾,您有机会通过构建 Tor 缺少的一些功能将自己的技巧融入工作中。登录/注销、索引、使用散列密码以及自动登录注册用户都列于待完成的任务列表中。您是怎样做的?
login 视图
login 视图可能类似于清单 1。
清单 1. login 视图
<?php
if (isset($error)) {
echo('Invalid Login.');
}
?>
<p>Please log in.</p>
<?php echo $form->create('User', array('action' => 'login')); ?>
<?php
echo $form->input('username');
echo $form->input('password');
?>
<?php echo $form->end('Login');?>
<?php echo $html->link('Register', array('action' => 'register')); ?>
|
index 视图可能类似于清单 2。
清单 2. index 视图
<p>Hello, <?php echo($user['first_name'] . ' ' . $user['last_name']); ?></p>
<?php echo $html->link('knownusers', array('action' => 'knownusers')); ?>
<?php echo $html->link('logout', array('action' => 'logout')); ?>
|
这两个视图看上去应当十分简单。index 视图仅在会话中检查用户的用户名,如果尚未设置,则让用户登录。login 视图并不设置特定的错误消息,因此尝试猜测系统登录方法的人无法知道哪些信息是正确的。
控制器可能类似于清单 3。
清单 3. 控制器
<?php
class UsersController extends AppController
{
var $name = 'Users';
var $helpers = array('Html', 'Form' );
function register()
{
if (!empty($this->data))
{
$this->data['User']['password'] = md5($this->data['User']['password']);
if ($this->User->save($this->data))
{
$this->Session->setFlash('Your registration information was accepted');
$this->Session->write('user', $this->data['User']['username']);
$this->redirect(array('action' => 'index'), null, true);
} else {
$this->data['User']['password'] = '';
$this->Session->setFlash('There was a problem saving this information');
}
}
}
function knownusers()
{
$this->set('knownusers', $this->User->findAll(null,
array('id', 'username', 'first_name', 'last_name'), 'id DESC') ) ;
}
function login()
{
if ($this->data)
{
$results = $this->User->findByUsername($this->data['User']
['username']);
if ($results && $results['User']['password'] ==
md5($this->data['User']
['password']))
{
$this->Session->write('user', $this->data['User']['username']);
$this->redirect(array('action' => 'index'), null, true);
} else {
$this->set('error', true);
}
}
}
function logout()
{
$this->Session->delete('user');
$this->redirect(array('action' => 'login'), null, true);
}
function index()
{
$username = $this->Session->read('user');
if ($username)
{
$results = $this->User->findByUsername($username);
$this->set('user', $results['User']);
} else {
$this->redirect(array('action' => 'login'), null, true);
}
}
}
?>
|
使用 md5() 对密码进行散列并比较其散列值,这意味着不必将明文密码存储到数据库中 — 只需在存储之前计算这些密码的散列值。logout 操作不需要使用视图;它只需清除输入到会话中的值。
如果您的解决方案不完全相同,也没关系。如果还没有自己的解决方案,请使用以上内容更新代码,以便准备完成本教程的其余部分。
|  |
|