GithubHelp home page GithubHelp logo

chrisreedio / socialment Goto Github PK

View Code? Open in Web Editor NEW
73.0 1.0 10.0 179 KB

Socialite OAuth Support for Filament

License: MIT License

JavaScript 1.33% PHP 93.08% CSS 0.20% Blade 5.39%
auth authen filament filamentphp laravel oauth oauth2 socialite

socialment's Introduction

Socialment - Socialite OAuth Support for Filament

Socialment

Latest Version on Packagist Tests Action Status Code Style Action Status PHPStan Action Status Total Downloads

About

Bring up-to-date and simple Socialite support to your Filament admin panel with this plugin. Adds OAuth buttons to your login page.

Ideal for Laravel and Filament users seeking a straightforward OAuth integration.

Warning

Socialment is currently in beta. Please report any issues you encounter.

Caution is advised if you choose to use this package in production.

Azure AD support has been the only tested provider so far.

References

This package extends Laravel Socialite. Socialite currently supports authentication via Facebook, Twitter, LinkedIn, Google, GitHub, GitLab, and Bitbucket out of the box.

Refer to the Socialite documentation for more information on how to configure your application to use these providers.

Many other providers are available via the Socialite Providers website. Refer to the documentation for each provider for information on how to configure your application to use them.

Demo

For an example usage of this package, see ChrisReedIO/Socialment-Demo.

image


Installation

You can install the package via composer:

composer require chrisreedio/socialment

Usage

Initial Setup

You can easily perform the initial setup by running the following command:

php artisan socialment:install

Additionally, edit your panel's tailwind.config.js content section to include the last line of the following:

    content: [
    "./app/Filament/**/*.php",
    "./resources/views/filament/**/*.blade.php",
    "./vendor/filament/**/*.blade.php",
    // ... Other Content Paths

    // Ensure the line below is listed!!!
    "./vendor/chrisreedio/socialment/resources/**/*.blade.php",
],

If this step is forgotten, the styling of the plugin will not be applied.

Please continue to the next sections to continue the setup process.

Panel Configuration

Include this plugin in your panel configuration:

$panel
	->plugins([
		// ... Other Plugins
        \ChrisReedIO\Socialment\SocialmentPlugin::make(),        
	])

Provider Configuration

Important

At this point, you'll need to configure your application to use the provider(s) you want to support.

Either configure the needed stock socialite providers or community maintained providers.

Refer to the Socialite documentation for more information.

This will usually involve installing a package and configuring your application's config/services.php file.

Socialment Configuration
Provider Configuration

Warning

This method of provider configuration is now deprecated and will be removed in a future release.

Configuring providers in your panel configuration has many advantages and is the recommended method.

Whether you're using the default providers or adding your own, you'll need to configure them in the socialment.php config file.

Configure the socialment.php config file to specify providers in the following format:

return [
    'providers' => [
        'azure' => [
            'icon' => 'fab-microsoft', // Font Awesome Brand Icon
            'label' => 'Azure', // Display Name on the Login Page
        ]
    ],
	// ... Other Configuration Parameters
];

Providers specified in the config file are global across all panels.

Per-Panel Provider Configuration

You should specify providers on a per-panel basis. To do this use the ->registerProvider method on the plugin.

$panel->plugins([
    \ChrisReedIO\Socialment\SocialmentPlugin::make()
        ->registerProvider('azure', 'fab-microsoft', 'Azure Active Directory'),
]);
Sample Provider Configuration - Azure Active Directory

Important

For this configured Azure provider, the redirect URI would be https://DOMAIN/login/azure/redirect

The callback URI would be https://DOMAIN/login/azure/callback

For example, the sample provider included in the stock socialment.php config is Azure Active Directory. To start, You would refer to the documentation for the Azure Socialite Provider.

Normally, you would follow the providers documentation on the aforementioned link but to demostrate the process for Socialment, I'll include the steps here.

Per their documentation, you would install the community Azure provider via

composer require socialiteproviders/microsoft-azure

Then you would configure your config/services.php file to include the Azure provider's credentials:

'azure' => [    
  'client_id' => env('AZURE_CLIENT_ID'),
  'client_secret' => env('AZURE_CLIENT_SECRET'),
  'redirect' => env('AZURE_REDIRECT_URI'),
  'tenant' => env('AZURE_TENANT_ID'),
  'proxy' => env('PROXY')  // optionally
],

In addition, you need to add this provider's event listener to your app/Providers/EventServiceProvider.php file:

protected $listen = [
	// ... other listeners

    \SocialiteProviders\Manager\SocialiteWasCalled::class => [
        // ... other providers
        \SocialiteProviders\Azure\AzureExtendSocialite::class.'@handle',
    ],
];

Finally, don't forget to add the needed environment variables to your .env file:

AZURE_CLIENT_ID=
AZURE_CLIENT_SECRET=
AZURE_REDIRECT_URI=
AZURE_TENANT_ID=

The usage section can usually be ignored as that is the main part this package should handle for you.

Note

It is in the plans to improve the handling of the sign in process to align more with Socialstream in allowing you to specify an action class or closure to handle the sign in process.

This will allow for customized handling on a per provider, per application basis.

This package also uses the Blade Font Awesome package by Owen Voke.

Search for brand icons on the Font Awesome Website.

Visibility Override

By default, the plugin displays the configured providers at the bottom of the login form. You can additionally override the visibility of the plugin by passing a boolean or closure to the visible method:

$panel->plugins([
    \ChrisReedIO\Socialment\SocialmentPlugin::make()
        ->visible(fn () => false)
]);

Extras

You may publish and customize the views using

php artisan vendor:publish --tag="socialment-views"

Login Callbacks

You may configure pre/post login hooks/callbacks by adding code similar to the following to the boot method of a service provider:

use ChrisReedIO\Socialment\Models\ConnectedAccount;

public function boot(): void
{
    // Post Login Hook
    Socialment::preLogin(function (ConnectedAccount $connectedAccount) {
        // Handle custom pre login logic here.
    });
    
    // Multiple hooks can be added
    Socialment::preLogin(function (ConnectedAccount $connectedAccount) {
        // Handle additional custom pre login logic here if you need.
    });

    // Post Login Hook
    Socialment::postLogin(function (ConnectedAccount $connectedAccount) {
        // Handle custom post login logic here.
        Log::info('User logged in with ' . $connectedAccount->provider . ' account', [
            'connectedAccount' => $connectedAccount,
        ]);
    });
}

The user relation can be accessed via $connectedAccount->user.

The ConnectedAccount is passed instead of the User so that you can easily know which social account was used for the login.

Login Route for failed logins

If a login fails or encounters a InvalidStateException, the user will be redirected to the configured loginRoute route.

This defaults to filament.admin.auth.login but can be overriden on the plugin declaration in your panel provider configuration:

$panel->plugins([
    \ChrisReedIO\Socialment\SocialmentPlugin::make()
        ->loginRoute('filament.staff.auth.login')
]);

You may also use a closure here to dynamically set the route:

$panel->plugins([
    \ChrisReedIO\Socialment\SocialmentPlugin::make()
        ->loginRoute(fn () => SomeFunctionToGetTheRouteName())
]);

Config

This is the contents of the published config file:

return [
    'view' => [
        // Set the text above the provider list
        'prompt' => 'Or Login Via',
        // Or change out the view completely with your own
        'providers-list' => 'socialment::providers-list',
    ],
    
    // DEPRECATED: This will be removed in a future version.
    // Configure routes via the panel provider.
    'routes' => [
        'home' => 'filament.admin.pages.dashboard',
    ],
    
    'models' => [
        // If you want to use a custom user model, you can specify it here.
        'user' => \App\Models\User::class,
    ],
    
    // DEPRECATED: This will be removed in a future version.
    // Configure providers via the panel provider.
    'providers' => [
        'azure' => [
            'icon' => 'fab-microsoft',
            'label' => 'Azure Active Directory',
        ]
    ],
];

Frontend SPA Authentication

Caution

This feature is still in development and thus highly experimental.

Expect breaking changes and bugs. Use at your own risk.

The documentation will be updated as the feature is finalized.

This feature may be spun off into a separate package in the future.

This package includes support for authenticating with a Single Page Application (SPA) frontend. Both the Filament backend and SPA frontend must be hosted on the same domain.

The login session is shared so logging into either the SPA or the backend will log you into both.

Special CORS and session settings are required to make this work and caution must be taken to ensure that proper access controls (Policies / Panel Access / Etc) are in place.

Setup

You'll need to add the new spaAuth routes to your routes/web file.

// In this example, we pass 'dashboard' as the SPA route name.
// We'll want to make sure the 'prefix' our custom routes match.
// If no prefix is set/passed to spaAuth, the default is 'spa'.

Route::spaAuth('dashboard');

Route::middleware('auth:sanctum')
    ->prefix('dashboard')
    ->as('dashboard.')
    ->group(function () {
        // Custom Routes
    });

Configuration Changes

You'll need to modify the config/cors.php file.

You'll need to add the following to the paths array:

    'paths' => [
        // ... Other Paths
        'spa/*', // OR use the custom prefix you set in the routes/web file.
    ],

Also ensure that the supports_credentials is set to true:

    'supports_credentials' => true,

Environment Variables

We need to set a few ENV variables to ensure that the SPA authentication works properly.

SANCTUM_STATEFUL_DOMAINS="https://frontend.localhost:3000,https://backend.localhost"
SESSION_DOMAIN=".localhost"
SESSION_SECURE_COOKIE=true
SPA_URL="https://frontend.localhost:3000"

The SESSION_DOMAIN should be the shared domain between your SPA and your backend. It should begin with a period.

The SPA_URL is the URL of your SPA application.

Note

Ths SPA functionality is a work in progress and is subject to change.

This documentation section will be updated as the feature is finalized.

Testing

Note

Tests have yet to be written for this package. They are on my TODO list. I'm also open to PRs.

composer test

Changelog

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

Contributing

Please see CONTRIBUTING for details.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

License

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

socialment's People

Contributors

atmonshi avatar chrisreedio avatar dependabot[bot] avatar github-actions[bot] avatar pepperfm 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

socialment's Issues

Login & Registration Callbacks

Discussed in #18

Originally posted by chrisreedio October 15, 2023
It would be useful to be able to setup callbacks/hooks on the login/signup process.

This would enable the developer to be able to customize the login/signup process.

Use Filament Button Component

Discussed in #25

Originally posted by devhoussam1998 October 29, 2023
providers-list.blade.php

@foreach ($providers as $providerName => $provider)
  <x-filament::button href="{{ route('socialment.redirect', $providerName) }}" tag="a"
    icon="{{ $provider['icon'] }}" color="{{ $provider['color'] }}" size="{{ $provider['size'] }}">
    {{ $provider['label'] }}
  </x-filament::button>
@endforeach

socialment.php

<?php

// config for ChrisReedIO/Socialment
return [
    // The list of providers to display on the login page
    // You must install the appropriate Socialite provider package for each provider you want to use
    // if it isn't one supported by the core Laravel Socialite package.
    'providers' => [
        'google' => [
            'icon' => 'bi-google',
            'label' => 'Google',
            'color' => 'danger',
            'size' => 'md',
        ],
    ],

    'view' => [
        // Set the text above the provider list
        'prompt' => 'Or Login Via',
        // Or change out the view completely with your own
        'providers-list' => 'socialment::providers-list',
    ],

    'routes' => [
        // The route to redirect to after a successful login
        'home' => 'filament.admin.pages.dashboard',
    ],

    'models' => [
        // If you want to use a custom user model, you can specify it here.
        'user' => \App\Models\User::class,
    ],

];

[Bug]: Svg by name "circle-x" from set "fontawesome-regular" not found.

What happened?

After encountering a login error, it appears that the following view is loaded:
.\vendor\chrisreedio\socialment\resources\views\login-error.blade.php
This view produces the error: "Svg by name "circle-x" from set "fontawesome-regular" not found."

How to reproduce the bug

  1. Add a new field to the User table, for example:

    $table->uuid('uuid')->index();
  2. Attempt to log in to the application.

  3. The login process fails due to the changes made to the User table.

  4. After the failed login, the user is redirected to the Filament admin login page:

    /admin/login
    
  5. The error message "Svg by name "circle-x" from set "fontawesome-regular" not found" is displayed on the login error page.

Package Version

3.6

PHP Version

8.2.17

Laravel Version

11.0.6

Which operating systems does with happen with?

Windows

Notes

I tried installing blade-ui-kit/blade-icons v1.6 and owenvoke/blade-fontawesome v2.6
It seems that the error is related to the Blade icon set "fontawesome-regular" and the specific icon "circle-x" not being found. This could be due to a missing or incorrect configuration of the Blade icon packages (blade-ui-kit/blade-icons and owenvoke/blade-fontawesome) in conjunction with the Socialment package. I have installed both.

[Bug]: Canceled login request triggers an error

What happened?

When a user tries to signup then later decides to return back by canceling the request for example when using twitter. He gets an error.

I fixed this by adding this line to the callback function in SocialmentController

        if (request()->has('denied')) {
            // Handle the denied access case here, such as showing an error message or redirecting
            return redirect()->route('filament.app.auth.login');
        }

I added this too to make it easier for users to create an account.

        if (! $connectedAccount->exists) {
            // Check if a user with the same email already exists
            $user = User::where('email', $socialUser->getEmail())->first();
        
            if (!$user) {
                // If the user doesn't exist, create a new one
                $user = User::create([
                    'name' => $socialUser->getName(),
                    'email' => $socialUser->getEmail(),
                    'company' => '',
                    // You can set other user attributes here as needed
                ]);
            }
        
            // Associate the user with the connected account
            $connectedAccount->user()->associate($user)->save();
        }
        

Also you could edit the documentation and tell the user to add routes to web.php because the ones in your package doesn't work, atleast i guess because i defined another path. Not everyone will know that he has to use /login/{provider}/callback because the standard is /auth/{provider}/callback which is important for the redirect url.

Route::get('/auth/{provider}', [SocialmentController::class, 'redirect'])->name('socialment.redirect');
Route::get('/auth/{provider}/callback', [SocialmentController::class, 'callback'])->name('socialment.callback');

Also you could mention that users have to add credentials to config/services.php or else it won't work.

How to reproduce the bug

I explained above how to reproduce the issue. I could not do a pull request. But its a great package.

Package Version

v3.0.0-beta

PHP Version

8.2.0

Laravel Version

10.0.0

Which operating systems does with happen with?

No response

Notes

No response

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.