2023-11-20 23:25:36 +01:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace App\Http\Controllers\Auth;
|
|
|
|
|
|
|
|
use App\Facades\Settings;
|
|
|
|
use App\Http\Controllers\Controller;
|
|
|
|
use App\Models\User;
|
|
|
|
use Illuminate\Http\Request;
|
|
|
|
use Illuminate\Support\Carbon;
|
|
|
|
use Illuminate\Support\Facades\Auth;
|
|
|
|
use Illuminate\Support\Str;
|
|
|
|
use Laravel\Socialite\Facades\Socialite;
|
|
|
|
|
|
|
|
class SocialiteController extends Controller
|
|
|
|
{
|
2023-12-09 17:22:24 +01:00
|
|
|
/**
|
|
|
|
* Redirect to the provider's authentication url
|
|
|
|
*
|
|
|
|
* @return \Symfony\Component\HttpFoundation\RedirectResponse|\Illuminate\Http\RedirectResponse
|
|
|
|
*/
|
|
|
|
public function redirect(Request $request, string $driver)
|
2023-11-20 23:25:36 +01:00
|
|
|
{
|
2023-12-09 17:22:24 +01:00
|
|
|
if (! config('services.' . $driver . '.client_id') || ! config('services.' . $driver . '.client_secret')) {
|
|
|
|
return redirect('/error?err=sso_bad_provider_setup');
|
|
|
|
}
|
|
|
|
|
|
|
|
return Settings::get('enableSso')
|
|
|
|
? Socialite::driver($driver)->redirect()
|
|
|
|
: redirect('/error?err=sso_disabled');
|
2023-11-20 23:25:36 +01:00
|
|
|
}
|
|
|
|
|
2023-12-09 17:22:24 +01:00
|
|
|
/**
|
|
|
|
* Register (if needed) the user and authenticate him
|
|
|
|
*
|
|
|
|
* @return \Illuminate\Routing\Redirector|\Illuminate\Http\RedirectResponse
|
|
|
|
*/
|
|
|
|
public function callback(Request $request, string $driver)
|
2023-11-20 23:25:36 +01:00
|
|
|
{
|
2023-12-09 17:22:24 +01:00
|
|
|
try {
|
|
|
|
$socialiteUser = Socialite::driver($driver)->user();
|
|
|
|
} catch (\Exception $e) {
|
|
|
|
return redirect('/error?err=sso_failed');
|
|
|
|
}
|
2023-11-20 23:25:36 +01:00
|
|
|
|
2023-12-09 17:22:24 +01:00
|
|
|
/** @var User|null $user */
|
2023-11-20 23:25:36 +01:00
|
|
|
$user = User::firstOrNew([
|
2023-12-09 17:22:24 +01:00
|
|
|
'oauth_id' => $socialiteUser->getId(),
|
|
|
|
'oauth_provider' => $driver,
|
2023-11-20 23:25:36 +01:00
|
|
|
]);
|
|
|
|
|
2023-12-09 17:22:24 +01:00
|
|
|
if (! $user->exists) {
|
|
|
|
if (User::count() === 0) {
|
|
|
|
$user->is_admin = true;
|
|
|
|
}
|
|
|
|
else if (Settings::get('disableRegistration')) {
|
|
|
|
return redirect('/error?err=no_register');
|
|
|
|
}
|
|
|
|
$user->password = bcrypt(Str::random());
|
2023-11-20 23:25:36 +01:00
|
|
|
}
|
|
|
|
|
2023-12-09 17:22:24 +01:00
|
|
|
$user->email = $socialiteUser->getEmail() ?? $socialiteUser->getId() . '@' . $driver;
|
|
|
|
$user->name = $socialiteUser->getNickname() ?? $socialiteUser->getName() ?? $driver . ' #' . $socialiteUser->getId();
|
2023-11-20 23:25:36 +01:00
|
|
|
$user->last_seen_at = Carbon::now()->format('Y-m-d H:i:s');
|
|
|
|
$user->save();
|
|
|
|
|
2023-12-09 17:22:24 +01:00
|
|
|
Auth::guard()->login($user);
|
2023-11-20 23:25:36 +01:00
|
|
|
|
2023-12-09 17:22:24 +01:00
|
|
|
return redirect('/accounts');
|
2023-11-20 23:25:36 +01:00
|
|
|
}
|
|
|
|
}
|