Add discord oauth
This commit is contained in:
60
app/Http/Controllers/Auth/DiscordAuthController.php
Normal file
60
app/Http/Controllers/Auth/DiscordAuthController.php
Normal file
@@ -0,0 +1,60 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Auth;
|
||||
|
||||
use App\Models\User;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Laravel\Socialite\Facades\Socialite;
|
||||
|
||||
class DiscordAuthController extends Controller
|
||||
{
|
||||
/**
|
||||
* Redirect to Discord
|
||||
*/
|
||||
public function redirect(): RedirectResponse
|
||||
{
|
||||
return Socialite::driver('discord')->redirect();
|
||||
}
|
||||
|
||||
/**
|
||||
* Callback received from Discord
|
||||
*/
|
||||
public function callback(): RedirectResponse
|
||||
{
|
||||
$discordUser = Socialite::driver('discord')->user();
|
||||
|
||||
$user = User::where('discord_id', $discordUser->id)->first();
|
||||
|
||||
if (! $user) {
|
||||
// link by email if it already exists
|
||||
$user = User::where('email', $discordUser->email)->first();
|
||||
|
||||
if ($user) {
|
||||
$user->update([
|
||||
'discord_id' => $discordUser->id,
|
||||
'discord_name' => $discordUser->nickname ?? $discordUser->name,
|
||||
'discord_avatar' => $discordUser->avatar,
|
||||
]);
|
||||
} else {
|
||||
// Create new user
|
||||
$user = User::create([
|
||||
'name' => $discordUser->name,
|
||||
'email' => $discordUser->email,
|
||||
'discord_id' => $discordUser->id,
|
||||
'discord_name' => $discordUser->nickname ?? $discordUser->name,
|
||||
'discord_avatar' => $discordUser->avatar,
|
||||
'password' => bcrypt(Str::random(40)),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
Auth::login($user, true);
|
||||
|
||||
return redirect()->route('home.index');
|
||||
}
|
||||
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Providers;
|
||||
|
||||
use Illuminate\Support\Facades\Event;
|
||||
use Illuminate\Support\ServiceProvider;
|
||||
|
||||
class AppServiceProvider extends ServiceProvider
|
||||
@@ -19,6 +20,8 @@ class AppServiceProvider extends ServiceProvider
|
||||
*/
|
||||
public function boot(): void
|
||||
{
|
||||
//
|
||||
Event::listen(function (\SocialiteProviders\Manager\SocialiteWasCalled $event) {
|
||||
$event->extendSocialite('discord', \SocialiteProviders\Discord\Provider::class);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user