added socialite and some hacks via vendor sideload to add social login
This commit is contained in:
@@ -0,0 +1,3 @@
|
||||
/vendor
|
||||
composer.phar
|
||||
composer.lock
|
||||
@@ -0,0 +1,11 @@
|
||||
language: php
|
||||
|
||||
php:
|
||||
- 5.5
|
||||
- 5.6
|
||||
|
||||
before_script:
|
||||
- curl -s http://getcomposer.org/installer | php
|
||||
- php composer.phar install --dev
|
||||
|
||||
script: phpunit
|
||||
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"name": "adamwathan/eloquent-oauth-l5",
|
||||
"description": "Stupid simple OAuth authentication with Laravel and Eloquent",
|
||||
"authors": [
|
||||
{
|
||||
"name": "Adam Wathan",
|
||||
"email": "adam.wathan@gmail.com"
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"require": {
|
||||
"php": ">=5.5.0",
|
||||
"adamwathan/eloquent-oauth": "~8.1",
|
||||
"guzzlehttp/guzzle": "^6.2.1"
|
||||
},
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"AdamWathan\\EloquentOAuthL5\\": "src/"
|
||||
}
|
||||
},
|
||||
"require-dev": {
|
||||
"phpunit/phpunit": "^4.8"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
<?php
|
||||
|
||||
use App\User;
|
||||
|
||||
return [
|
||||
'model' => User::class,
|
||||
'table' => 'oauth_identities',
|
||||
'providers' => [
|
||||
'facebook' => [
|
||||
'client_id' => '12345678',
|
||||
'client_secret' => 'y0ur53cr374ppk3y',
|
||||
'redirect_uri' => 'https://example.com/your/facebook/redirect',
|
||||
'scope' => [],
|
||||
],
|
||||
'google' => [
|
||||
'client_id' => '12345678',
|
||||
'client_secret' => 'y0ur53cr374ppk3y',
|
||||
'redirect_uri' => 'https://example.com/your/google/redirect',
|
||||
'scope' => [],
|
||||
],
|
||||
'github' => [
|
||||
'client_id' => '12345678',
|
||||
'client_secret' => 'y0ur53cr374ppk3y',
|
||||
'redirect_uri' => 'https://example.com/your/github/redirect',
|
||||
'scope' => [],
|
||||
],
|
||||
'linkedin' => [
|
||||
'client_id' => '12345678',
|
||||
'client_secret' => 'y0ur53cr374ppk3y',
|
||||
'redirect_uri' => 'https://example.com/your/linkedin/redirect',
|
||||
'scope' => [],
|
||||
],
|
||||
'instagram' => [
|
||||
'client_id' => '12345678',
|
||||
'client_secret' => 'y0ur53cr374ppk3y',
|
||||
'redirect_uri' => 'https://example.com/your/instagram/redirect',
|
||||
'scope' => [],
|
||||
],
|
||||
'soundcloud' => [
|
||||
'client_id' => '12345678',
|
||||
'client_secret' => 'y0ur53cr374ppk3y',
|
||||
'redirect_uri' => 'https://example.com/your/soundcloud/redirect',
|
||||
'scope' => [],
|
||||
],
|
||||
],
|
||||
];
|
||||
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
|
||||
class CreateOauthIdentitiesTable extends Migration
|
||||
{
|
||||
public function up()
|
||||
{
|
||||
$tableName = Config::get('eloquent-oauth.table');
|
||||
Schema::create($tableName, function (Blueprint $table) {
|
||||
$table->increments('id');
|
||||
$table->integer('user_id')->unsigned();
|
||||
$table->string('provider_user_id');
|
||||
$table->string('provider');
|
||||
$table->string('access_token');
|
||||
$table->timestamps();
|
||||
});
|
||||
}
|
||||
|
||||
public function down()
|
||||
{
|
||||
$tableName = Config::get('eloquent-oauth.table');
|
||||
Schema::drop($tableName);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<phpunit backupGlobals="false"
|
||||
backupStaticAttributes="false"
|
||||
bootstrap="vendor/autoload.php"
|
||||
colors="true"
|
||||
convertErrorsToExceptions="true"
|
||||
convertNoticesToExceptions="true"
|
||||
convertWarningsToExceptions="true"
|
||||
processIsolation="false"
|
||||
stopOnFailure="false"
|
||||
syntaxCheck="false"
|
||||
>
|
||||
<testsuites>
|
||||
<testsuite name="Package Test Suite">
|
||||
<directory suffix=".php">./tests/</directory>
|
||||
</testsuite>
|
||||
</testsuites>
|
||||
</phpunit>
|
||||
@@ -0,0 +1,263 @@
|
||||
# Eloquent OAuth L5
|
||||
|
||||
> Note: Use the [Laravel 4 package](https://github.com/adamwathan/eloquent-oauth-l4) if you are using Laravel 4.
|
||||
|
||||
Eloquent OAuth is a package for Laravel 5 designed to make authentication against various OAuth providers *ridiculously* brain-dead simple. Specify your client IDs and secrets in a config file, run a migration and after that it's just two method calls and you have OAuth integration.
|
||||
|
||||
#### Video Walkthrough
|
||||
|
||||
[](https://vimeo.com/120085196)
|
||||
|
||||
#### Basic example
|
||||
|
||||
```php
|
||||
// Redirect to Facebook for authorization
|
||||
Route::get('facebook/authorize', function() {
|
||||
return SocialAuth::authorize('facebook');
|
||||
});
|
||||
|
||||
// Facebook redirects here after authorization
|
||||
Route::get('facebook/login', function() {
|
||||
|
||||
// Automatically log in existing users
|
||||
// or create a new user if necessary.
|
||||
SocialAuth::login('facebook');
|
||||
|
||||
// Current user is now available via Auth facade
|
||||
$user = Auth::user();
|
||||
|
||||
return Redirect::intended();
|
||||
});
|
||||
```
|
||||
|
||||
#### Supported Providers
|
||||
|
||||
- Facebook
|
||||
- GitHub
|
||||
- Google
|
||||
- LinkedIn
|
||||
- Instagram
|
||||
- Soundcloud
|
||||
|
||||
>Feel free to open an issue if you would like support for a particular provider, or even better, submit a pull request.
|
||||
|
||||
## Installation
|
||||
|
||||
#### Add this package using Composer
|
||||
|
||||
From the command line inside your project directory, simply type:
|
||||
|
||||
`composer require adamwathan/eloquent-oauth-l5`
|
||||
|
||||
#### Update your config
|
||||
|
||||
Add the service provider to the `providers` array in `config/app.php`:
|
||||
|
||||
```php
|
||||
'providers' => [
|
||||
// ...
|
||||
AdamWathan\EloquentOAuthL5\EloquentOAuthServiceProvider::class,
|
||||
// ...
|
||||
]
|
||||
```
|
||||
|
||||
Add the facade to the `aliases` array in `config/app.php`:
|
||||
|
||||
```php
|
||||
'aliases' => [
|
||||
// ...
|
||||
'SocialAuth' => AdamWathan\EloquentOAuth\Facades\OAuth::class,
|
||||
// ...
|
||||
]
|
||||
```
|
||||
|
||||
#### Publish the package configuration
|
||||
|
||||
Publish the configuration file and migrations by running the provided console command:
|
||||
|
||||
`php artisan eloquent-oauth:install`
|
||||
|
||||
Next, re-migrate your database:
|
||||
|
||||
`php artisan migrate`
|
||||
|
||||
> If you need to change the name of the table used to store OAuth identities, you can do so in the `eloquent-oauth` config file.
|
||||
|
||||
#### Configure the providers
|
||||
|
||||
Update your app information for the providers you are using in `config/eloquent-oauth.php`:
|
||||
|
||||
```php
|
||||
'providers' => [
|
||||
'facebook' => [
|
||||
'client_id' => '12345678',
|
||||
'client_secret' => 'y0ur53cr374ppk3y',
|
||||
'redirect_uri' => 'https://example.com/facebook/login'),
|
||||
'scope' => [],
|
||||
]
|
||||
]
|
||||
```
|
||||
|
||||
> Each provider is preconfigured with the scope necessary to retrieve basic user information and the user's email address, so the scope array can usually be left empty unless you need specific additional permissions. Consult the provider's API documentation to find out what permissions are available for the various services.
|
||||
|
||||
All done!
|
||||
|
||||
> Eloquent OAuth is designed to integrate with Laravel's Eloquent authentication driver, so be sure you are using the `eloquent` driver in `app/config/auth.php`. You can define your actual `User` model however you choose and add whatever behavior you need, just be sure to specify the model you are using with its fully qualified namespace in `app/config/auth.php` as well.
|
||||
|
||||
#### Custom providers
|
||||
|
||||
If you'd like to register a provider for a service that isn't supported out of the box, you can do so by first specifying the configuration needed for that provider in your `config/eloquent-oauth.php`:
|
||||
|
||||
```php
|
||||
// config/eloquent-oauth.php
|
||||
return [
|
||||
'model' => User::class,
|
||||
'table' => 'oauth_identities',
|
||||
'providers' => [
|
||||
'facebook' => [ /* ... */],
|
||||
'google' => [ /* ... */],
|
||||
'gumroad' => [
|
||||
'client_id' => env('GUMROAD_CLIENT_ID'),
|
||||
'client_secret' => env('GUMROAD_CLIENT_SECRET'),
|
||||
'redirect_uri' => env('GUMROAD_REDIRECT_URI'),
|
||||
'scope' => ['view_sales'],
|
||||
],
|
||||
],
|
||||
];
|
||||
```
|
||||
|
||||
Then specify which class should be used for that provider by extending `EloquentOAuthServiceProvider` with your own implementation that maps the provider name to a provider class:
|
||||
|
||||
```php
|
||||
class MySocialAuthServiceProvider extends EloquentOAuthServiceProvider
|
||||
{
|
||||
protected function getProviderLookup()
|
||||
{
|
||||
// Merge the default providers if you like, or override entirely
|
||||
// to skip loading those providers completely.
|
||||
return array_merge($this->providerLookup, [
|
||||
'gumroad' => GumroadProvider::class
|
||||
]);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
> Don't forget to use your extension of the provider in `config/app.php` instead of the one supplied by the package.
|
||||
|
||||
If your provider follows the same `__construct($config, $httpClient, $request)` parameter signature that the default providers use, you're done.
|
||||
|
||||
If not, make sure you bind your provider to the IOC container in another provider, and the package will make sure to fetch the implementation from the container instead of trying to construct it itself.
|
||||
|
||||
To get an idea of how the providers work, take a look at how the packaged providers are implemented:
|
||||
|
||||
- https://github.com/adamwathan/socialnorm-google
|
||||
- https://github.com/adamwathan/socialnorm-github
|
||||
- https://github.com/adamwathan/socialnorm-instagram
|
||||
- https://github.com/adamwathan/socialnorm-soundcloud
|
||||
- https://github.com/adamwathan/socialnorm-facebook
|
||||
- https://github.com/adamwathan/socialnorm-linkedin
|
||||
|
||||
## Usage
|
||||
|
||||
Authentication against an OAuth provider is a multi-step process, but I have tried to simplify it as much as possible.
|
||||
|
||||
### Authorizing with the provider
|
||||
|
||||
First you will need to define the authorization route. This is the route that your "Login" button will point to, and this route redirects the user to the provider's domain to authorize your app. After authorization, the provider will redirect the user back to your second route, which handles the rest of the authentication process.
|
||||
|
||||
To authorize the user, simply return the `SocialAuth::authorize()` method directly from the route.
|
||||
|
||||
```php
|
||||
Route::get('facebook/authorize', function() {
|
||||
return SocialAuth::authorize('facebook');
|
||||
});
|
||||
```
|
||||
|
||||
### Authenticating within your app
|
||||
|
||||
Next you need to define a route for authenticating against your app with the details returned by the provider.
|
||||
|
||||
For basic cases, you can simply call `SocialAuth::login()` with the provider name you are authenticating with. If the user
|
||||
rejected your application, this method will throw an `ApplicationRejectedException` which you can catch and handle
|
||||
as necessary.
|
||||
|
||||
The `login` method will create a new user if necessary, or update an existing user if they have already used your application
|
||||
before.
|
||||
|
||||
Once the `login` method succeeds, the user will be authenticated and available via `Auth::user()` just like if they
|
||||
had logged in through your application normally.
|
||||
|
||||
```php
|
||||
use SocialNorm\Exceptions\ApplicationRejectedException;
|
||||
use SocialNorm\Exceptions\InvalidAuthorizationCodeException;
|
||||
|
||||
Route::get('facebook/login', function() {
|
||||
try {
|
||||
SocialAuth::login('facebook');
|
||||
} catch (ApplicationRejectedException $e) {
|
||||
// User rejected application
|
||||
} catch (InvalidAuthorizationCodeException $e) {
|
||||
// Authorization was attempted with invalid
|
||||
// code,likely forgery attempt
|
||||
}
|
||||
|
||||
// Current user is now available via Auth facade
|
||||
$user = Auth::user();
|
||||
|
||||
return Redirect::intended();
|
||||
});
|
||||
```
|
||||
|
||||
If you need to do anything with the newly created user, you can pass an optional closure as the second
|
||||
argument to the `login` method. This closure will receive the `$user` instance and a `ProviderUserDetails`
|
||||
object that contains basic information from the OAuth provider, including:
|
||||
|
||||
- User ID
|
||||
- Nickname
|
||||
- Full Name
|
||||
- Email
|
||||
- Avatar URL
|
||||
- Access Token
|
||||
|
||||
```php
|
||||
SocialAuth::login('facebook', function($user, $details) {
|
||||
$user->nickname = $details->nickname;
|
||||
$user->name = $details->full_name;
|
||||
$user->profile_image = $details->avatar;
|
||||
$user->save();
|
||||
});
|
||||
```
|
||||
|
||||
> Note: The Instagram and Soundcloud APIs do not allow you to retrieve the user's email address, so unfortunately that field will always be `null` for those providers.
|
||||
|
||||
### Advanced: Storing additional data
|
||||
|
||||
Remember: One of the goals of the Eloquent OAuth package is to normalize the data received across all supported providers, so that you can count on those specific data items (explained above) being available in the `$details` object.
|
||||
|
||||
But, each provider offers its own sets of additional data. If you need to access or store additional data beyond the basics of what Eloquent OAuth's default `ProviderUserDetails` object supplies, you need to do two things:
|
||||
|
||||
1. Request it from the provider, by extending its scope:
|
||||
|
||||
Say for example we want to collect the user's gender when they login using Facebook.
|
||||
|
||||
In the `config/eloquent-oauth.php` file, set the `[scope]` in the `facebook` provider section to include the `public_profile` scope, like this:
|
||||
|
||||
```php
|
||||
'scope' => ['public_profile'],
|
||||
```
|
||||
|
||||
> For available scopes with each provider, consult that provider's API documentation.
|
||||
|
||||
> Note: By increasing the scope you will be asking the user to grant access to additional information. They will be informed of the scopes you're requesting. If you ask for too much unnecessary data, they may refuse. So exercise restraint when requesting additional scopes.
|
||||
|
||||
2. Now where you do your `SocialAuth::login`, store the to your `$user` object by accessing the `$details->raw()['KEY']` data:
|
||||
|
||||
```php
|
||||
SocialAuth::login('facebook', function($user, $details) (
|
||||
$user->gender = $details->raw()['gender'];
|
||||
$user->save();
|
||||
});
|
||||
```
|
||||
|
||||
> Tip: You can see what the available keys are by testing with `dd($details->raw());` inside that same closure.
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
<?php namespace AdamWathan\EloquentOAuthL5;
|
||||
|
||||
use Illuminate\Support\ServiceProvider;
|
||||
use GuzzleHttp\Client as HttpClient;
|
||||
use SocialNorm\SocialNorm;
|
||||
use SocialNorm\ProviderRegistry;
|
||||
use SocialNorm\Request;
|
||||
use SocialNorm\StateGenerator;
|
||||
use AdamWathan\EloquentOAuth\Authenticator;
|
||||
use AdamWathan\EloquentOAuth\EloquentIdentityStore;
|
||||
use AdamWathan\EloquentOAuth\IdentityStore;
|
||||
use AdamWathan\EloquentOAuth\Session;
|
||||
use AdamWathan\EloquentOAuth\OAuthIdentity;
|
||||
use AdamWathan\EloquentOAuth\OAuthManager;
|
||||
use AdamWathan\EloquentOAuth\UserStore;
|
||||
|
||||
class EloquentOAuthServiceProvider extends ServiceProvider {
|
||||
|
||||
protected $providerLookup = [
|
||||
'facebook' => 'SocialNorm\Facebook\FacebookProvider',
|
||||
'github' => 'SocialNorm\GitHub\GitHubProvider',
|
||||
'google' => 'SocialNorm\Google\GoogleProvider',
|
||||
];
|
||||
|
||||
/**
|
||||
* Indicates if loading of the provider is deferred.
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
protected $defer = false;
|
||||
|
||||
/**
|
||||
* Register the service provider.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function register()
|
||||
{
|
||||
// $this->configureOAuthIdentitiesTable();
|
||||
$this->registerIdentityStore();
|
||||
$this->registerOAuthManager();
|
||||
// $this->registerCommands();
|
||||
}
|
||||
|
||||
protected function registerIdentityStore()
|
||||
{
|
||||
$this->app->singleton('AdamWathan\EloquentOAuth\IdentityStore', function ($app) {
|
||||
return new EloquentIdentityStore;
|
||||
});
|
||||
}
|
||||
|
||||
protected function registerOAuthManager()
|
||||
{
|
||||
$this->app->singleton('adamwathan.oauth', function ($app) {
|
||||
$providerRegistry = new ProviderRegistry;
|
||||
$session = new Session($app['session']);
|
||||
$request = new Request($app['request']->all());
|
||||
$stateGenerator = new StateGenerator;
|
||||
|
||||
$socialnorm = new SocialNorm($providerRegistry, $session, $request, $stateGenerator);
|
||||
$this->registerProviders($socialnorm, $request);
|
||||
|
||||
// take user model from the config file
|
||||
$users = new UserStore($app['config']['auth.providers.users.model']);
|
||||
|
||||
$authenticator = new Authenticator(
|
||||
$app['Illuminate\Contracts\Auth\Guard'],
|
||||
$users,
|
||||
$app['AdamWathan\EloquentOAuth\IdentityStore']
|
||||
);
|
||||
|
||||
$oauth = new OAuthManager($app['redirect'], $authenticator, $socialnorm);
|
||||
return $oauth;
|
||||
});
|
||||
}
|
||||
|
||||
protected function registerProviders($socialnorm, $request)
|
||||
{
|
||||
if (! $providerAliases = $this->app['config']['services.oauth_providers']) {
|
||||
return;
|
||||
}
|
||||
|
||||
foreach ($providerAliases as $alias => $config) {
|
||||
if (isset($this->getProviderLookup()[$alias])) {
|
||||
$providerClass = $this->getProviderLookup()[$alias];
|
||||
|
||||
if ($this->app->bound($providerClass)) {
|
||||
$provider = $this->app->make($providerClass);
|
||||
} else {
|
||||
$provider = new $providerClass($config, new HttpClient, $request);
|
||||
}
|
||||
|
||||
$socialnorm->registerProvider($alias, $provider);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected function getProviderLookup()
|
||||
{
|
||||
return $this->providerLookup;
|
||||
}
|
||||
|
||||
// protected function configureOAuthIdentitiesTable()
|
||||
// {
|
||||
// OAuthIdentity::configureTable($this->app['config']['eloquent-oauth.table']);
|
||||
// }
|
||||
|
||||
// /**
|
||||
// * Registers some utility commands with artisan
|
||||
// * @return void
|
||||
// */
|
||||
// public function registerCommands()
|
||||
// {
|
||||
// $this->app->bind('command.eloquent-oauth.install', 'AdamWathan\EloquentOAuthL5\Installation\InstallCommand');
|
||||
// $this->commands('command.eloquent-oauth.install');
|
||||
// }
|
||||
|
||||
/**
|
||||
* Get the services provided by the provider.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function provides()
|
||||
{
|
||||
return ['adamwathan.oauth'];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
<?php namespace AdamWathan\EloquentOAuthL5\Installation;
|
||||
|
||||
use Exception;
|
||||
|
||||
class FileExistsException extends Exception {}
|
||||
@@ -0,0 +1,70 @@
|
||||
<?php namespace AdamWathan\EloquentOAuthL5\Installation;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Filesystem\Filesystem;
|
||||
use Illuminate\Foundation\Composer as Composer51;
|
||||
use Illuminate\Support\Composer as Composer52;
|
||||
use Symfony\Component\Console\Input\InputOption;
|
||||
|
||||
class InstallCommand extends Command
|
||||
{
|
||||
protected $filesystem;
|
||||
protected $composer;
|
||||
protected $name = 'eloquent-oauth:install';
|
||||
protected $description = 'Install package config and migrations';
|
||||
|
||||
public function __construct(Filesystem $filesystem)
|
||||
{
|
||||
parent::__construct();
|
||||
$this->filesystem = $filesystem;
|
||||
|
||||
if (class_exists(Composer52::class)) {
|
||||
$this->composer = app(Composer52::class);
|
||||
} else {
|
||||
$this->composer = app(Composer51::class);
|
||||
}
|
||||
}
|
||||
|
||||
public function handle()
|
||||
{
|
||||
try {
|
||||
$this->publishConfig();
|
||||
$this->publishMigrations();
|
||||
$this->composer->dumpAutoloads();
|
||||
$this->comment('Package configuration and migrations installed!');
|
||||
} catch (FileExistsException $e) {
|
||||
$this->error('It looks like this package has already been installed. Use --force to override.');
|
||||
}
|
||||
}
|
||||
|
||||
public function publishConfig()
|
||||
{
|
||||
$this->publishFile(__DIR__ . '/../../config/eloquent-oauth.php', config_path() . '/eloquent-oauth.php');
|
||||
$this->info('Configuration published.');
|
||||
}
|
||||
|
||||
public function publishMigrations()
|
||||
{
|
||||
$name = 'create_oauth_identities_table';
|
||||
$path = $this->laravel['path.database'] . '/migrations';
|
||||
$fullPath = $this->laravel['migration.creator']->create($name, $path);
|
||||
$this->filesystem->put($fullPath, $this->filesystem->get(__DIR__ . '/../../migrations/create_oauth_identities_table.stub'));
|
||||
}
|
||||
|
||||
public function publishFile($from, $to)
|
||||
{
|
||||
if ($this->filesystem->exists($to) && !$this->option('force')) {
|
||||
throw new FileExistsException;
|
||||
}
|
||||
|
||||
$this->filesystem->copy($from, $to);
|
||||
}
|
||||
|
||||
protected function getOptions()
|
||||
{
|
||||
return [
|
||||
['force', null, InputOption::VALUE_NONE, 'Overwrite any existing files.'],
|
||||
];
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
# To Do
|
||||
- Add tests for individual provider implementations
|
||||
- Probably extract providers into their own packages
|
||||
- Add documentation for creating your own providers
|
||||
- Delete created user and OAuth identity if anything goes wrong that would leave the user in an "unfinished" state after initial creation
|
||||
- Add exception handling for "user creation failed" (unique constraints or just database errors, whatever)
|
||||
- Maybe stop storing access token? Don't actually ever use it again, it's totally single use...
|
||||
- Remove hard dependency on Session\Store, replace with some sort of "CrossRequestPersistanceInterface" or something
|
||||
- Look for more opportunities to add abstractions to different provider implementations. Had to do some crappy stuff with the LinkedIn provider.
|
||||
- Twitter support, going to be interesting...
|
||||
@@ -0,0 +1,3 @@
|
||||
/vendor
|
||||
composer.phar
|
||||
composer.lock
|
||||
@@ -0,0 +1,11 @@
|
||||
language: php
|
||||
|
||||
php:
|
||||
- 5.5
|
||||
- 5.6
|
||||
|
||||
before_script:
|
||||
- curl -s http://getcomposer.org/installer | php
|
||||
- php composer.phar install --dev
|
||||
|
||||
script: phpunit
|
||||
@@ -0,0 +1,39 @@
|
||||
{
|
||||
"name": "adamwathan/eloquent-oauth",
|
||||
"description": "Stupid simple OAuth authentication with Laravel and Eloquent",
|
||||
"authors": [
|
||||
{
|
||||
"name": "Adam Wathan",
|
||||
"email": "adam.wathan@gmail.com"
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"require": {
|
||||
"php": ">=5.5.0",
|
||||
"illuminate/auth": "4.*|5.*",
|
||||
"illuminate/session": "4.*|5.*",
|
||||
"illuminate/database": "4.*|5.*",
|
||||
"illuminate/http": "4.*|5.*",
|
||||
"illuminate/routing": "4.*|5.*",
|
||||
"illuminate/support": "4.*|5.*",
|
||||
"socialnorm/socialnorm": "^0.2",
|
||||
"socialnorm/facebook": "^0.2",
|
||||
"socialnorm/github": "^0.2",
|
||||
"socialnorm/linkedin": "^0.2",
|
||||
"socialnorm/google": "^0.2",
|
||||
"socialnorm/instagram": "^0.2",
|
||||
"socialnorm/soundcloud": "^0.2"
|
||||
},
|
||||
"require-dev": {
|
||||
"mockery/mockery": "~0.9",
|
||||
"phpunit/phpunit": "^4.8"
|
||||
},
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"AdamWathan\\EloquentOAuth\\": "src/"
|
||||
},
|
||||
"classmap": [
|
||||
"tests/FunctionalTestCase.php"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<phpunit backupGlobals="false"
|
||||
backupStaticAttributes="false"
|
||||
bootstrap="vendor/autoload.php"
|
||||
colors="true"
|
||||
convertErrorsToExceptions="true"
|
||||
convertNoticesToExceptions="true"
|
||||
convertWarningsToExceptions="true"
|
||||
processIsolation="false"
|
||||
stopOnFailure="false"
|
||||
syntaxCheck="false"
|
||||
>
|
||||
<testsuites>
|
||||
<testsuite name="Package Test Suite">
|
||||
<directory suffix=".php">./tests/</directory>
|
||||
</testsuite>
|
||||
</testsuites>
|
||||
</phpunit>
|
||||
@@ -0,0 +1,159 @@
|
||||
# Eloquent OAuth
|
||||
|
||||
[](https://codeclimate.com/github/adamwathan/eloquent-oauth)
|
||||
[](https://scrutinizer-ci.com/g/adamwathan/eloquent-oauth/?branch=master)
|
||||
[](https://travis-ci.org/adamwathan/eloquent-oauth)
|
||||
|
||||
> - Use the [Laravel 4 wrapper](https://github.com/adamwathan/eloquent-oauth-l4) for easy integration with Laravel 4.
|
||||
> - Use the [Laravel 5 wrapper](https://github.com/adamwathan/eloquent-oauth-l5) for easy integration with Laravel 5.
|
||||
|
||||
Eloquent OAuth is a package for Laravel designed to make authentication against various OAuth providers *ridiculously* brain-dead simple. Specify your client IDs and secrets in a config file, run a migration and after that it's just two method calls and you have OAuth integration.
|
||||
|
||||
#### Video Walkthrough
|
||||
|
||||
[](https://vimeo.com/120085196)
|
||||
|
||||
#### Basic example
|
||||
|
||||
```php
|
||||
// Redirect to Facebook for authorization
|
||||
Route::get('facebook/authorize', function() {
|
||||
return OAuth::authorize('facebook');
|
||||
});
|
||||
|
||||
// Facebook redirects here after authorization
|
||||
Route::get('facebook/login', function() {
|
||||
|
||||
// Automatically log in existing users
|
||||
// or create a new user if necessary.
|
||||
OAuth::login('facebook');
|
||||
|
||||
// Current user is now available via Auth facade
|
||||
$user = Auth::user();
|
||||
|
||||
return Redirect::intended();
|
||||
});
|
||||
```
|
||||
|
||||
#### Supported Providers
|
||||
|
||||
- Facebook
|
||||
- GitHub
|
||||
- Google
|
||||
- LinkedIn
|
||||
- Instagram
|
||||
- SoundCloud
|
||||
|
||||
>Feel free to open an issue if you would like support for a particular provider, or even better, submit a pull request.
|
||||
|
||||
## Installation
|
||||
|
||||
Check the appropriate wrapper package for installation instructions for your version of Laravel.
|
||||
|
||||
- [Laravel 4 wrapper](https://github.com/adamwathan/eloquent-oauth-l4)
|
||||
- [Laravel 5 wrapper](https://github.com/adamwathan/eloquent-oauth-l5)
|
||||
|
||||
## Usage
|
||||
|
||||
Authentication against an OAuth provider is a multi-step process, but I have tried to simplify it as much as possible.
|
||||
|
||||
### Authorizing with the provider
|
||||
|
||||
First you will need to define the authorization route. This is the route that your "Login" button will point to, and this route redirects the user to the provider's domain to authorize your app. After authorization, the provider will redirect the user back to your second route, which handles the rest of the authentication process.
|
||||
|
||||
To authorize the user, simply return the `OAuth::authorize()` method directly from the route.
|
||||
|
||||
```php
|
||||
Route::get('facebook/authorize', function() {
|
||||
return OAuth::authorize('facebook');
|
||||
});
|
||||
```
|
||||
|
||||
### Authenticating within your app
|
||||
|
||||
Next you need to define a route for authenticating against your app with the details returned by the provider.
|
||||
|
||||
For basic cases, you can simply call `OAuth::login()` with the provider name you are authenticating with. If the user
|
||||
rejected your application, this method will throw an `ApplicationRejectedException` which you can catch and handle
|
||||
as necessary.
|
||||
|
||||
The `login` method will create a new user if necessary, or update an existing user if they have already used your application
|
||||
before.
|
||||
|
||||
Once the `login` method succeeds, the user will be authenticated and available via `Auth::user()` just like if they
|
||||
had logged in through your application normally.
|
||||
|
||||
```php
|
||||
use SocialNorm\Exceptions\ApplicationRejectedException;
|
||||
use SocialNorm\Exceptions\InvalidAuthorizationCodeException;
|
||||
|
||||
Route::get('facebook/login', function() {
|
||||
try {
|
||||
OAuth::login('facebook');
|
||||
} catch (ApplicationRejectedException $e) {
|
||||
// User rejected application
|
||||
} catch (InvalidAuthorizationCodeException $e) {
|
||||
// Authorization was attempted with invalid
|
||||
// code,likely forgery attempt
|
||||
}
|
||||
|
||||
// Current user is now available via Auth facade
|
||||
$user = Auth::user();
|
||||
|
||||
return Redirect::intended();
|
||||
});
|
||||
```
|
||||
|
||||
If you need to do anything with the newly created user, you can pass an optional closure as the second
|
||||
argument to the `login` method. This closure will receive the `$user` instance and a `SocialNorm\User`
|
||||
object that contains basic information from the OAuth provider, including:
|
||||
|
||||
- `id`
|
||||
- `nickname`
|
||||
- `full_name`
|
||||
- `avatar`
|
||||
- `email`
|
||||
- `access_token`
|
||||
|
||||
```php
|
||||
OAuth::login('facebook', function($user, $details) {
|
||||
$user->nickname = $details->nickname;
|
||||
$user->name = $details->full_name;
|
||||
$user->profile_image = $details->avatar;
|
||||
$user->save();
|
||||
});
|
||||
```
|
||||
|
||||
> Note: The Instagram and Soundcloud APIs do not allow you to retrieve the user's email address, so unfortunately that field will always be `null` for those provider.
|
||||
|
||||
### Advanced: Storing additional data
|
||||
|
||||
Remember: One of the goals of the Eloquent OAuth package is to normalize the data received across all supported providers, so that you can count on those specific data items (explained above) being available in the `$details` object.
|
||||
|
||||
But, each provider offers its own sets of additional data. If you need to access or store additional data beyond the basics of what Eloquent OAuth's default `ProviderUserDetails` object supplies, you need to do two things:
|
||||
|
||||
1. Request it from the provider, by extending its scope:
|
||||
|
||||
Say for example we want to collect the user's gender when they login using Facebook.
|
||||
|
||||
In the `config/eloquent-oauth.php` file, set the `[scope]` in the `facebook` provider section to include the `public_profile` scope, like this:
|
||||
|
||||
```php
|
||||
'scope' => ['email', 'public_profile'],
|
||||
```
|
||||
|
||||
> For available scopes with each provider, consult that provider's API documentation.
|
||||
|
||||
> NOTE: By increasing the scope you will be asking the user to grant access to additional information. They will be informed of the scopes you're requesting. If you ask for too much unnecessary data, they may refuse. So exercise restraint when requesting additional scopes.
|
||||
|
||||
2. Now where you do your `OAuth::login`, store the to your `$user` object by accessing the `$details->raw()['KEY']` data:
|
||||
|
||||
```php
|
||||
OAuth::login('facebook', function($user, $details) (
|
||||
$user->gender = $details->raw()['gender']; // Or whatever the key is
|
||||
$user->save();
|
||||
});
|
||||
```
|
||||
|
||||
> TIP: You can see what the available keys are by testing with `dd($details->raw());` inside that same closure.
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
<?php namespace AdamWathan\EloquentOAuth;
|
||||
|
||||
use SocialNorm\User;
|
||||
|
||||
class Authenticator
|
||||
{
|
||||
protected $auth;
|
||||
protected $users;
|
||||
protected $identities;
|
||||
|
||||
public function __construct($auth, $users, $identities)
|
||||
{
|
||||
$this->auth = $auth;
|
||||
$this->users = $users;
|
||||
$this->identities = $identities;
|
||||
}
|
||||
|
||||
public function login($providerAlias, $userDetails, $callback = null)
|
||||
{
|
||||
$user = $this->getUser($providerAlias, $userDetails);
|
||||
$user = $this->runCallback($callback, $user, $userDetails);
|
||||
$this->updateUser($user, $providerAlias, $userDetails);
|
||||
$this->auth->login($user);
|
||||
}
|
||||
|
||||
protected function getUser($providerAlias, \SocialNorm\User $details)
|
||||
{
|
||||
if ($this->identities->userExists($providerAlias, $details)) {
|
||||
return $this->getExistingUser($providerAlias, $details);
|
||||
}
|
||||
|
||||
/** @var \App\Models\User $newuser */
|
||||
$newuser = $this->users->create();
|
||||
$newuser->name = $details->nickname ?: ($details->full_name ?: $details->email);
|
||||
$newuser->email = $details->email;
|
||||
return $newuser;
|
||||
}
|
||||
|
||||
protected function runCallback($callback, $user, $userDetails)
|
||||
{
|
||||
$callback = $callback ?: function () {};
|
||||
$callbackUser = $callback($user, $userDetails);
|
||||
return $callbackUser ?: $user;
|
||||
}
|
||||
|
||||
protected function updateUser($user, $providerAlias, $details)
|
||||
{
|
||||
$this->users->store($user);
|
||||
$this->storeProviderIdentity($user, $providerAlias, $details);
|
||||
}
|
||||
|
||||
protected function getExistingUser($providerAlias, $details)
|
||||
{
|
||||
$identity = $this->identities->getByProvider($providerAlias, $details);
|
||||
return $this->users->findByIdentity($identity);
|
||||
}
|
||||
|
||||
protected function storeProviderIdentity($user, $providerAlias, $details)
|
||||
{
|
||||
if ($this->identities->userExists($providerAlias, $details)) {
|
||||
$this->updateProviderIdentity($providerAlias, $details);
|
||||
} else {
|
||||
$this->addProviderIdentity($user, $providerAlias, $details);
|
||||
}
|
||||
}
|
||||
|
||||
protected function updateProviderIdentity($providerAlias, $details)
|
||||
{
|
||||
$identity = $this->identities->getByProvider($providerAlias, $details);
|
||||
$identity->access_token = $details->access_token;
|
||||
$this->identities->store($identity);
|
||||
}
|
||||
|
||||
protected function addProviderIdentity($user, $providerAlias, $details)
|
||||
{
|
||||
$identity = new OAuthIdentity;
|
||||
$identity->user_id = $user->getKey();
|
||||
$identity->provider = $providerAlias;
|
||||
$identity->provider_user_id = $details->id;
|
||||
$identity->access_token = $details->access_token;
|
||||
$this->identities->store($identity);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php namespace AdamWathan\EloquentOAuth;
|
||||
|
||||
class EloquentIdentityStore implements IdentityStore
|
||||
{
|
||||
public function getByProvider($provider, $providerUser)
|
||||
{
|
||||
return OAuthIdentity::where('provider', $provider)
|
||||
->where('provider_user_id', $providerUser->id)
|
||||
->first();
|
||||
}
|
||||
|
||||
public function flush($user, $provider)
|
||||
{
|
||||
OAuthIdentity::where('user_id', $user->getKey())
|
||||
->where('provider', $provider)
|
||||
->delete();
|
||||
}
|
||||
|
||||
public function store($identity)
|
||||
{
|
||||
$identity->save();
|
||||
}
|
||||
|
||||
public function userExists($provider, $providerUser)
|
||||
{
|
||||
return (bool) $this->getByProvider($provider, $providerUser);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
<?php namespace AdamWathan\EloquentOAuth\Facades;
|
||||
|
||||
use Illuminate\Support\Facades\Facade;
|
||||
|
||||
class OAuth extends Facade
|
||||
{
|
||||
protected static function getFacadeAccessor()
|
||||
{
|
||||
return 'adamwathan.oauth';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
<?php namespace AdamWathan\EloquentOAuth;
|
||||
|
||||
interface IdentityStore
|
||||
{
|
||||
public function getByProvider($provider, $providerUser);
|
||||
public function flush($user, $provider);
|
||||
public function store($identity);
|
||||
public function userExists($provider, $providerUser);
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
<?php namespace AdamWathan\EloquentOAuth;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model as Eloquent;
|
||||
use Config;
|
||||
|
||||
/**
|
||||
* @property $id
|
||||
* @property $user_id
|
||||
* @property $provider
|
||||
* @property $provider_user_id
|
||||
* @property $access_token
|
||||
*/
|
||||
class OAuthIdentity extends Eloquent
|
||||
{
|
||||
protected static $configuredTable = 'oauth_identities';
|
||||
|
||||
// public static function configureTable($table)
|
||||
// {
|
||||
// static::$configuredTable = $table;
|
||||
// }
|
||||
|
||||
public function getTable()
|
||||
{
|
||||
return static::$configuredTable;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
<?php namespace AdamWathan\EloquentOAuth;
|
||||
|
||||
use SocialNorm\SocialNorm;
|
||||
|
||||
class OAuthManager
|
||||
{
|
||||
/** @var string */
|
||||
protected $redirect;
|
||||
|
||||
/** @var Authenticator */
|
||||
protected $authenticator;
|
||||
|
||||
/** @var SocialNorm */
|
||||
protected $socialnorm;
|
||||
|
||||
public function __construct($redirect, $authenticator, $socialnorm)
|
||||
{
|
||||
$this->redirect = $redirect;
|
||||
$this->authenticator = $authenticator;
|
||||
$this->socialnorm = $socialnorm;
|
||||
}
|
||||
|
||||
public function authorize($providerAlias)
|
||||
{
|
||||
return $this->redirect->to($this->socialnorm->authorize($providerAlias));
|
||||
}
|
||||
|
||||
public function login($providerAlias, $callback = null)
|
||||
{
|
||||
$details = $this->socialnorm->getUser($providerAlias);
|
||||
return $this->authenticator->login($providerAlias, $details, $callback);
|
||||
}
|
||||
|
||||
public function registerProvider($alias, $provider)
|
||||
{
|
||||
$this->socialnorm->registerProvider($alias, $provider);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php namespace AdamWathan\EloquentOAuth;
|
||||
|
||||
use SocialNorm\Session as SocialNormSession;
|
||||
|
||||
class Session implements SocialNormSession
|
||||
{
|
||||
private $store;
|
||||
|
||||
public function __construct($store)
|
||||
{
|
||||
$this->store = $store;
|
||||
}
|
||||
|
||||
public function get($key)
|
||||
{
|
||||
return $this->store->get($key);
|
||||
}
|
||||
|
||||
public function put($key, $value)
|
||||
{
|
||||
return $this->store->put($key, $value);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
<?php namespace AdamWathan\EloquentOAuth;
|
||||
|
||||
class UserStore
|
||||
{
|
||||
protected $model;
|
||||
|
||||
public function __construct($model)
|
||||
{
|
||||
$this->model = $model;
|
||||
}
|
||||
|
||||
public function create()
|
||||
{
|
||||
$user = new $this->model;
|
||||
return $user;
|
||||
}
|
||||
|
||||
public function store($user)
|
||||
{
|
||||
return $user->save();
|
||||
}
|
||||
|
||||
public function findByIdentity($identity)
|
||||
{
|
||||
return $identity->belongsTo($this->model, 'user_id')->firstOrFail();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
<?php
|
||||
|
||||
use Mockery as M;
|
||||
use AdamWathan\EloquentOAuth\Authenticator;
|
||||
use AdamWathan\EloquentOAuth\OAuthIdentity;
|
||||
use SocialNorm\User as SocialNormUser;
|
||||
|
||||
class AuthenticatorTest extends PHPUnit_Framework_TestCase
|
||||
{
|
||||
public function tearDown()
|
||||
{
|
||||
M::close();
|
||||
}
|
||||
|
||||
public function test_login_creates_new_user_if_no_matching_user_exists()
|
||||
{
|
||||
$providerAlias = 'provider';
|
||||
$auth = M::spy();
|
||||
$users = M::spy();
|
||||
$identities = M::spy();
|
||||
$userDetails = new SocialNormUser([]);
|
||||
$user = M::mock('Illuminate\Contracts\Auth\Authenticatable')->shouldIgnoreMissing();
|
||||
|
||||
$identities->shouldReceive('userExists')->andReturn(false);
|
||||
$users->shouldReceive('create')->andReturn($user);
|
||||
|
||||
$authenticator = new Authenticator($auth, $users, $identities);
|
||||
$authenticator->login('provider', $userDetails);
|
||||
|
||||
$users->shouldHaveReceived('create');
|
||||
$users->shouldHaveReceived('store')->with($user);
|
||||
$identities->shouldHaveReceived('store');
|
||||
$auth->shouldHaveReceived('login')->with($user);
|
||||
}
|
||||
|
||||
public function test_login_uses_existing_user_if_matching_user_exists()
|
||||
{
|
||||
$providerAlias = 'provider';
|
||||
|
||||
$userDetails = new SocialNormUser([]);
|
||||
$user = M::mock('Illuminate\Contracts\Auth\Authenticatable')->shouldIgnoreMissing();
|
||||
|
||||
$auth = M::spy();
|
||||
|
||||
$users = M::spy([
|
||||
'findByIdentity' => $user
|
||||
]);
|
||||
|
||||
$identities = M::spy([
|
||||
'userExists' => true,
|
||||
'getByProvider' => new OAuthIdentity,
|
||||
]);
|
||||
|
||||
$authenticator = new Authenticator($auth, $users, $identities);
|
||||
$authenticator->login('provider', $userDetails);
|
||||
|
||||
$users->shouldNotHaveReceived('create');
|
||||
$users->shouldHaveReceived('store')->with($user);
|
||||
$identities->shouldHaveReceived('store');
|
||||
$auth->shouldHaveReceived('login')->with($user);
|
||||
}
|
||||
|
||||
public function test_if_a_user_is_returned_from_the_callback_that_user_is_used()
|
||||
{
|
||||
$providerAlias = 'provider';
|
||||
|
||||
$userDetails = new SocialNormUser([]);
|
||||
$user = M::mock('Illuminate\Contracts\Auth\Authenticatable')->shouldIgnoreMissing();
|
||||
$otherUser = M::mock('Illuminate\Contracts\Auth\Authenticatable')->shouldIgnoreMissing();
|
||||
|
||||
$auth = M::spy();
|
||||
|
||||
$users = M::spy([
|
||||
'findByIdentity' => $user
|
||||
]);
|
||||
|
||||
$identities = M::spy([
|
||||
'userExists' => true,
|
||||
'getByProvider' => new OAuthIdentity,
|
||||
]);
|
||||
|
||||
$authenticator = new Authenticator($auth, $users, $identities);
|
||||
$authenticator->login('provider', $userDetails, function () use ($otherUser) {
|
||||
return $otherUser;
|
||||
});
|
||||
|
||||
$users->shouldNotHaveReceived('create');
|
||||
$users->shouldHaveReceived('store')->with($otherUser);
|
||||
$identities->shouldHaveReceived('store');
|
||||
$auth->shouldHaveReceived('login')->with($otherUser);
|
||||
}
|
||||
|
||||
public function test_if_nothing_is_returned_from_the_callback_the_found_or_created_user_is_used()
|
||||
{
|
||||
$providerAlias = 'provider';
|
||||
|
||||
$userDetails = new SocialNormUser([]);
|
||||
$foundUser = M::mock('Illuminate\Contracts\Auth\Authenticatable')->shouldIgnoreMissing();
|
||||
$otherUser = M::mock('Illuminate\Contracts\Auth\Authenticatable')->shouldIgnoreMissing();
|
||||
|
||||
$auth = M::spy();
|
||||
|
||||
$users = M::spy([
|
||||
'findByIdentity' => $foundUser
|
||||
]);
|
||||
|
||||
$identities = M::spy([
|
||||
'userExists' => true,
|
||||
'getByProvider' => new OAuthIdentity,
|
||||
]);
|
||||
|
||||
$authenticator = new Authenticator($auth, $users, $identities);
|
||||
$authenticator->login('provider', $userDetails, function () {
|
||||
return;
|
||||
});
|
||||
|
||||
$users->shouldNotHaveReceived('create');
|
||||
$users->shouldHaveReceived('store')->with($foundUser);
|
||||
$identities->shouldHaveReceived('store');
|
||||
$auth->shouldHaveReceived('login')->with($foundUser);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Capsule\Manager as DB;
|
||||
|
||||
abstract class FunctionalTestCase extends PHPUnit_Framework_TestCase
|
||||
{
|
||||
public function setUp()
|
||||
{
|
||||
$this->configureDatabase();
|
||||
$this->migrateIdentitiesTable();
|
||||
}
|
||||
|
||||
protected function configureDatabase()
|
||||
{
|
||||
$db = new DB;
|
||||
$db->addConnection(array(
|
||||
'driver' => 'sqlite',
|
||||
'database' => ':memory:',
|
||||
'charset' => 'utf8',
|
||||
'collation' => 'utf8_unicode_ci',
|
||||
'prefix' => '',
|
||||
));
|
||||
$db->bootEloquent();
|
||||
$db->setAsGlobal();
|
||||
}
|
||||
|
||||
public function migrateIdentitiesTable()
|
||||
{
|
||||
DB::schema()->create('oauth_identities', function($table) {
|
||||
$table->increments('id');
|
||||
$table->integer('user_id')->unsigned();
|
||||
$table->string('provider_user_id');
|
||||
$table->string('provider');
|
||||
$table->string('access_token');
|
||||
$table->timestamps();
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
<?php
|
||||
|
||||
use AdamWathan\EloquentOAuth\OAuthIdentity;
|
||||
use AdamWathan\EloquentOAuth\EloquentIdentityStore;
|
||||
use Illuminate\Database\Eloquent\Model as Eloquent;
|
||||
use Mockery as M;
|
||||
use SocialNorm\User as UserDetails;
|
||||
|
||||
class IdentityStoreTest extends FunctionalTestCase
|
||||
{
|
||||
public function setUp()
|
||||
{
|
||||
parent::setUp();
|
||||
Eloquent::unguard();
|
||||
}
|
||||
|
||||
public function test_get_by_provider()
|
||||
{
|
||||
OAuthIdentity::create(array(
|
||||
'user_id' => 1,
|
||||
'provider' => 'facebook',
|
||||
'provider_user_id' => 'foobar',
|
||||
'access_token' => 'abc123',
|
||||
));
|
||||
OAuthIdentity::create(array(
|
||||
'user_id' => 2,
|
||||
'provider' => 'facebook',
|
||||
'provider_user_id' => 'bazfoo',
|
||||
'access_token' => 'def456',
|
||||
));
|
||||
$details = new UserDetails(array(
|
||||
'access_token' => 'new-token',
|
||||
'id' => 'bazfoo',
|
||||
'nickname' => 'john.doe',
|
||||
'full_name' => 'John Doe',
|
||||
'email' => 'john.doe@example.com',
|
||||
'avatar' => 'http://example.com/photos/john_doe.jpg',
|
||||
));
|
||||
$identities = new EloquentIdentityStore;
|
||||
$identity = $identities->getByProvider('facebook', $details);
|
||||
$this->assertEquals(2, $identity->user_id);
|
||||
$this->assertEquals('facebook', $identity->provider);
|
||||
$this->assertEquals('bazfoo', $identity->provider_user_id);
|
||||
$this->assertEquals('def456', $identity->access_token);
|
||||
}
|
||||
|
||||
public function test_get_by_provider_when_no_match()
|
||||
{
|
||||
OAuthIdentity::create(array(
|
||||
'user_id' => 1,
|
||||
'provider' => 'facebook',
|
||||
'provider_user_id' => 'foobar',
|
||||
'access_token' => 'abc123',
|
||||
));
|
||||
OAuthIdentity::create(array(
|
||||
'user_id' => 2,
|
||||
'provider' => 'facebook',
|
||||
'provider_user_id' => 'bazfoo',
|
||||
'access_token' => 'def456',
|
||||
));
|
||||
$details = new UserDetails(array(
|
||||
'access_token' => 'new-token',
|
||||
'id' => 'missing-id',
|
||||
'nickname' => 'john.doe',
|
||||
'full_name' => 'John Doe',
|
||||
'email' => 'john.doe@example.com',
|
||||
'avatar' => 'http://example.com/photos/john_doe.jpg',
|
||||
));
|
||||
$identities = new EloquentIdentityStore;
|
||||
$identity = $identities->getByProvider('facebook', $details);
|
||||
$this->assertNull($identity);
|
||||
}
|
||||
|
||||
public function test_flush()
|
||||
{
|
||||
OAuthIdentity::create(array(
|
||||
'user_id' => 1,
|
||||
'provider' => 'facebook',
|
||||
'provider_user_id' => 'foobar',
|
||||
'access_token' => 'abc123',
|
||||
));
|
||||
OAuthIdentity::create(array(
|
||||
'user_id' => 2,
|
||||
'provider' => 'facebook',
|
||||
'provider_user_id' => 'bazfoo',
|
||||
'access_token' => 'def456',
|
||||
));
|
||||
|
||||
$this->assertEquals(1, OAuthIdentity::where('provider', 'facebook')->where('user_id', 2)->count());
|
||||
|
||||
$identities = new EloquentIdentityStore;
|
||||
$user = M::mock();
|
||||
$user->shouldReceive('getKey')->andReturn(2);
|
||||
$identities->flush($user, 'facebook');
|
||||
|
||||
$this->assertEquals(0, OAuthIdentity::where('provider', 'facebook')->where('user_id', 2)->count());
|
||||
}
|
||||
|
||||
public function test_store()
|
||||
{
|
||||
$identity = new OAuthIdentity(array(
|
||||
'user_id' => 1,
|
||||
'provider' => 'facebook',
|
||||
'provider_user_id' => 'foobar',
|
||||
'access_token' => 'abc123',
|
||||
));
|
||||
|
||||
$this->assertEquals(0, OAuthIdentity::count());
|
||||
|
||||
$identities = new EloquentIdentityStore;
|
||||
$identities->store($identity);
|
||||
|
||||
$this->assertEquals(1, OAuthIdentity::count());
|
||||
}
|
||||
|
||||
public function test_user_exists_returns_true_when_user_exists()
|
||||
{
|
||||
OAuthIdentity::create(array(
|
||||
'user_id' => 2,
|
||||
'provider' => 'facebook',
|
||||
'provider_user_id' => 'bazfoo',
|
||||
'access_token' => 'def456',
|
||||
));
|
||||
$details = new UserDetails(array(
|
||||
'access_token' => 'new-token',
|
||||
'id' => 'bazfoo',
|
||||
'nickname' => 'john.doe',
|
||||
'full_name' => 'John Doe',
|
||||
'email' => 'john.doe@example.com',
|
||||
'avatar' => 'http://example.com/photos/john_doe.jpg',
|
||||
));
|
||||
$identities = new EloquentIdentityStore;
|
||||
$this->assertTrue($identities->userExists('facebook', $details));
|
||||
}
|
||||
|
||||
public function test_user_exists_returns_false_when_user_doesnt_exist()
|
||||
{
|
||||
OAuthIdentity::create(array(
|
||||
'user_id' => 2,
|
||||
'provider' => 'facebook',
|
||||
'provider_user_id' => 'foobar',
|
||||
'access_token' => 'def456',
|
||||
));
|
||||
$details = new UserDetails(array(
|
||||
'access_token' => 'new-token',
|
||||
'id' => 'bazfoo',
|
||||
'nickname' => 'john.doe',
|
||||
'full_name' => 'John Doe',
|
||||
'email' => 'john.doe@example.com',
|
||||
'avatar' => 'http://example.com/photos/john_doe.jpg',
|
||||
));
|
||||
$identities = new EloquentIdentityStore;
|
||||
$this->assertFalse($identities->userExists('facebook', $details));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
<?php
|
||||
|
||||
use Mockery as M;
|
||||
use AdamWathan\EloquentOAuth\OAuthManager;
|
||||
use Illuminate\Routing\Redirector;
|
||||
use Illuminate\Routing\UrlGenerator;
|
||||
use Illuminate\Routing\RouteCollection;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class OAuthManagerTest extends PHPUnit_Framework_TestCase
|
||||
{
|
||||
public function tearDown()
|
||||
{
|
||||
M::close();
|
||||
}
|
||||
|
||||
public function test_it_returns_a_redirect_to_the_authorize_url()
|
||||
{
|
||||
$redirector = $this->buildRedirector();
|
||||
$authenticator = M::mock('AdamWathan\EloquentOAuth\Authenticator');
|
||||
$socialnorm = M::mock('SocialNorm\SocialNorm');
|
||||
$socialnorm->shouldReceive('authorize')->with('example')->andReturn('http://example.com/authorize');
|
||||
|
||||
$oauth = new OAuthManager($redirector, $authenticator, $socialnorm);
|
||||
$response = $oauth->authorize('example');
|
||||
$this->assertEquals('http://example.com/authorize', $response->getTargetUrl());
|
||||
}
|
||||
|
||||
public function test_it_logs_the_user_in()
|
||||
{
|
||||
$providerAlias = 'twitbook';
|
||||
$socialnormUser = new SocialNorm\User([]);
|
||||
$callback = function () {};
|
||||
|
||||
$redirector = $this->buildRedirector();
|
||||
|
||||
$authenticator = M::spy('AdamWathan\EloquentOAuth\Authenticator');
|
||||
|
||||
$socialnorm = M::mock('SocialNorm\SocialNorm');
|
||||
$socialnorm->shouldReceive('getUser')
|
||||
->with($providerAlias)
|
||||
->andReturn($socialnormUser);
|
||||
|
||||
$oauth = new OAuthManager($redirector, $authenticator, $socialnorm);
|
||||
$oauth->login($providerAlias, $callback);
|
||||
|
||||
$authenticator->shouldHaveReceived('login')->with($providerAlias, $socialnormUser, $callback);
|
||||
}
|
||||
|
||||
private function buildRedirector()
|
||||
{
|
||||
return new Redirector(new UrlGenerator(new RouteCollection, new Request));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
# To Do
|
||||
- Add tests for individual provider implementations
|
||||
- Probably extract providers into their own packages
|
||||
- Add documentation for creating your own providers
|
||||
- Delete created user and OAuth identity if anything goes wrong that would leave the user in an "unfinished" state after initial creation
|
||||
- Add exception handling for "user creation failed" (unique constraints or just database errors, whatever)
|
||||
- Maybe stop storing access token? Don't actually ever use it again, it's totally single use...
|
||||
- Remove hard dependency on Session\Store, replace with some sort of "CrossRequestPersistanceInterface" or something
|
||||
- Look for more opportunities to add abstractions to different provider implementations. Had to do some crappy stuff with the LinkedIn provider.
|
||||
- Twitter support, going to be interesting...
|
||||
Reference in New Issue
Block a user