Skip to content

Commit

Permalink
Merge pull request #75 from thedevdojo/facebookSocialAuthFix
Browse files Browse the repository at this point in the history
fixing issues where facebook was not authenticating
  • Loading branch information
tnylea authored Jun 30, 2024
2 parents 3df4be0 + b102cf3 commit e26b3f5
Show file tree
Hide file tree
Showing 6 changed files with 109 additions and 52 deletions.
2 changes: 1 addition & 1 deletion public/build/assets/styles.css

Large diffs are not rendered by default.

26 changes: 26 additions & 0 deletions resources/views/components/elements/session-message.blade.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<!-- resources/views/components/auth/elements/session-message.blade.php -->
@php
$messageTypes = ['error', 'warning', 'success', 'info'];
$message = null;
$type = null;
foreach ($messageTypes as $messageType) {
if (session()->has($messageType)) {
$message = session($messageType);
$type = $messageType;
break;
}
}
@endphp

@if($message)
<div @class([
'mb-6 p-4 text-sm rounded-lg',
'bg-red-100 text-red-700' => $type == 'error',
'bg-orange-100 text-orange-700' => $type == 'warning',
'bg-green-100 text-green-700' => $type == 'success',
'bg-blue-100 text-blue-700' => $type == 'info',
]) role="alert">
{{ $message }}
</div>
@endif
2 changes: 2 additions & 0 deletions resources/views/pages/auth/login.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,8 @@ public function authenticate()
:description="($language->login->subheadline ?? 'No Description')"
:show_subheadline="($language->login->show_subheadline ?? false)" />

<x-auth::elements.session-message />

@if(config('devdojo.auth.settings.login_show_social_providers') && config('devdojo.auth.settings.social_providers_location') == 'top')
<x-auth::elements.social-providers />
@endif
Expand Down
1 change: 1 addition & 0 deletions resources/views/pages/auth/register.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,7 @@ public function register()
<x-auth::elements.container>

<x-auth::elements.heading :text="($language->register->headline ?? 'No Heading')" :description="($language->register->subheadline ?? 'No Description')" :show_subheadline="($language->register->show_subheadline ?? false)" />
<x-auth::elements.session-message />

@if(config('devdojo.auth.settings.social_providers_location') == 'top')
<x-auth::elements.social-providers />
Expand Down
127 changes: 77 additions & 50 deletions src/Http/Controllers/SocialController.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,71 +23,98 @@ public function redirect(Request $request, string $driver): RedirectResponse
return Socialite::driver($driver)->redirect();
}

private function dynamicallySetSocialProviderCredentials($provider)
{
$socialProvider = $this->getProviderCredentialsWithOverrides($provider);

Config::set('services.'.$provider.'.client_id', $socialProvider->client_id);
Config::set('services.'.$provider.'.client_secret', $socialProvider->client_secret);
Config::set('services.'.$provider.'.redirect', '/auth/'.$provider.'/callback');

}

private function getProviderCredentialsWithOverrides($provider)
{
$socialProvider = SocialProvider::where('slug', $provider)->first();

switch ($provider) {
case 'facebook':
$socialProvider->client_id = sprintf('%d', $socialProvider->client_id);
break;
}

return $socialProvider;
}

public function callback(Request $request, $driver)
{
$this->dynamicallySetSocialProviderCredentials($driver);

$socialiteUser = Socialite::driver($driver)->user();
try {
$socialiteUser = Socialite::driver($driver)->user();
$providerUser = $this->findOrCreateProviderUser($socialiteUser, $driver);

DB::transaction(function () use ($socialiteUser, $driver) {
// Attempt to find the user based on the social provider's ID and slug
$socialProviderUser = SocialProviderUser::where('provider_slug', $driver)
->where('provider_user_id', $socialiteUser->getId())
->first();
if ($providerUser instanceof RedirectResponse) {
return $providerUser; // This is an error redirect
}

if ($socialProviderUser) {
// Log the user in and redirect to the home page
Auth::login($socialProviderUser->user);
Auth::login($providerUser->user);

return redirect()->to(config('devdojo.auth.settings.redirect_after_auth'));
}
return redirect()->to(config('devdojo.auth.settings.redirect_after_auth'));
} catch (\Exception $e) {
return redirect()->route('auth.login')->with('error', 'An error occurred during authentication. Please try again.');
}
}

private function findOrCreateProviderUser($socialiteUser, $driver)
{
$providerUser = SocialProviderUser::where('provider_slug', $driver)
->where('provider_user_id', $socialiteUser->getId())
->first();

// Check if the email from the social provider already exists in the User table
$user = User::where('email', $socialiteUser->getEmail())->first();
if ($providerUser) {
return $providerUser;
}

if ($user) {
// Inform the user that an account with this email already exists
throw new \Exception('An account with the provided email already exists. Please log in.');
$user = User::where('email', $socialiteUser->getEmail())->first();

if ($user) {
$existingProvider = $user->socialProviders()->first();
if ($existingProvider) {
return redirect()->route('auth.login')->with('error',
"This email is already associated with a {$existingProvider->provider_slug} account. Please login using that provider.");
}
}

// No user exists, register a new user
$newUser = User::create([
'name' => $socialiteUser->getName(),
'email' => $socialiteUser->getEmail(),
// Add other fields as necessary
]);

$newUser->email_verified_at = now();
$newUser->save();

// Now add the social provider info for this new user
$newUser->addOrUpdateSocialProviderUser($driver, [
'provider_user_id' => $socialiteUser->getId(),
'nickname' => $socialiteUser->getNickname(),
'name' => $socialiteUser->getName(),
'email' => $socialiteUser->getEmail(),
'avatar' => $socialiteUser->getAvatar(),
'provider_data' => json_encode($socialiteUser->user),
'token' => $socialiteUser->token,
'refresh_token' => $socialiteUser->refreshToken,
'token_expires_at' => now()->addSeconds($socialiteUser->expiresIn),
]);

// Log in the newly created user
Auth::login($newUser);
});
return DB::transaction(function () use ($socialiteUser, $driver, $user) {
$user = $user ?? $this->createUser($socialiteUser);

// Redirect to a specific page after successful registration and login
return redirect()->to(config('devdojo.auth.settings.redirect_after_auth')); // Adjust according to your needs
return $this->createSocialProviderUser($user, $socialiteUser, $driver);
});
}

private function dynamicallySetSocialProviderCredentials($provider)
private function createUser($socialiteUser)
{
$socialProvider = SocialProvider::where('slug', $provider)->first();

Config::set('services.'.$provider.'.client_id', $socialProvider->client_id);
Config::set('services.'.$provider.'.client_secret', $socialProvider->client_secret);
Config::set('services.'.$provider.'.redirect', '/auth/'.$provider.'/callback');
return User::create([
'name' => $socialiteUser->getName(),
'email' => $socialiteUser->getEmail(),
'email_verified_at' => now(),
]);
}

private function createSocialProviderUser($user, $socialiteUser, $driver)
{
return $user->socialProviders()->create([
'provider_slug' => $driver,
'provider_user_id' => $socialiteUser->getId(),
'nickname' => $socialiteUser->getNickname(),
'name' => $socialiteUser->getName(),
'email' => $socialiteUser->getEmail(),
'avatar' => $socialiteUser->getAvatar(),
'provider_data' => json_encode($socialiteUser->user),
'token' => $socialiteUser->token,
'refresh_token' => $socialiteUser->refreshToken,
'token_expires_at' => $socialiteUser->expiresIn ? now()->addSeconds($socialiteUser->expiresIn) : null,
]);
}
}
3 changes: 2 additions & 1 deletion tailwind.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ import forms from '@tailwindcss/forms';
export default {
content: [
'resources/views/**/*.blade.php',
'../../resources/views/components/auth/**/*.blade.php'
'../../resources/views/components/auth/**/*.blade.php',
'resources/views/components/**/*.blade.php'
],

theme: {},
Expand Down

0 comments on commit e26b3f5

Please sign in to comment.