Created
November 3, 2015 13:07
-
-
Save enygma/70aa7a5ea11d50e8b1a1 to your computer and use it in GitHub Desktop.
An authentication example for PHP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
interface Subject | |
{ | |
public function getIdentifier(); | |
public function getCredential(); | |
} | |
interface Enforcer | |
{ | |
public function evaluate(); | |
} | |
abstract class Authenticator implements Enforcer | |
{ | |
protected $context = []; | |
public function __construct($context = array()) | |
{ | |
if (!empty($context)) { | |
$this->setContext($context); | |
} | |
} | |
public function setContext(array $context) | |
{ | |
$this->context = $context; | |
} | |
public function getContext($property = null) | |
{ | |
if ($property !== null) { | |
return (isset($this->context[$property])) ? $this->context[$property] : null; | |
} else { | |
return $this->context; | |
} | |
} | |
} | |
class PasswordAuthenticator extends Authenticator | |
{ | |
public function evaluate() | |
{ | |
$user = $this->getContext('user'); | |
$password = $this->getContext('password'); | |
if ($user === null || $password === null) { | |
throw new \Exception('Invalid username or password!'); | |
} | |
// Compare the values | |
return password_verify($password, $user->getCredential()); | |
} | |
public function login(Subject $user, $password) | |
{ | |
$this->setContext([ | |
'user' => $user, | |
'password' => $password | |
]); | |
return $this->evaluate(); | |
} | |
} | |
//-------------------- | |
class User implements Subject | |
{ | |
private $properties = []; | |
public function __construct($properties) | |
{ | |
$this->properties = $properties; | |
} | |
public function getIdentifier() | |
{ | |
return $this->properties['username']; | |
} | |
public function getCredential() | |
{ | |
return $this->properties['password']; | |
} | |
} | |
$user = new User([ | |
'username' => 'ccornutt', | |
'password' => '$2y$10$qDOrBNv9ZsYE4AmmYOk6BuNIT6uoH2DOahpNep7tS4w3u4NbmCwcG' | |
]); | |
echo 'ident: '.$user->getIdentifier()."\n"; | |
$password = 'test1234'; | |
$authn = new PasswordAuthenticator(); | |
$result = $authn->login($user, $password); | |
echo 'RESULT: '.var_export($result, true)."\n"; | |
echo "\n\n"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment