unsa-pis-be/app/Http/Controllers/Api/LoginController.php

93 lines
2.3 KiB
PHP
Raw Normal View History

2022-08-18 00:18:05 +00:00
<?php
namespace App\Http\Controllers\Api;
2022-08-18 00:18:05 +00:00
2022-10-20 22:27:03 +00:00
use App\Http\Controllers\Controller;
2022-08-18 00:18:05 +00:00
use Laravel\Socialite\Facades\Socialite;
use App\Models\User;
2022-10-20 14:51:13 +00:00
class LoginController extends Controller
{
public function redirectToProvider($provider)
{
2022-08-18 00:18:05 +00:00
$validated = $this->validateProvider($provider);
2022-10-20 14:51:13 +00:00
if (!is_null($validated)) {
2022-08-18 00:18:05 +00:00
return $validated;
}
2022-10-20 22:20:51 +00:00
return Socialite::driver($provider)->stateless()->redirect();
2022-08-18 00:18:05 +00:00
//return Socialite::driver($provider)->redirect();
}
//$out = new \Symfony\Component\Console\Output\ConsoleOutput();
//$out->writeln("Hello from Terminal");
//error_log('Some message here.');
2022-10-20 14:51:13 +00:00
public function handleProviderCallback($provider)
{
$validated = $this->validateProvider($provider);
if (!is_null($validated)) {
return $validated;
}
try {
2022-10-20 22:51:02 +00:00
$userProvider = Socialite::driver($provider)->stateless()->user();
2022-10-20 14:51:13 +00:00
} catch (ClientException $exception) {
return response()->json(['error' => 'Credenciales de google invalidas.'], 422);
}
2022-10-20 22:36:41 +00:00
$user = $user = User::where("email", "=", $userProvider->email)->first();
2022-10-20 14:51:13 +00:00
if (isset($user)) {
2022-10-21 23:12:39 +00:00
$userCreated = User::updateOrCreate(
2022-10-20 14:51:13 +00:00
[
'email' => $userProvider->email
],
[
//'email_verified_at' => now(),
'name' => $userProvider->user['given_name'],
'lastname' => $userProvider->user['family_name'],
'status' => true
]
);
$userCreated->providers()->updateOrCreate(
[
'provider' => $provider,
'id_provider' => $userProvider->getId()
],
[
'avatar' => $userProvider->getAvatar()
]
);
$token = $userCreated->createToken('token-auth_token')->plainTextToken;
return response()->json([
"message" => "Usuario logueado",
"user" => $userCreated,
"image" => $userProvider->getAvatar(),
"role" => $userCreated->roles[0]->name,
2022-10-20 14:51:13 +00:00
"access_token" => $token
]);
2022-10-20 14:51:13 +00:00
} else {
return response()->json([
"status" => 0,
"message" => "Usuario no registrado en el sistema",
], 404);
}
2022-08-18 00:18:05 +00:00
}
2022-10-20 14:51:13 +00:00
protected function validateProvider($provider)
{
2022-08-18 00:18:05 +00:00
//En caso se quiera iniciar sesion con facebook o github
//if (!in_array($provider, ['facebook', 'github', 'google'])){
//por el momento solo con google
2022-10-20 14:51:13 +00:00
if (!in_array($provider, ['google'])) {
2022-08-18 00:18:05 +00:00
return response()->json(['error' => 'Por favor usar google para loguearse'], 422);
}
}
}