Created
January 22, 2015 23:09
-
-
Save MarkRedeman/00b46d7d873d21f173d7 to your computer and use it in GitHub Desktop.
This gist uses a decorator to create a `HashedValue` object from the result of the `$hasherContext->make()` function such that it is possible to determine if a string has been hashed.
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 | |
// Use a value object to represent Hashed Values (for example passwords) | |
// this way we can deterine if a string has been hashed before or if it needs hashing | |
class HashedValue { | |
private $hash; | |
public function __construct($hash = '') | |
{ | |
$this->hash = $hash; | |
} | |
public function __toString() | |
{ | |
return $this->hash; | |
} | |
} | |
trait HashPassword { | |
// TODO make it customizable | |
// protected $propertiesToHash = ['password']; | |
public function setPasswordAttribute($password) | |
{ | |
$this->attributes['password'] = $this->hashedVersionOf($password); | |
} | |
public function getPasswordAttribute($password) | |
{ | |
return $this->hashedVersionOf($password); | |
} | |
public function hashedVersionOf($value) | |
{ | |
return ($this->isHashed($value)) ? $value : $this->hash($value); | |
} | |
public function isHash($value) | |
{ | |
return is_a($value, HashedValue::class); | |
} | |
public function hash($value) | |
{ | |
return Hash::make($value); | |
} | |
} | |
use Illuminate\Contracts\Hashing\Hasher; | |
class HashedValueHasher implements HasherContract { | |
private $hasher; | |
public function __construct(HasherContract $hasher) | |
{ | |
$this->hasher = $hasher; | |
} | |
public function make($value, array $options = array()) | |
{ | |
$hash = $this->hasher->make($value, $options); | |
return new HashedValue($hash); | |
} | |
public function check($value, $hashedValue, array $options = array()) | |
{ | |
return $this->hasher->check($value, $hashedValue, $options); | |
} | |
public function needsRehash($hashedValue, array $options = array()) | |
{ | |
return $this->hasher->needsRehash($hashedValue, $options): | |
} | |
} | |
use Illuminate\Support\ServiceProvider; | |
use Illuminate\Hashing\BcryptHasher; | |
class HashVOServiceProvider extends ServiceProvider { | |
protected $defer = true; | |
public function register() | |
{ | |
$this->app->singleton('hash', function() { | |
$bcryptHasher = new BcryptHasher;; | |
return new HashedValueHasher($bcryptHasher); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment