CakePHP1.2 Authコンポーネントを使って認証機能を実現する
標準でAuthコンポーネントを使って認証機能を実現する。
1.userテーブル作成
CREATE TABLE `users` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`username` VARCHAR( 255 ) NOT NULL ,
`password` VARCHAR( 255 ) NOT NULL ,
`created` DATETIME NOT NULL ,
`modified` DATETIME NOT NULL
) ;
2.
userモデル作成
<?php // app/model/user.php class User extends AppModel { public $useTable = 'user'; function index(){ } } ?>
3.
userコントローラ作成
ログイン成功時はindex.ctpを表示。
ログイン失敗時はlogin.ctpを表示。
ログイン前に登録ページの表示は許可する。
<?php class UsersController extends AppController { var $name = 'Users'; var $uses = array('User'); var $helpers = array('Html','Form'); var $components = array('Auth'); function beforeFilter() { $this->Auth->allow(a('regist')); } function index(){ $this->pageTitle = 'マイページ'; } function login() { $this->pageTitle = 'ログイン'; } function logout() { $this->redirect($this->Auth->logout()); } function regist(){ $this->pageTitle = '登録'; } } ?>
4.ビュー作成
index.ctp
ログイン成功
login.ctp
<?php if ($session->check('Message.auth')){ $session->flash('auth'); } $form->create('User', array('action'=>'login', 'type'=>'post'))."\n"; $form->input('User.username')."\n"; $form->input('User.password')."\n"; $form->submit('ログイン'); $form->end(); $html->link('新規登録', array('controller'=>'users', 'action'=>'regist'), array(), null); ?>
参考にさせていただきました。
http://allweb.blog115.fc2.com/blog-entry-32.html