Giter VIP home page Giter VIP logo

laravel-social-auth's Introduction

Stand With Ukraine

Social Authentication

Latest Version on Packagist Software License Build Status Code Style Quality Score Total Downloads

This package give ability to

  • Sign In
  • Sign Up
  • Attach/Detach social network provider to an existing account

This package based on laravel/socialite and provide an easy ability of usage a lot of additional providers from Socialite Providers.

Install

Via Composer:

$ composer require mad-web/laravel-social-auth

and add the service provider in config/app.php file:

'providers' => [
    // ...
    MadWeb\SocialAuth\SocialAuthServiceProvider::class,
];

Next, publish the migration with:

$ php artisan vendor:publish --provider="MadWeb\SocialAuth\SocialAuthServiceProvider" --tag="migrations"

The package assumes that your users table name is called "users". If this is not the case you should manually edit the published migration to use your custom table name.

After the migration has been published you can create the social_providers table for storing supported providers and user_has_social_provider pivot table for attaching providers to users by running migrations:

$ php artisan migrate

You can publish the config file with:

$ php artisan vendor:publish --provider="MadWeb\SocialAuth\SocialAuthServiceProvider" --tag="config"

This is the contents of the published config/social-auth.php config file:

return [

    /*
    |--------------------------------------------------------------------------
    | Additional service providers
    |--------------------------------------------------------------------------
    |
    | The social providers listed here will enable support for additional social
    | providers which provided by https://socialiteproviders.github.io/ just
    | add new event listener from the installation guide
    |
    */
    'providers' => [
        //
    ],

    'models' => [
        /*
         * When using the "UserSocialite" trait from this package, we need to know which
         * Eloquent model should be used to retrieve your available social providers. Of course, it
         * is often just the "SocialProvider" model but you may use whatever you like.
         */
        'social' => \MadWeb\SocialAuth\Models\SocialProvider::class,

        /*
         * User model which you will use as "SocialAuthenticatable"
         */
        'user' => \App\User::class,
    ],

    'table_names' => [

       /*
       |--------------------------------------------------------------------------
       | Users Table
       |--------------------------------------------------------------------------
       |
       | The table for storing relation between users and social providers. Also there is
       | a place for saving "user social network id", "token", "expiresIn" if it exist
       |
       */
        'user_has_social_provider' => 'user_has_social_provider',

        /*
        |--------------------------------------------------------------------------
        | Social Providers Table
        |--------------------------------------------------------------------------
        |
        | The table that contains all social network providers which your application use.
        |
        */
        'social_providers' => 'social_providers'
    ],

    'foreign_keys' => [

        /*
         * The name of the foreign key to the users table.
         */
        'users' => 'user_id',

        /*
         * The name of the foreign key to the socials table
         */
        'socials' => 'social_id'
    ],

    /*
    |--------------------------------------------------------------------------
    | Authentication redirection
    |--------------------------------------------------------------------------
    |
    | Redirect path after success/error login via social network
    |
    */
    'redirect' => '/home'
];

Or you can publish and modify view templates with:

$ php artisan vendor:publish --provider="MadWeb\SocialAuth\SocialAuthServiceProvider" --tag="views"

Also you can publish and modify translation file:

$ php artisan vendor:publish --provider="MadWeb\SocialAuth\SocialAuthServiceProvider" --tag="lang"
Add credetials to your project

Add providers to config/services.php:

'facebook' => [
    'client_id' => env('FB_ID'),
    'client_secret' => env('FB_SECRET'),
    'redirect' => env('FB_REDIRECT'),
],

'google' => [
    'client_id' => env('GOOGLE_ID'),
    'client_secret' => env('GOOGLE_SECRET'),
    'redirect' => env('GOOGLE_REDIRECT'),
],

'github' => [
    'client_id' => env('GITHUB_ID'),
    'client_secret' => env('GITHUB_SECRET'),
    'redirect' => env('GITHUB_REDIRECT'),
]

Add credantials to .env:

FB_ID=
FB_SECRET=
FB_REDIRECT=https://app.domain/social/facebook/callback

GOOGLE_ID=
GOOGLE_SECRET=
GOOGLE_REDIRECT=https://app.domain/social/google/callback

GITHUB_ID=
GITHUB_SECRET=
GITHUB_REDIRECT=https://app.domain/social/github/callback

After that, create your social providers in the database.

Using console command:

php artisan social-auth:add google --label=Google+

By model, for example in seeder:

SocialProvider::create(['slug' => 'google', 'label' => 'Google+']);

Or add records directly.

You can add additional scopes and parameters to the social auth request:

SocialProvider::create([
    'label' => 'github',
    'slug' => 'Github',
    'scopes' => ['foo', 'bar'],
    'parameters' => ['foo' => 'bar']
]);

To override default scopes:

$SocialProvider->setScopes(['foo', 'bar'], true);
Include social buttons into your templates
 @include('social-auth::attach') // for authenticated user to attach/detach another socials
 @include('social-auth::buttons') // for guests to login via
Prepare your user model

Implement SocialAuthenticatable interface and add UserSocialite trait to your User model:

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use MadWeb\SocialAuth\Traits\UserSocialite;
use MadWeb\SocialAuth\Contracts\SocialAuthenticatable;

class User extends Model implements SocialAuthenticatable
{
    use UserSocialite;
   ...
}

Additional Providers

To use any of additional providers from socialiteproviders.netlify.com, at first install it:

composer require socialiteproviders/instagram

next, add an event listener from guide to the social-auth config file:

/*
|--------------------------------------------------------------------------
| Additional service providers
|--------------------------------------------------------------------------
|
| The social providers listed here will enable support for additional social
| providers which provided by https://socialiteproviders.netlify.com just
| add new event listener from the installation guide
|
*/
'providers' => [
    SocialiteProviders\Instagram\InstagramExtendSocialite::class,
],
...

Customization

Routes

If you need do some custom with social flow, you should define yourself controllers and put your custom url into routes file.

For example:

Route::get('social/{social}', 'Auth\SocialAuthController@getAccount');
Route::get('social/{social}/callback', 'Auth\SocialAuthController@callback');
Route::get('social/{social}/detach', 'Auth\SocialAuthController@detachAccount');

In case if you no need any special functionality ypu can use our default controllers.

Custom User Model

User model we takes from the social-auth.models.user.

User Properties Mapping

SocialAuthenticatable interface contains method mapSocialData for mapping social fields for user model. If you need customize a data mapping, you can override this method for your preferences project in the User model.

Default mapping method:

public function mapSocialData(User $socialUser)
{
    $raw = $socialUser->getRaw();
    $name = $socialUser->getName() ?? $socialUser->getNickname();
    $name = $name ?? $socialUser->getEmail();

    $result = [
        $this->getEmailField() => $socialUser->getEmail(),
        'name' => $name,
        'verified' => $raw['verified'] ?? true,
        'avatar' => $socialUser->getAvatar(),
    ];

    return $result;
}

Change log

Please see CHANGELOG for more information on what has changed recently.

Testing

$ composer test

Contributing

Please see CONTRIBUTING and CONDUCT for details.

Security

If you discover any security related issues, please email [email protected] instead of using the issue tracker.

Credits

License

The MIT License (MIT). Please see License File for more information.

laravel-social-auth's People

Contributors

serhiistarovoitov avatar slavarazum avatar thewebartisan7 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

laravel-social-auth's Issues

Attach does no record data in user_has_accounts table

When including @include('attach') i am getting buttons displayed. However, when i click on to attach, nothing happens.
user_has_profiles table is empty
i am catching script fetching user profile from social in LoginController@callback which is a path for the Laravel socialite Social logins.

Package does not login

Detailed description

After I log in to Google, I get redirected back to the site without logging in. I see that the entry is made in the table. I use multiple auth guards. Could you explain me how to implement that?

Token stored without encryption

Detailed description

The token is stored on database without encryption. It's not good for security, since it can be considered as a password, because these tokens give access to privileged information about your users.

Also default laravel socialite table has not even this field for the same reason, because for only oauth authentication it's not even so required if you don't use it. You could use it for like a remember me storing it (encrypted always) in session and then check in database if match, and check also expires and in case ask new one via refresh token.

But then you must also ask users if they want to remember their authentication.

I think would be better to remove or encrypt.

What do you think?

Default value missing for email and password

Detailed description

It's really great package, I like it. However, there is nothing in migration regarding change of password field and email to make them nullable, or an additional step to ask users to fill this data when is not provided. For example Twitter doesn't provide email address, so you get an error when connect with Twitter, this:

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'email' cannot be null (SQL: insert into users (email, name, updated_at, created_at) values (?, thewebartisan7, 2019-12-19 10:00:16, 2019-12-19 10:00:16))

And for all providers you get this:

SQLSTATE[HY000]: General error: 1364 Field 'password' doesn't have a default value (SQL: insert into users (email, name, updated_at, created_at) values ([email protected], The Web Artisan, 2019-12-19 09:57:32, 2019-12-19 09:57:32))

Would be good to add an additional step before create user account, a form where end-users can see the data that will be imported (this mapped data), so users can also edit this data, and add missing one, like set password and email.

Possible implementation

I have already do this in my current project that use only Socialite, but I would like to start using this package. If you are interested, I can make a pull request.

After callback, if user is first time registering, I store provider name, token and if exist the secret in session, encrypted, in this way:

                // Store the token encrypted in session
                // so we can retrieve socialUser data in next step
                session([
                    'provider'  => encrypt($provider),
                    'token'     => encrypt($socialUser->token)
                ]);

                if(! empty($socialUser->tokenSecret)) {
                    session([
                        'tokenSecret' => encrypt($socialUser->tokenSecret)
                    ]);
                }
                // Load second step registration form where user see all additional mapped data
                return view('auth.register-after', compact('user'));

Then in the method where the second step registration form is submitted I retrieve provider, token and if exist the secret for retrieve user social data, and delete from session, code:

            // Get submitted data from form request
            $userData = $request->validated();

            // Retrieve and delete from session the provider and token
            $provider = decrypt(session()->pull('provider'));
            $token = decrypt(session()->pull('token'));

            // Get socialUser by provider and token / secret
            if($request->session()->exists('tokenSecret')) {
                $socialUser = $this->socialiteService->connectByTokenAndSecret(
                    $provider, $token, decrypt(session()->pull('tokenSecret'))
                );
            }
            else {
                $socialUser = $this->socialiteService->connectByToken($provider, $token);
            }

            // Add data for registration
            $socialData['provider'] = $provider;
            $socialData['provider_id'] = $socialUser->getId();
            $socialData['properties'] = $socialUser->user;
            $socialData['email'] = $socialUser->getEmail();

            // Register user and associate with social profile
            $user = $this->socialiteService->registerWithProvider($userData, $socialData);

            // Login user
            auth()->loginUsingId($user->id);

In my socialite service class, registerWithProvider() I then use $userData and $socialData for create user and attach to social provider, and as additional step I check if email was changed by user, and when is not changed, I mark email as verified (but this depend on project that use MustVerifyEmail trait of Laravel:

        // Mark email as verified only if email come from social
        if($socialData['email'] === $userData['email'])
            $user->markEmailAsVerified();

Let me know what do you think.

Didn't see social providers in view.

Hi, I just prepared SocialProviderSeeder with fb, google, and github. I run command php artisan db:seed --class=SocialProviderSeeder. I see my providers in database but @include('social-auth::buttons') not return stored data. So how can I get return?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.