端くれプログラマの備忘録 CakePHP [CakePHP] パスワードのリセット機能を実装する (2)

[CakePHP] パスワードのリセット機能を実装する (2)

(前回の続き)

メールアドレス入力 → パスワードリセットのリンクをメール送信

まずビューを実装。

<?php /*app/View/Users/recover.ctp*/ ?>

<h2>Recover Password</h2>
<?php
echo $this->Form->create('User', array('action' => 'recover'));
echo $this->Form->input('email');
echo $this->Form->end('Recover');
?>

そしてアクションを実装。

// app/Controller/UsersController.php

...
class UsersController extends AppController {
    ...
    // Allows the user to email themselves a password redemption token.
    public function recover() {
        if ($this->Auth->user()) {
            $this->redirect(array('action' => 'password'));
        }
        if (!empty($this->data['User']['email'])) {
            $user = $this->User->find('first', array(
                'recursive' => -1,
                'conditions' => array('User.email' => $this->data['User']['email']),
            ));
            if ($user === false || empty($user)) {
                $this->Session->setFlash('No matching user found.');
                return false;
            }
            $Token = ClassRegistry::init('Token');
            $token = $Token->generate(array('User' => $user['User']));
            $this->Session->setFlash('An email has been sent to your account, please follow the instruction in this email.');
            
            $email = new CakeEmail();
            $email->template('recover', 'default');
            $email->viewVars(array('user' => $user, 'token' => $token));
            $email->from(array('sender@domain.com' => 'Sender'));
            $email->to($this->data['User']['email']);
            $email->subject('Password recovery');
            $email->send();
        }
    }
    ....
}

メールのテンプレートはこんな感じ。

<?php /* app/View/Emails/text/recover.ctp*/ ?>

Someone is attempting to reset your password.

Your username for this account is: <?php echo $user['User']['username']; ?>

If you wish to continue, you may reset your password by following this link:

<?php echo Router::url(array('controller' => 'users', 'action' => 'verify', $token), true); ?>

If you did not initiate this action, please contact support.
You can log in to change your password at this address:

<?php echo Router::url(array('controller' => 'users', 'action' => 'login'), true); ?>
    
Thanks,
Support

(次回へ続く)