JWT for mail authentication.
Easily issue tokens(JWT) that can be used for mail authentication.
No need for token field in table.
one-time/url-safe/safety 👍
- PHP 7.0+
- CakePHP 3.0.0+
composer require mosaxiv/cakephp-token-verify
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY, # Required
name VARCHAR(255) NOT NULL,
email VARCHAR(255) NOT NULL,
password VARCHAR(255) NOT NULL,
created DATETIME,
modified DATETIME # Required
);
// app/src/Model/Entity/User.php
use Token\Model\Entity\TokenTrait;
class User extends Entity
{
use TokenTrait;
}
// app/src/Controller/UsersController.php
use Cake\Routing\Router;
use Token\Util\Token;
class UsersController extends AppController
{
public function forgotPassword()
{
if ($this->request->is('post')) {
$email = $this->request->getData('email');
$user = $this->Users->findByEmail($email)->first();
if ($user) {
$token = $user->tokenGenerate();
$url = Router::url(['controller' => 'User', 'action' => 'resetPassword', $token], true);
// send email
}
}
}
public function resetPassword($token)
{
$user = $this->Users->get(Token::getId($token));
if (!$user->tokenVerify($token)) {
throw new \Cake\Network\Exception\NotFoundException();
}
if ($this->request->is('post')) {
$user = $this->Users->patchEntity($user, $this->request->getData());
if ($this->Users->save($user)) {
// success
} else {
// error
}
}
}
}
id
fieldmodified
field
By using modified field, JWT can be used as one-time tokens.
JWT should be discarded when the table is updated.
Used in entity.
// token generate(default token expiration in 10 minits)
$token = $entity->tokenGenerate();
// token generate(token expiration in 60 minits)
$token = $entity->tokenGenerate(60);
$user->tokenVerify($token) // true or false
※ It does not encrypt the set data
$user->setTokenData('test', 'testdata')
Token::getId($token) // id or false
Token::getData($token, 'test') // data or false