cakephp3 ログイン処理

■AppControllerのinitialize()に

$this->loadComponent(‘Auth’,[
    ‘authorize’ => [‘Controller’],
    ‘authenticate’ => [
        ‘Form’ => [
            ‘fields’ => [
                ‘username’ => ‘username’,
                ‘password’ => ‘password’
            ]
        ]
    ],
    ‘loginRedirect’ => [
        ‘controller’ => ‘Users’,
        ‘action’ => ‘index’
    ],
    ‘logoutRedirect’ => [
        ‘controller’ => ‘Users’,
        ‘action’ => ‘login’,
    ],
    ‘loginAction’ => [
        ‘controller’ => ‘Users’,
        ‘action’ => ‘login’
    ],
    ‘authError’ => false,
]);

■UsersControllerに

public function isAuthorized($user = null){
    if(in_array($this->request->params[‘action’], [‘index’, ‘delete’])){
        if(in_array($user[‘role’], [‘admin’, ‘super’])) {
            return true;
        }
    }
    if(in_array($this->request->params[‘action’], [‘edit’])){
        if(in_array($user[‘role’], [‘admin’, ‘super’, ‘user’, ‘sp’])) {
            return true;
        }
    }

    return false;
}

public function beforeFilter(\Cake\Event\Event $event) {
    parent::beforeFilter($event);
    $this->Auth->allow([‘add’, ‘confirm’, ‘logout’]);
}

public function login()
{
    $this->viewBuilder()->setLayout(‘nohead’);

    if($this->request->is(‘post’)){
        $user = $this->Auth->identify();
        if($user){
            $this->Auth->setUser($user);
            return $this->redirect($this->Auth->redirectUrl());
        }
        $this->Flash->error(‘ユーザー名かパスワードが間違えています。’);
    }
}

public function logout()
{
    $this->Flash->success(‘ログアウトしました’);
    return $this->redirect($this->Auth->logout());
}

■login.ctp

<div class=”users form columns content”>
    <p style=”text-align:center;border-bottom:1px solid #555;”>Login</p>
    <?= $this->Form->create() ?>

    <?= $this->Form->input(‘username’) ?>
    <?= $this->Form->input(‘password’) ?>
    <?= $this->Form->button(‘Login’) ?>

    <p style=”clear:right;float:right;”><?= $this->Html->link(“ユーザー登録はこちらから”, [‘action’ => ‘add’]) ?></p>

    <?= $this->Form->end() ?>
</div>

■Model User

use Cake\Auth\DefaultPasswordHasher;

protected $_hidden = [
    ‘password’
];

protected function _setPassword($password)
{
    if (strlen($password) > 0) {
        return (new DefaultPasswordHasher)->hash($password);
    }
}

■SQL

CREATE TABLE `users` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`username` varchar(50) NOT NULL,
`password` varchar(255) NOT NULL,
`role` varchar(20) DEFAULT NULL,
`created` datetime DEFAULT NULL,
`modified` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
)

返信を残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です