Fahim Uddin
Fahim Uddin

Reputation: 701

Social Login with Angular 5 and Lumen 5.6

I am trying to implement social login with angular 5 as my front-end and lumen 5.6 as my backend.

I am using JWT Authentication system with Lumen. So, I am confused here how I should implement social login system in this situation.

Through my research I have come to these libraries which can do that work, but I am not sure how the process is handled from the front-end (angular) to back-end (lumen).

For Angular 5 -
angularx-social-login OR Satellizer
For Lumen -
laravel/socialite

But as I have not found any documentation on Satellizer working with Angular 5, so I choosed to use other one.

I have read this article, but still the process from front-end to back-end is not clear to me. https://medium.com/@barryvdh/oauth-in-javascript-apps-with-angular-and-lumen-using-satellizer-and-laravel-socialite-bb05661c0d5c

Any explanatory help ?

Upvotes: 1

Views: 2369

Answers (1)

Skel
Skel

Reputation: 1667

So the way I used social login with Angular 5 is with a package called

"angular5-social-login": "^1.0.9",

So add that to your package.json file.

Import it in app.module.ts

import { SocialLoginModule, AuthServiceConfig, GoogleLoginProvider, FacebookLoginProvider } from 'angular5-social-login';

Set up a function in app.module.ts

export function getAuthServiceConfigs() {
  const config = new AuthServiceConfig(
      [
        {
          id: FacebookLoginProvider.PROVIDER_ID,
          provider: new FacebookLoginProvider('') // Left as i dont use it
        },
        {
          id: GoogleLoginProvider.PROVIDER_ID,
          provider: new GoogleLoginProvider('YOUR-API-TOKEN.apps.googleusercontent.com')
        },
      ]
  );
  return config;
}

Add it to your Imports in app.module.ts

imports: [
    HttpClientModule,
    AppRoutingModule,
    ...
    SocialLoginModule, // One we need to add
  ],

Then at the add it to your providers in app.module.ts

providers: [
    YourServices,
    ...
    ApiAuthService,
    {
        provide: AuthServiceConfig,
        useFactory: getAuthServiceConfigs
    },
    LoggedInGuard,
],

As you can see i have a LoggedInGuard and a ApiAuthService these are these with the auth and checking your logged in.

So That's the package installed and set up...

Now inside of api-auth.service.ts add this function

socialSignIn(userData) {
    const formData = new FormData();
      formData.append('email', userData.email);
      formData.append('name', userData.name);
      formData.append('provider', userData.provider);
      formData.append('id', userData.id);
      formData.append('idToken', userData.idToken);
      formData.append('token', userData.token);
      formData.append('image', userData.image);
    return this._http.post(
      environment.apiUrl + '/auth/social-signin/',
      formData,
      {
        headers: new Headers({
          'Authorization': 'Bearer ' + userData.idToken
        })
      }
    );
  }

Now in your sign in component add this to the HTML

<div (click)="socialSignIn('google')" class="c2a_btn large google">
    Log in with google 
</div>

In your sign in component .ts file add this function

import { AuthService, FacebookLoginProvider, GoogleLoginProvider, LinkedinLoginProvider } from 'angular5-social-login';
import { ApiAuthService } from '../../../../services/api-auth.service';
import { TokenService } from '../../../../services/token.service';


public socialSignIn(socialPlatform: string) {
    this.loading = true;
    let socialPlatformProvider;
    if (socialPlatform === 'facebook') {
      socialPlatformProvider = FacebookLoginProvider.PROVIDER_ID;
    } else if (socialPlatform === 'google') {
      socialPlatformProvider = GoogleLoginProvider.PROVIDER_ID;
    } else if (socialPlatform === 'linkedin') {
      socialPlatformProvider = LinkedinLoginProvider.PROVIDER_ID;
    }

    this.socialAuthService.signIn(socialPlatformProvider).then(
      (userData) => {
        this._apiAuthService.socialSignIn(userData)
        .map( data => {
          return data.json();
        })
        .subscribe(
          token => {
            this._tokenService.setAccessToken(token.access_token);
          },
          error => {
            this.invalidLogin = true;
            this.loading = false;
          },
          () => {
            this.loading = false;
            this.closeSignIn.emit('out');
            // this._router.navigate(['/profile']);
          }
        );
      }
    );
  }

This is just the front end now for the back end. I'm using Laravel 5.6

But I made a function like this

public function socialSignIn(Request $request, Response $response) {

        $date = date('Y-m-d h:i:s');
        $provider = $request->input('provider');

        if ($provider == 'google') {
            $id_token = $request->header('Authorization');
            $id_token = str_replace("Bearer ","",$id_token);

            $CLIENT_ID = Config::get('google.client_id');

            $email = $request->input('email');
            $names = $request->input('name');
            $name = explode(' ', $names);

            $client = new \Google_Client();
            $client->setDeveloperKey($CLIENT_ID);
            $payload = $client->verifyIdToken($id_token);
            if ($payload) {
                if (User::where('email', '=', $email)->exists()) {

                    $user = User::Where('email', '=', $email)->first();
                    if(!Auth::loginUsingId($user->id)){
                        return response()->json([
                            'failed'
                        ], 403);
                    }

                    $updateLastLoginDate = User::where('id', Auth::user()->id)-first();
                    $updateLastLoginDate->last_login_date = $date;
                    $updateLastLoginDate->save();

                    $activeAccount = Auth::user();
                    $activeAccount->active = '1';
                    $activeAccount->save();

                } else {

                    $recordUser = New User;
                    $recordUser->email = $request->input('email');
                    $recordUser->last_login_date = $date;
                    $recordUser->save();

                    $recordLinkedSocialAcounts = new LSA;
                    $recordLinkedSocialAcounts->user_id = $recordUser->id;
                    $recordLinkedSocialAcounts->provider_name = $provider;
                    $recordLinkedSocialAcounts->provider_id = $request->input('id');
                    $recordLinkedSocialAcounts->save();

                    $recordUserInformation = new UPI;
                    $recordUserInformation->user_id = $recordUser->id;
                    $recordUserInformation->first_name = $name[0];
                    $recordUserInformation->last_name = $name[1];
                    $recordUserInformation->last_login_date = $date;
                    $recordUserInformation->image = $request->input('image');
                    $recordUserInformation->save();

                    if(!Auth::loginUsingId($recordUser->id)){
                        return response()->json([
                            'failed'
                        ], 403);
                    }
                }

                return response()->json([
                    'access_token' => Auth::user()->createToken('access_token')->accessToken,
                    'role_id' => Auth::user()->role_id
                ], 200);
            } else {
                return response()->json([
                    'failed'
                ], 403);
            }
        }
    }

I will most probably make a video on this soon. Any questions just ask

Upvotes: 1

Related Questions