HandlCallback

mail@pastecode.io avatar
unknown
php
17 days ago
2.4 kB
1
Indexable
Never
 public function handleCallback(Request $request, $provider)
    {
        $validator = Validator::make($request->only('name', 'email', 'google_id'), [
            'name' => 'required',
            'email' => 'required|email',
            'google_id' => 'required|numeric',
        ]);

        if($validator->fails())
        {
            return response()->json($validator->errors(), 400);
        }

        $validated = $this->validateProvider($provider);
        if (! is_null($validated)) {
            return $validated;
        }

        if (empty($request->input('name'))) {
            return response()->json('Parameter atau payload name tidak boleh kosong');
        } elseif (empty($request->input('email'))) {
            return response()->json('Parameter atau payload email tidak boleh kosong');
        } elseif (empty($request->input('google_id'))) {
            return response()->json('Parameter atau payload google_id tidak boleh kosong');
        }

        // $googleUser =  Socialite::driver($provider)->stateless();

        $findNameUser = User::where('name', $request->input('name'))->first();
        $findEmailUser = User::where('email', $request->input('email'))->first();
        $findGoogleIdUser = SocialAccount::where('google_id', $request->input('google_id'))->first();

        if (! $findGoogleIdUser || ! $findNameUser || ! $findEmailUser) {

        $newUser = User::create([
            'name' => $request->input('name'),
            'username' => $request->input('name'),
            'email' => $request->input('email'),
            'password' => '',
        ]);

        $newUser->social_accounts()->create([
            'provider' => $provider,
            'user_id' => $newUser->id,
            'google_id' => $request->input('google_id'),
            'avatar' => '',
        ]);

        $newUser->assignRole('orang_tua');

        $data = [
            'token' => $newUser->createToken('login-token')->plainTextToken,
            'user' => $newUser,
        ];

        return response()->json($data, 200);

    } else {
        // $token = $findGoogleIdUser->createToken('login-token')->plainTextToken;

        $data = [
            'token' => $findGoogleIdUser->createToken('login-token')->plainTextToken,
            'user' => $findNameUser,
        ];

        return response()->json($data, 200);
    }

    }
Leave a Comment