Skip to content

Instantly share code, notes, and snippets.

@Koc

Koc/classes.php Secret

Created March 10, 2011 12:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Koc/778803cec98a82cde77b to your computer and use it in GitHub Desktop.
Save Koc/778803cec98a82cde77b to your computer and use it in GitHub Desktop.
<?php
class Account_Example implements AccountInterface
{
protected $id = null;
protected $data = array();
public function __construct(array $data)
{
$this->data = $data;
}
public function getIdentify()
{
return $this->data;
}
public function setAuthenticated($isAuthenticated)
{
$this->id = $isAuthenticated ? $this->data['id'] : null;
}
public function isAuthenticated()
{
return (bool)$this->id;
}
public function getId()
{
if (!$this->isAuthenticated()) {
throw new Exception('Not authed yet');
}
return $this->id;
}
}
class AccountProvider_Example implements AccountProviderInterface
{
protected $data = array(
'ivan' => array(
'id' => 1,
'name' => 'ivan',
'pass' => 'qwerty'
)
);
public function getAccount(CredentialsStorageInterface $credentialsStorage)
{
$criteria = $credentialsStorage->getCredentials();
if (!isset($this->data[$criteria['login']])) {
throw new Exception('User not found');
}
return new Account_Example($this->data[$criteria['login']]);
}
}
class CredentialsStorage_Form_Example implements CredentialsStorageInterface
{
public function getCredentials()
{
return array('login' => $_POST['login'], 'pass' => $_POST['pass']);
}
public function eraseCredentials(AccountInterface $account)
{
$account->setAuthenticated(false);
}
public function updateCredentials(AccountInterface $account, array $credentials)
{
}
}
class Auditor_Form_Example implements AuditorInterface
{
protected function checkIdentify(AccountInterface $account, CredentialsStorageInterface $credentialsStorage)
{
$identify = $account->getIdentify();
$credentials = $credentialsStorage->getCredentials();
return $credentials['pass'] == $identify['pass'];
}
public function identify(AccountInterface $account, CredentialsStorageInterface $credentialsStorage)
{
if (!$this->checkIdentify($account, $credentialsStorage)) {
throw new Exception('Not valid user');
}
$account->setAuthenticated(true);
}
public function updateIdentify(AccountInterface $account, CredentialsStorageInterface $credentialsStorage)
{
if (!$this->checkIdentify($account, $credentialsStorage)) {
throw new Exception('Not valid user');
}
$credentialsStorage->updateCredentials($account, array());
}
public function removeIdentify(AccountInterface $account, CredentialsStorageInterface $credentialsStorage)
{
$account->setAuthenticated(false);
$credentialsStorage->eraseCredentials($account);
}
}
class CredentialsStorage_Cookie_Example implements CredentialsStorageInterface
{
public function eraseCredentials(AccountInterface $account)
{
setcookie('passhash', '');
setcookie('login', '');
}
public function getCredentials()
{
return array('login' => $_COOKIE['login'] , 'passhash' => $_COOKIE['passhash']);
}
public function updateCredentials(AccountInterface $account, array $credentials)
{
$identify = $account->getIdentify();
setcookie('passhash', $credentials['passhash'], time() + 100500);
setcookie('login', $identify['login'], time() + 100500);
}
}
class Auditor_Cookie_Example extends Auditor_Form_Example
{
protected function checkIdentify(AccountInterface $account, CredentialsStorageInterface $credentialsStorage)
{
$identify = $account->getIdentify();
$credentials = $credentialsStorage->getCredentials();
return $credentials['passhash'] == md5($identify['pass']);
}
public function updateIdentify(AccountInterface $account, CredentialsStorageInterface $credentialsStorage)
{
if (!$this->checkIdentify($account, $credentialsStorage)) {
throw new Exception('Not valid user');
}
$identify = $account->getIdentify();
$credentialsStorage->updateCredentials($account, array('passhash' => md5($identify['pass'])));
}
}
<?php
/**
* Репозиторий, из которого выбираем пользователя (база/no-sql)
*/
interface AccountProviderInterface
{
/**
* @param CredentialsStorageInterface $credentialsStorage Критерии, по которым происходит выборка (логин/имеил/ид)
* @return AccountInterface
* @throws
*/
function getAccount(CredentialsStorageInterface $credentialsStorage);
}
/**
* Пользователь
*/
interface AccountInterface
{
/**
* @return array Данные о пользователе из постоянного хранилища, на основе которых можно проверить аутентификацию (хеш пароля+соль)
*/
function getIdentify();
/**
* @param bool $isAuthenticated
*/
function setAuthenticated($isAuthenticated);
/**
* @return bool
*/
function isAuthenticated();
/**
* @return string|int Уникальный идентификатор записи внутри текущего репозитория (ид из базы, vk/fb/twitter-userId)
*/
function getId();
}
/**
* Сравниватель паролей
*/
interface AuditorInterface
{
//TODO: кто генерирует хеш новых паролей?
//TODO: а кто кладет их в репозиторий?
/**
* Пытается выполнить аутентификацию на основе EntityInterface::getIdentify() (что в базе) и CredentialsStorageInterface::getCredentials() (что пришло от пользователя)
* @param AccountInterface $account
* @param CredentialsStorageInterface $credentialsStorage
* @throws
*/
function identify(AccountInterface $account, CredentialsStorageInterface $credentialsStorage);
/**
* Обновление сессии
* @param AccountInterface $account
* @param CredentialsStorageInterface $credentialsStorage
* @throws
*/
function updateIdentify(AccountInterface $account, CredentialsStorageInterface $credentialsStorage);
/**
* Разрыв сессии (логаут)
* @param AccountInterface $account
* @param CredentialsStorageInterface $credentialsStorage
* @throws
*/
function removeIdentify(AccountInterface $account, CredentialsStorageInterface $credentialsStorage);
}
/**
* Механизм запоминания пользователя (сессии/куки) или же данные из формы
*/
interface CredentialsStorageInterface
{
/**
* Выборка данных из сессии/куки/формы
* @return array
*/
function getCredentials();
/**
* Отсылка обновленных кук
* @param AccountInterface $account
*/
function updateCredentials(AccountInterface $account, array $credentials);
/**
* Удаление кук
* @param AccountInterface $account
*/
function eraseCredentials(AccountInterface $account);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment