the whole shebang

This commit is contained in:
2014-11-25 16:42:40 +01:00
parent 7f74c0613e
commit ab1334c0cf
3686 changed files with 496409 additions and 1 deletions

View File

@@ -0,0 +1,105 @@
<?php namespace Illuminate\Auth;
use Illuminate\Support\Manager;
class AuthManager extends Manager {
/**
* Create a new driver instance.
*
* @param string $driver
* @return mixed
*/
protected function createDriver($driver)
{
$guard = parent::createDriver($driver);
// When using the remember me functionality of the authentication services we
// will need to be set the encryption instance of the guard, which allows
// secure, encrypted cookie values to get generated for those cookies.
$guard->setCookieJar($this->app['cookie']);
$guard->setDispatcher($this->app['events']);
return $guard->setRequest($this->app['request']);
}
/**
* Call a custom driver creator.
*
* @param string $driver
* @return mixed
*/
protected function callCustomCreator($driver)
{
$custom = parent::callCustomCreator($driver);
if ($custom instanceof Guard) return $custom;
return new Guard($custom, $this->app['session']);
}
/**
* Create an instance of the database driver.
*
* @return \Illuminate\Auth\Guard
*/
protected function createDatabaseDriver()
{
$provider = $this->createDatabaseProvider();
return new Guard($provider, $this->app['session']);
}
/**
* Create an instance of the database user provider.
*
* @return \Illuminate\Auth\DatabaseUserProvider
*/
protected function createDatabaseProvider()
{
$connection = $this->app['db']->connection();
// When using the basic database user provider, we need to inject the table we
// want to use, since this is not an Eloquent model we will have no way to
// know without telling the provider, so we'll inject the config value.
$table = $this->app['config']['auth.table'];
return new DatabaseUserProvider($connection, $this->app['hash'], $table);
}
/**
* Create an instance of the Eloquent driver.
*
* @return \Illuminate\Auth\Guard
*/
public function createEloquentDriver()
{
$provider = $this->createEloquentProvider();
return new Guard($provider, $this->app['session']);
}
/**
* Create an instance of the Eloquent user provider.
*
* @return \Illuminate\Auth\EloquentUserProvider
*/
protected function createEloquentProvider()
{
$model = $this->app['config']['auth.model'];
return new EloquentUserProvider($this->app['hash'], $model);
}
/**
* Get the default authentication driver name.
*
* @return string
*/
protected function getDefaultDriver()
{
return $this->app['config']['auth.driver'];
}
}

View File

@@ -0,0 +1,79 @@
<?php namespace Illuminate\Auth;
use Illuminate\Support\ServiceProvider;
class AuthServiceProvider extends ServiceProvider {
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = true;
/**
* Bootstrap the application events.
*
* @return void
*/
public function boot()
{
$this->registerAuthEvents();
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app['auth'] = $this->app->share(function($app)
{
// Once the authentication service has actually been requested by the developer
// we will set a variable in the application indicating such. This helps us
// know that we need to set any queued cookies in the after event later.
$app['auth.loaded'] = true;
return new AuthManager($app);
});
}
/**
* Register the events needed for authentication.
*
* @return void
*/
protected function registerAuthEvents()
{
$app = $this->app;
$app->after(function($request, $response) use ($app)
{
// If the authentication service has been used, we'll check for any cookies
// that may be queued by the service. These cookies are all queued until
// they are attached onto Response objects at the end of the requests.
if (isset($app['auth.loaded']))
{
foreach ($app['auth']->getDrivers() as $driver)
{
foreach ($driver->getQueuedCookies() as $cookie)
{
$response->headers->setCookie($cookie);
}
}
}
});
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return array('auth');
}
}

View File

@@ -0,0 +1,96 @@
<?php namespace Illuminate\Auth\Console;
use Illuminate\Console\Command;
use Illuminate\Filesystem\Filesystem;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
class MakeRemindersCommand extends Command {
/**
* The console command name.
*
* @var string
*/
protected $name = 'auth:reminders';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create a migration for the password reminders table';
/**
* The filesystem instance.
*
* @var \Illuminate\Filesystem\Filesystem
*/
protected $files;
/**
* Create a new reminder table command instance.
*
* @param \Illuminate\Filesystem\Filesystem $files
* @return void
*/
public function __construct(Filesystem $files)
{
parent::__construct();
$this->files = $files;
}
/**
* Execute the console command.
*
* @return void
*/
public function fire()
{
$fullPath = $this->createBaseMigration();
$this->files->put($fullPath, $this->getMigrationStub());
$this->info('Migration created successfully!');
$this->call('dump-autoload');
}
/**
* Create a base migration file for the reminders.
*
* @return string
*/
protected function createBaseMigration()
{
$name = 'create_password_reminders_table';
$path = $this->laravel['path'].'/database/migrations';
return $this->laravel['migration.creator']->create($name, $path);
}
/**
* Get the contents of the reminder migration stub.
*
* @return string
*/
protected function getMigrationStub()
{
$stub = $this->files->get(__DIR__.'/stubs/reminders.stub');
return str_replace('password_reminders', $this->getTable(), $stub);
}
/**
* Get the password reminder table name.
*
* @return string
*/
protected function getTable()
{
return $this->laravel['config']->get('auth.reminder.table');
}
}

View File

@@ -0,0 +1,32 @@
<?php
use Illuminate\Database\Migrations\Migration;
class CreatePasswordRemindersTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('password_reminders', function($t)
{
$t->string('email');
$t->string('token');
$t->timestamp('created_at');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('password_reminders');
}
}

View File

@@ -0,0 +1,106 @@
<?php namespace Illuminate\Auth;
use Illuminate\Database\Connection;
use Illuminate\Hashing\HasherInterface;
class DatabaseUserProvider implements UserProviderInterface {
/**
* The active database connection.
*
* @param \Illuminate\Database\Connection
*/
protected $conn;
/**
* The hasher implementation.
*
* @var \Illuminate\Hashing\HasherInterface
*/
protected $hasher;
/**
* The table containing the users.
*
* @var string
*/
protected $table;
/**
* Create a new database user provider.
*
* @param \Illuminate\Database\Connection $conn
* @param \Illuminate\Hashing\HasherInterface $hasher
* @param string $table
* @return void
*/
public function __construct(Connection $conn, HasherInterface $hasher, $table)
{
$this->conn = $conn;
$this->table = $table;
$this->hasher = $hasher;
}
/**
* Retrieve a user by their unique identifier.
*
* @param mixed $identifier
* @return \Illuminate\Auth\UserInterface|null
*/
public function retrieveById($identifier)
{
$user = $this->conn->table($this->table)->find($identifier);
if ( ! is_null($user))
{
return new GenericUser((array) $user);
}
}
/**
* Retrieve a user by the given credentials.
*
* @param array $credentials
* @return \Illuminate\Auth\UserInterface|null
*/
public function retrieveByCredentials(array $credentials)
{
// First we will add each credential element to the query as a where clause.
// Then we can execute the query and, if we found a user, return it in a
// generic "user" object that will be utilized by the Guard instances.
$query = $this->conn->table($this->table);
foreach ($credentials as $key => $value)
{
if ( ! str_contains($key, 'password'))
{
$query->where($key, $value);
}
}
// Now we are ready to execute the query to see if we have an user matching
// the given credentials. If not, we will just return nulls and indicate
// that there are no matching users for these given credential arrays.
$user = $query->first();
if ( ! is_null($user))
{
return new GenericUser((array) $user);
}
}
/**
* Validate a user against the given credentials.
*
* @param \Illuminate\Auth\UserInterface $user
* @param array $credentials
* @return bool
*/
public function validateCredentials(UserInterface $user, array $credentials)
{
$plain = $credentials['password'];
return $this->hasher->check($plain, $user->getAuthPassword());
}
}

View File

@@ -0,0 +1,92 @@
<?php namespace Illuminate\Auth;
use Illuminate\Hashing\HasherInterface;
class EloquentUserProvider implements UserProviderInterface {
/**
* The hasher implementation.
*
* @var \Illuminate\Hashing\HasherInterface
*/
protected $hasher;
/**
* The Eloquent user model.
*
* @var string
*/
protected $model;
/**
* Create a new database user provider.
*
* @param \Illuminate\Hashing\HasherInterface $hasher
* @param string $model
* @return void
*/
public function __construct(HasherInterface $hasher, $model)
{
$this->model = $model;
$this->hasher = $hasher;
}
/**
* Retrieve a user by their unique identifier.
*
* @param mixed $identifier
* @return \Illuminate\Auth\UserInterface|null
*/
public function retrieveById($identifier)
{
return $this->createModel()->newQuery()->find($identifier);
}
/**
* Retrieve a user by the given credentials.
*
* @param array $credentials
* @return \Illuminate\Auth\UserInterface|null
*/
public function retrieveByCredentials(array $credentials)
{
// First we will add each credential element to the query as a where clause.
// Then we can execute the query and, if we found a user, return it in a
// Eloquent User "model" that will be utilized by the Guard instances.
$query = $this->createModel()->newQuery();
foreach ($credentials as $key => $value)
{
if ( ! str_contains($key, 'password')) $query->where($key, $value);
}
return $query->first();
}
/**
* Validate a user against the given credentials.
*
* @param \Illuminate\Auth\UserInterface $user
* @param array $credentials
* @return bool
*/
public function validateCredentials(UserInterface $user, array $credentials)
{
$plain = $credentials['password'];
return $this->hasher->check($plain, $user->getAuthPassword());
}
/**
* Create a new instance of the model.
*
* @return \Illuminate\Database\Eloquent\Model
*/
public function createModel()
{
$class = '\\'.ltrim($this->model, '\\');
return new $class;
}
}

View File

@@ -0,0 +1,86 @@
<?php namespace Illuminate\Auth;
class GenericUser implements UserInterface {
/**
* All of the user's attributes.
*
* @var array
*/
protected $attributes;
/**
* Create a new generic User object.
*
* @param array $attributes
* @return void
*/
public function __construct(array $attributes)
{
$this->attributes = $attributes;
}
/**
* Get the unique identifier for the user.
*
* @return mixed
*/
public function getAuthIdentifier()
{
return $this->attributes['id'];
}
/**
* Get the password for the user.
*
* @return string
*/
public function getAuthPassword()
{
return $this->attributes['password'];
}
/**
* Dynamically access the user's attributes.
*
* @param string $key
* @return mixed
*/
public function __get($key)
{
return $this->attributes[$key];
}
/**
* Dynamically set an attribute on the user.
*
* @param string $key
* @param mixed $value
* @return void
*/
public function __set($key, $value)
{
$this->attributes[$key] = $value;
}
/**
* Dynamically check if a value is set on the user.
*
* @return bool
*/
public function __isset($key)
{
return isset($this->attributes[$key]);
}
/**
* Dynamically unset a value on the user.
*
* @return bool
*/
public function __unset($key)
{
unset($this->attributes[$key]);
}
}

View File

@@ -0,0 +1,589 @@
<?php namespace Illuminate\Auth;
use Illuminate\Cookie\CookieJar;
use Illuminate\Events\Dispatcher;
use Illuminate\Encryption\Encrypter;
use Symfony\Component\HttpFoundation\Request;
use Illuminate\Session\Store as SessionStore;
use Symfony\Component\HttpFoundation\Response;
class Guard {
/**
* The currently authenticated user.
*
* @var UserInterface
*/
protected $user;
/**
* The user provider implementation.
*
* @var \Illuminate\Auth\UserProviderInterface
*/
protected $provider;
/**
* The session store used by the guard.
*
* @var \Illuminate\Session\Store
*/
protected $session;
/**
* The Illuminate cookie creator service.
*
* @var \Illuminate\Cookie\CookieJar
*/
protected $cookie;
/**
* The request instance.
*
* @var \Symfony\Component\HttpFoundation\Request
*/
protected $request;
/**
* The cookies queued by the guards.
*
* @var array
*/
protected $queuedCookies = array();
/**
* The event dispatcher instance.
*
* @var \Illuminate\Events\Dispatcher
*/
protected $events;
/**
* Indicates if the logout method has been called.
*
* @var bool
*/
protected $loggedOut = false;
/**
* Create a new authentication guard.
*
* @param \Illuminate\Auth\UserProviderInterface $provider
* @param \Illuminate\Session\Store $session
* @return void
*/
public function __construct(UserProviderInterface $provider,
SessionStore $session)
{
$this->session = $session;
$this->provider = $provider;
}
/**
* Determine if the current user is authenticated.
*
* @return bool
*/
public function check()
{
return ! is_null($this->user());
}
/**
* Determine if the current user is a guest.
*
* @return bool
*/
public function guest()
{
return is_null($this->user());
}
/**
* Get the currently authenticated user.
*
* @return \Illuminate\Auth\UserInterface|null
*/
public function user()
{
if ($this->loggedOut) return;
// If we have already retrieved the user for the current request we can just
// return it back immediately. We do not want to pull the user data every
// request into the method becaue that would tremendously slow the app.
if ( ! is_null($this->user))
{
return $this->user;
}
$id = $this->session->get($this->getName());
// First we will try to load the user using the identifier in the session if
// one exists. Otherwise we will check for a "remember me" cookie in this
// request, and if one exists, attempt to retrieve the user using that.
$user = null;
if ( ! is_null($id))
{
$user = $this->provider->retrieveByID($id);
}
// If the user is null, but we decrypt a "recaller" cookie we can attempt to
// pull the user data on that cookie which serves as a remember cookie on
// the application. Once we have a user we can return it to the caller.
$recaller = $this->getRecaller();
if (is_null($user) and ! is_null($recaller))
{
$user = $this->provider->retrieveByID($recaller);
}
return $this->user = $user;
}
/**
* Get the decrypted recaller cookie for the request.
*
* @return string|null
*/
protected function getRecaller()
{
if (isset($this->cookie))
{
return $this->getCookieJar()->get($this->getRecallerName());
}
}
/**
* Log a user into the application without sessions or cookies.
*
* @param array $credentials
* @return bool
*/
public function once(array $credentials = array())
{
if ($this->validate($credentials))
{
$this->setUser($this->provider->retrieveByCredentials($credentials));
return true;
}
return false;
}
/**
* Validate a user's credentials.
*
* @param array $credentials
* @return bool
*/
public function validate(array $credentials = array())
{
return $this->attempt($credentials, false, false);
}
/**
* Attempt to authenticate using HTTP Basic Auth.
*
* @param string $field
* @param \Symfony\Component\HttpFoundation\Request $request
* @return \Symfony\Component\HttpFoundation\Response|null
*/
public function basic($field = 'email', Request $request = null)
{
if ($this->check()) return;
$request = $request ?: $this->getRequest();
// If a username is set on the HTTP basic request, we will return out without
// interrupting the request lifecycle. Otherwise, we'll need to generate a
// request indicating that the given credentials were invalid for login.
if ($this->attemptBasic($request, $field)) return;
return $this->getBasicResponse();
}
/**
* Perform a stateless HTTP Basic login attempt.
*
* @param string $field
* @param \Symfony\Component\HttpFoundation\Request $request
* @return \Symfony\Component\HttpFoundation\Response|null
*/
public function onceBasic($field = 'email', Request $request = null)
{
$request = $request ?: $this->getRequest();
if ( ! $this->once($this->getBasicCredentials($request, $field)))
{
return $this->getBasicResponse();
}
}
/**
* Attempt to authenticate using basic authentication.
*
* @param \Symfony\Component\HttpFoundation\Request $request
* @param string $field
* @return bool
*/
protected function attemptBasic(Request $request, $field)
{
if ( ! $request->getUser()) return false;
return $this->attempt($this->getBasicCredentials($request, $field));
}
/**
* Get the credential array for a HTTP Basic request.
*
* @param \Symfony\Component\HttpFoundation\Request $request
* @param string $field
* @return array
*/
protected function getBasicCredentials(Request $request, $field)
{
return array($field => $request->getUser(), 'password' => $request->getPassword());
}
/**
* Get the response for basic authentication.
*
* @return \Symfony\Component\HttpFoundation\Response
*/
protected function getBasicResponse()
{
$headers = array('WWW-Authenticate' => 'Basic');
return new Response('Invalid credentials.', 401, $headers);
}
/**
* Attempt to authenticate a user using the given credentials.
*
* @param array $credentials
* @param bool $remember
* @param bool $login
* @return bool
*/
public function attempt(array $credentials = array(), $remember = false, $login = true)
{
$this->fireAttemptEvent($credentials, $remember, $login);
$user = $this->provider->retrieveByCredentials($credentials);
// If an implementation of UserInterface was returned, we'll ask the provider
// to validate the user against the given credentials, and if they are in
// fact valid we'll log the users into the application and return true.
if ($user instanceof UserInterface)
{
if ($this->provider->validateCredentials($user, $credentials))
{
if ($login) $this->login($user, $remember);
return true;
}
}
return false;
}
/**
* Fire the attempt event with the arguments.
*
* @param array $credentials
* @param bool $remember
* @param bool $login
* @return void
*/
protected function fireAttemptEvent(array $credentials, $remember, $login)
{
if ($this->events)
{
$payload = array($credentials, $remember, $login);
$this->events->fire('auth.attempt', $payload);
}
}
/**
* Register an authentication attempt event listener.
*
* @param mixed $callback
* @return void
*/
public function attempting($callback)
{
if ($this->events)
{
$this->events->listen('auth.attempt', $callback);
}
}
/**
* Log a user into the application.
*
* @param \Illuminate\Auth\UserInterface $user
* @param bool $remember
* @return void
*/
public function login(UserInterface $user, $remember = false)
{
$id = $user->getAuthIdentifier();
$this->session->put($this->getName(), $id);
// If the user should be permanently "remembered" by the application we will
// queue a permanent cookie that contains the encrypted copy of the user
// identifier. We will then decrypt this later to retrieve the users.
if ($remember)
{
$this->queuedCookies[] = $this->createRecaller($id);
}
// If we have an event dispatcher instance set we will fire an event so that
// any listeners will hook into the authentication events and run actions
// based on the login and logout events fired from the guard instances.
if (isset($this->events))
{
$this->events->fire('auth.login', array($user, $remember));
}
$this->setUser($user);
}
/**
* Log the given user ID into the application.
*
* @param mixed $id
* @param bool $remember
* @return \Illuminate\Auth\UserInterface
*/
public function loginUsingId($id, $remember = false)
{
$this->session->put($this->getName(), $id);
return $this->login($this->provider->retrieveById($id), $remember);
}
/**
* Log the given user ID into the application without sessions or cookies.
*
* @param mixed $id
* @return bool
*/
public function onceUsingId($id)
{
$this->setUser($this->provider->retrieveById($id));
return $this->user instanceof UserInterface;
}
/**
* Create a remember me cookie for a given ID.
*
* @param mixed $id
* @return \Symfony\Component\HttpFoundation\Cookie
*/
protected function createRecaller($id)
{
return $this->getCookieJar()->forever($this->getRecallerName(), $id);
}
/**
* Log the user out of the application.
*
* @return void
*/
public function logout()
{
$user = $this->user();
// If we have an event dispatcher instance, we can fire off the logout event
// so any further processing can be done. This allows the developer to be
// listening for anytime a user signs out of this application manually.
$this->clearUserDataFromStorage();
if (isset($this->events))
{
$this->events->fire('auth.logout', array($user));
}
// Once we have fired the logout event we will clear the users out of memory
// so they are no longer available as the user is no longer considered as
// being signed into this application and should not be available here.
$this->user = null;
$this->loggedOut = true;
}
/**
* Remove the user data from the session and cookies.
*
* @return void
*/
protected function clearUserDataFromStorage()
{
$this->session->forget($this->getName());
$recaller = $this->getRecallerName();
$this->queuedCookies[] = $this->getCookieJar()->forget($recaller);
}
/**
* Get the cookies queued by the guard.
*
* @return array
*/
public function getQueuedCookies()
{
return $this->queuedCookies;
}
/**
* Get the cookie creator instance used by the guard.
*
* @return \Illuminate\Cookie\CookieJar
*/
public function getCookieJar()
{
if ( ! isset($this->cookie))
{
throw new \RuntimeException("Cookie jar has not been set.");
}
return $this->cookie;
}
/**
* Set the cookie creator instance used by the guard.
*
* @param \Illuminate\Cookie\CookieJar $cookie
* @return void
*/
public function setCookieJar(CookieJar $cookie)
{
$this->cookie = $cookie;
}
/**
* Get the event dispatcher instance.
*
* @return \Illuminate\Events\Dispatcher
*/
public function getDispatcher()
{
return $this->events;
}
/**
* Set the event dispatcher instance.
*
* @param \Illuminate\Events\Dispatcher
*/
public function setDispatcher(Dispatcher $events)
{
$this->events = $events;
}
/**
* Get the session store used by the guard.
*
* @return \Illuminate\Session\Store
*/
public function getSession()
{
return $this->session;
}
/**
* Get the user provider used by the guard.
*
* @return \Illuminate\Auth\UserProviderInterface
*/
public function getProvider()
{
return $this->provider;
}
/**
* Set the user provider used by the guard.
*
* @param \Illuminate\Auth\UserProviderInterface $provider
* @return void
*/
public function setProvider(UserProviderInterface $provider)
{
$this->provider = $provider;
}
/**
* Return the currently cached user of the application.
*
* @return \Illuminate\Auth\UserInterface|null
*/
public function getUser()
{
return $this->user;
}
/**
* Set the current user of the application.
*
* @param \Illuminate\Auth\UserInterface $user
* @return void
*/
public function setUser(UserInterface $user)
{
$this->user = $user;
$this->loggedOut = false;
}
/**
* Get the current request instance.
*
* @return \Symfony\Component\HttpFoundation\Request
*/
public function getRequest()
{
return $this->request ?: Request::createFromGlobals();
}
/**
* Set the current request instance.
*
* @param \Symfony\Component\HttpFoundation\Request
* @return \Illuminate\Auth\Guard
*/
public function setRequest(Request $request)
{
$this->request = $request;
return $this;
}
/**
* Get a unique identifier for the auth session value.
*
* @return string
*/
public function getName()
{
return 'login_'.md5(get_class($this));
}
/**
* Get the name of the cookie used to store the "recaller".
*
* @return string
*/
public function getRecallerName()
{
return 'remember_'.md5(get_class($this));
}
}

View File

@@ -0,0 +1,170 @@
<?php namespace Illuminate\Auth\Reminders;
use DateTime;
use Illuminate\Database\Connection;
class DatabaseReminderRepository implements ReminderRepositoryInterface {
/**
* The database connection instance.
*
* @var \Illuminate\Database\Connection
*/
protected $connection;
/**
* The reminder database table.
*
* @var string
*/
protected $table;
/**
* The hashing key.
*
* @var string
*/
protected $hashKey;
/**
* The number of seconds a reminder should last.
*
* @var int
*/
protected $expires;
/**
* Create a new reminder repository instance.
*
* @param \Illuminate\Database\Connection $connection
* @param string $table
* @param string $hashKey
* @param int $expires
* @return void
*/
public function __construct(Connection $connection, $table, $hashKey, $expires = 60)
{
$this->table = $table;
$this->hashKey = $hashKey;
$this->expires = $expires * 60;
$this->connection = $connection;
}
/**
* Create a new reminder record and token.
*
* @param \Illuminate\Auth\RemindableInterface $user
* @return string
*/
public function create(RemindableInterface $user)
{
$email = $user->getReminderEmail();
// We will create a new, random token for the user so that we can e-mail them
// a safe link to the password reset form. Then we will insert a record in
// the database so that we can verify the token within the actual reset.
$token = $this->createNewToken($user);
$this->getTable()->insert($this->getPayload($email, $token));
return $token;
}
/**
* Build the record payload for the table.
*
* @param string $email
* @param string $token
* @return array
*/
protected function getPayload($email, $token)
{
return array('email' => $email, 'token' => $token, 'created_at' => new DateTime);
}
/**
* Determine if a reminder record exists and is valid.
*
* @param \Illuminate\Auth\RemindableInterface $user
* @param string $token
* @return bool
*/
public function exists(RemindableInterface $user, $token)
{
$email = $user->getReminderEmail();
$reminder = $this->getTable()->where('email', $email)->where('token', $token)->first();
return $reminder and ! $this->reminderExpired($reminder);
}
/**
* Determine if the reminder has expired.
*
* @param StdClass $reminder
* @return bool
*/
protected function reminderExpired($reminder)
{
$createdPlusHour = strtotime($reminder->created_at) + $this->expires;
return $createdPlusHour < $this->getCurrentTime();
}
/**
* Get the current UNIX timestamp.
*
* @return int
*/
protected function getCurrentTime()
{
return time();
}
/**
* Delete a reminder record by token.
*
* @param string $token
* @return void
*/
public function delete($token)
{
$this->getTable()->where('token', $token)->delete();
}
/**
* Create a new token for the user.
*
* @param \Illuminate\Auth\RemindableInterface $user
* @return string
*/
public function createNewToken(RemindableInterface $user)
{
$email = $user->getReminderEmail();
$value = str_shuffle(sha1($email.spl_object_hash($this).microtime(true)));
return hash_hmac('sha1', $value, $this->hashKey);
}
/**
* Begin a new database query against the table.
*
* @return \Illuminate\Database\Query\Builder
*/
protected function getTable()
{
return $this->connection->table($this->table);
}
/**
* Get the database connection instance.
*
* @return \Illuminate\Database\Connection
*/
public function getConnection()
{
return $this->connection;
}
}

View File

@@ -0,0 +1,262 @@
<?php namespace Illuminate\Auth\Reminders;
use Closure;
use Illuminate\Mail\Mailer;
use Illuminate\Routing\Redirector;
use Illuminate\Auth\UserProviderInterface;
class PasswordBroker {
/**
* The password reminder repository.
*
* @var \Illuminate\Auth\Reminders\ReminderRepositoryInterface $reminders
*/
protected $reminders;
/**
* The user provider implementation.
*
* @var \Illuminate\Auth\UserProviderInterface
*/
protected $users;
/**
* The redirector instance.
*
* @var \Illuminate\Routing\Redirector
*/
protected $redirector;
/**
* The mailer instance.
*
* @var \Illuminate\Mail\Mailer
*/
protected $mailer;
/**
* The view of the password reminder e-mail.
*
* @var string
*/
protected $reminderView;
/**
* Create a new password broker instance.
*
* @param \Illuminate\Auth\Reminders\ReminderRepositoryInterface $reminders
* @param \Illuminate\Auth\UserProviderInterface $users
* @param \Illuminate\Routing\Redirector $redirect
* @param \Illuminate\Mail\Mailer $mailer
* @param string $reminderView
* @return void
*/
public function __construct(ReminderRepositoryInterface $reminders,
UserProviderInterface $users,
Redirector $redirect,
Mailer $mailer,
$reminderView)
{
$this->users = $users;
$this->mailer = $mailer;
$this->redirect = $redirect;
$this->reminders = $reminders;
$this->reminderView = $reminderView;
}
/**
* Send a password reminder to a user.
*
* @param array $credentials
* @param Closure $callback
* @return \Illuminate\Http\RedirectResponse
*/
public function remind(array $credentials, Closure $callback = null)
{
// First we will check to see if we found a user at the given credentials and
// if we did not we will redirect back to this current URI with a piece of
// "flash" data in the session to indicate to the developers the errors.
$user = $this->getUser($credentials);
if (is_null($user))
{
return $this->makeErrorRedirect('user');
}
// Once we have the reminder token, we are ready to send a message out to the
// user with a link to reset their password. We will then redirect back to
// the current URI having nothing set in the session to indicate errors.
$token = $this->reminders->create($user);
$this->sendReminder($user, $token, $callback);
return $this->redirect->refresh()->with('success', true);
}
/**
* Send the password reminder e-mail.
*
* @param \Illuminate\Auth\Reminders\RemindableInterface $user
* @param string $token
* @param Closure $callback
* @return void
*/
public function sendReminder(RemindableInterface $user, $token, Closure $callback = null)
{
// We will use the reminder view that was given to the broker to display the
// password reminder e-mail. We'll pass a "token" variable into the views
// so that it may be displayed for an user to click for password reset.
$view = $this->reminderView;
return $this->mailer->send($view, compact('token', 'user'), function($m) use ($user, $callback)
{
$m->to($user->getReminderEmail());
if ( ! is_null($callback)) call_user_func($callback, $m, $user);
});
}
/**
* Reset the password for the given token.
*
* @param array $credentials
* @param Closure $callback
* @return mixed
*/
public function reset(array $credentials, Closure $callback)
{
// If the responses from the validate method is not a user instance, we will
// assume that it is a redirect and simply return it from this method and
// the user is properly redirected having an error message on the post.
$user = $this->validateReset($credentials);
if ( ! $user instanceof RemindableInterface)
{
return $user;
}
$pass = $this->getPassword();
// Once we have called this callback, we will remove this token row from the
// table and return the response from this callback so the user gets sent
// to the destination given by the developers from the callback return.
$response = call_user_func($callback, $user, $pass);
$this->reminders->delete($this->getToken());
return $response;
}
/**
* Validate a password reset for the given credentials.
*
* @param array $credenitals
* @return \Illuminate\Auth\RemindableInterface
*/
protected function validateReset(array $credentials)
{
if (is_null($user = $this->getUser($credentials)))
{
return $this->makeErrorRedirect('user');
}
if ( ! $this->validNewPasswords())
{
return $this->makeErrorRedirect('password');
}
if ( ! $this->reminders->exists($user, $this->getToken()))
{
return $this->makeErrorRedirect('token');
}
return $user;
}
/**
* Determine if the passwords match for the request.
*
* @return bool
*/
protected function validNewPasswords()
{
$password = $this->getPassword();
$confirm = $this->getConfirmedPassword();
return $password and strlen($password) >= 6 and $password == $confirm;
}
/**
* Make an error redirect response.
*
* @param string $reason
* @return \Illuminate\Http\RedirectResponse
*/
protected function makeErrorRedirect($reason = '')
{
if ($reason != '') $reason = 'reminders.'.$reason;
return $this->redirect->refresh()->with('error', true)->with('reason', $reason);
}
/**
* Get the user for the given credentials.
*
* @param array $credentials
* @return \Illuminate\Auth\Reminders\RemindableInterface
*/
public function getUser(array $credentials)
{
$user = $this->users->retrieveByCredentials($credentials);
if ($user and ! $user instanceof RemindableInterface)
{
throw new \UnexpectedValueException("User must implement Remindable interface.");
}
return $user;
}
/**
* Get the current request object.
*
* @return \Illuminate\Http\Request
*/
protected function getRequest()
{
return $this->redirect->getUrlGenerator()->getRequest();
}
/**
* Get the reset token for the current request.
*
* @return string
*/
protected function getToken()
{
return $this->getRequest()->input('token');
}
/**
* Get the password for the current request.
*
* @return string
*/
protected function getPassword()
{
return $this->getRequest()->input('password');
}
/**
* Get the confirmed password.
*
* @return string
*/
protected function getConfirmedPassword()
{
return $this->getRequest()->input('password_confirmation');
}
}

View File

@@ -0,0 +1,12 @@
<?php namespace Illuminate\Auth\Reminders;
interface RemindableInterface {
/**
* Get the e-mail address where password reminders are sent.
*
* @return string
*/
public function getReminderEmail();
}

View File

@@ -0,0 +1,30 @@
<?php namespace Illuminate\Auth\Reminders;
interface ReminderRepositoryInterface {
/**
* Create a new reminder record and token.
*
* @param \Illuminate\Auth\RemindableInterface $user
* @return string
*/
public function create(RemindableInterface $user);
/**
* Determine if a reminder record exists and is valid.
*
* @param \Illuminate\Auth\RemindableInterface $user
* @param string $token
* @return bool
*/
public function exists(RemindableInterface $user, $token);
/**
* Delete a reminder record by token.
*
* @param string $token
* @return void
*/
public function delete($token);
}

View File

@@ -0,0 +1,112 @@
<?php namespace Illuminate\Auth\Reminders;
use Illuminate\Support\ServiceProvider;
use Illuminate\Auth\Console\MakeRemindersCommand;
use Illuminate\Auth\Reminders\DatabaseReminderRepository as DbRepository;
class ReminderServiceProvider extends ServiceProvider {
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = true;
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->registerPasswordBroker();
$this->registerReminderRepository();
$this->registerCommands();
}
/**
* Register the password broker instance.
*
* @return void
*/
protected function registerPasswordBroker()
{
$this->app['auth.reminder'] = $this->app->share(function($app)
{
// The reminder repository is responsible for storing the user e-mail addresses
// and password reset tokens. It will be used to verify the tokens are valid
// for the given e-mail addresses. We will resolve an implementation here.
$reminders = $app['auth.reminder.repository'];
$users = $app['auth']->driver()->getProvider();
$view = $app['config']['auth.reminder.email'];
// The password broker uses the reminder repository to validate tokens and send
// reminder e-mails, as well as validating that password reset process as an
// aggregate service of sorts providing a convenient interface for resets.
return new PasswordBroker(
$reminders, $users, $app['redirect'], $app['mailer'], $view
);
});
}
/**
* Register the reminder repository implementation.
*
* @return void
*/
protected function registerReminderRepository()
{
$app = $this->app;
$app['auth.reminder.repository'] = $app->share(function($app)
{
$connection = $app['db']->connection();
// The database reminder repository is an implementation of the reminder repo
// interface, and is responsible for the actual storing of auth tokens and
// their e-mail addresses. We will inject this table and hash key to it.
$table = $app['config']['auth.reminder.table'];
$key = $app['config']['app.key'];
$expire = $app['config']->get('auth.reminder.expire', 60);
return new DbRepository($connection, $table, $key, $expire);
});
}
/**
* Register the auth related console commands.
*
* @return void
*/
protected function registerCommands()
{
$app = $this->app;
$app['command.auth.reminders'] = $app->share(function($app)
{
return new MakeRemindersCommand($app['files']);
});
$this->commands('command.auth.reminders');
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return array('auth.reminder', 'auth.reminder.repository', 'command.auth.reminders');
}
}

View File

@@ -0,0 +1,19 @@
<?php namespace Illuminate\Auth;
interface UserInterface {
/**
* Get the unique identifier for the user.
*
* @return mixed
*/
public function getAuthIdentifier();
/**
* Get the password for the user.
*
* @return string
*/
public function getAuthPassword();
}

View File

@@ -0,0 +1,30 @@
<?php namespace Illuminate\Auth;
interface UserProviderInterface {
/**
* Retrieve a user by their unique identifier.
*
* @param mixed $identifier
* @return \Illuminate\Auth\UserInterface|null
*/
public function retrieveById($identifier);
/**
* Retrieve a user by the given credentials.
*
* @param array $credentials
* @return \Illuminate\Auth\UserInterface|null
*/
public function retrieveByCredentials(array $credentials);
/**
* Validate a user against the given credentials.
*
* @param \Illuminate\Auth\UserInterface $user
* @param array $credentials
* @return bool
*/
public function validateCredentials(UserInterface $user, array $credentials);
}

View File

@@ -0,0 +1,35 @@
{
"name": "illuminate/auth",
"license": "MIT",
"authors": [
{
"name": "Taylor Otwell",
"email": "taylorotwell@gmail.com"
}
],
"require": {
"php": ">=5.3.0",
"illuminate/cookie": "4.0.x",
"illuminate/encryption": "4.0.x",
"illuminate/events": "4.0.x",
"illuminate/hashing": "4.0.x",
"illuminate/http": "4.0.x",
"illuminate/session": "4.0.x",
"illuminate/support": "4.0.x"
},
"require-dev": {
"illuminate/console": "4.0.x",
"illuminate/routing": "4.0.x",
"phpunit/phpunit": "3.7.*"
},
"autoload": {
"psr-0": {"Illuminate\\Auth": ""}
},
"target-dir": "Illuminate/Auth",
"extra": {
"branch-alias": {
"dev-master": "4.0-dev"
}
},
"minimum-stability": "dev"
}