Boy132 b208835ed4
Add Oauth frontend and backend improvements (#718)
* better oauth provider loading

* add auth frontend

* add configs for all default providers

* add more default providers

* add env variables to enable oauth providers

* small refactor to link/ unlink routes

* add oauth tab to (admin) profile

* use redirects instead of exceptions

* add notification if no oauth user is found

* use import in config

* remove whmcs provider

* replace hardcoded links with `route`

* redirect to account page on unlink

* remove unnecessary controller and handle linking/ unlinking in action

* only show oauth tab if at least one oauth provider is enabled
2024-11-30 17:38:38 +01:00

79 lines
2.2 KiB
PHP

<?php
namespace App\Http\Controllers\Auth;
use App\Filament\Resources\UserResource\Pages\EditProfile;
use Filament\Notifications\Notification;
use Illuminate\Auth\AuthManager;
use Illuminate\Http\RedirectResponse;
use Laravel\Socialite\Facades\Socialite;
use App\Http\Controllers\Controller;
use App\Models\User;
use App\Services\Users\UserUpdateService;
use Exception;
use Illuminate\Http\Request;
class OAuthController extends Controller
{
/**
* OAuthController constructor.
*/
public function __construct(
private AuthManager $auth,
private UserUpdateService $updateService
) {}
/**
* Redirect user to the OAuth provider
*/
protected function redirect(string $driver): RedirectResponse
{
// Driver is disabled - redirect to normal login
if (!config("auth.oauth.$driver.enabled")) {
return redirect()->route('auth.login');
}
return Socialite::with($driver)->redirect();
}
/**
* Callback from OAuth provider.
*/
protected function callback(Request $request, string $driver): RedirectResponse
{
// Driver is disabled - redirect to normal login
if (!config("auth.oauth.$driver.enabled")) {
return redirect()->route('auth.login');
}
$oauthUser = Socialite::driver($driver)->user();
// User is already logged in and wants to link a new OAuth Provider
if ($request->user()) {
$oauth = $request->user()->oauth;
$oauth[$driver] = $oauthUser->getId();
$this->updateService->handle($request->user(), ['oauth' => $oauth]);
return redirect(EditProfile::getUrl(['tab' => '-oauth-tab']));
}
try {
$user = User::query()->whereJsonContains('oauth->'. $driver, $oauthUser->getId())->firstOrFail();
$this->auth->guard()->login($user, true);
} catch (Exception) {
// No user found - redirect to normal login
Notification::make()
->title('No linked User found')
->danger()
->persistent()
->send();
return redirect()->route('auth.login');
}
return redirect('/');
}
}