Social Authentication (OAuth)

Rhapsody provides a built‑in SocialAuthController that handles authentication through Google and Facebook using the league/oauth2-client packages.

Installation

The required packages are already included in the core if you installed via Composer. If you're upgrading, run:

composer require league/oauth2-client league/oauth2-google league/oauth2-facebook

Configuration

Add the following environment variables to your .env file:

APP_URL=http://localhost/rhapsody-dev   # (adjust to your base URL)

GOOGLE_CLIENT_ID=your_google_client_id
GOOGLE_CLIENT_SECRET=your_google_client_secret
GOOGLE_REDIRECT_URI=http://localhost/rhapsody-dev/auth/callback/google

FACEBOOK_APP_ID=your_facebook_app_id
FACEBOOK_APP_SECRET=your_facebook_app_secret
FACEBOOK_REDIRECT_URI=http://localhost/rhapsody-dev/auth/callback/facebook

The redirect URIs must match exactly what you have registered in the Google and Facebook developer consoles.

Routes

Add these routes to your routes/web.php file:

use Rhapsody\Core\Controllers\SocialAuthController;

Router::get('/auth/redirect/{provider}', [SocialAuthController::class, 'redirectToProvider'])->name('auth.redirect');
Router::get('/auth/callback/{provider}', [SocialAuthController::class, 'handleProviderCallback']);

The redirectToProvider method sends the user to the chosen provider's authorization page, and handleProviderCallback handles the callback, creating or logging in the user.

Using in Views

In your login view, you can generate the provider links using the named route:

<a href="{{ route('auth.redirect', {provider: 'google'}) }}">Login with Google</a>
<a href="{{ route('auth.redirect', {provider: 'facebook'}) }}">Login with Facebook</a>

Customizing the User Model

The controller uses App\Models\User by default. If you're using a different model, you can override the handleProviderCallback method or extend the controller.

Adding More Providers

To add other providers (e.g., GitHub, Twitter), you'll need to install their respective OAuth2 packages, add a new case to the getProvider() method in SocialAuthController, and update your routes accordingly.