amber-laravel/app/Http/Controllers/Web/AuthController.php
2024-07-24 00:40:56 +08:00

123 lines
3.6 KiB
PHP

<?php
namespace App\Http\Controllers\Web;
use App\Http\Controllers\Controller;
use App\Logic\OpenIDLogic;
use App\Models\User;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
class AuthController extends Controller
{
public string $scopes = 'profile email realname openid';
protected OpenIDLogic $openIDLogic;
protected string $callback_url;
/**
* @throws ContainerExceptionInterface
* @throws GuzzleException
* @throws NotFoundExceptionInterface
*/
public function __construct()
{
$this->openIDLogic = app(OpenIDLogic::class);
}
public function redirect(Request $request)
{
$request->session()->put('state', $state = Str::random(40));
$query = http_build_query([
'client_id' => config('oauth.client_id'),
'redirect_uri' => $this->callback_url,
'response_type' => 'code',
'scope' => $this->scopes,
'state' => $state,
]);
return redirect()->to($this->openIDLogic->auth_url.'?'.$query);
}
/**
* @throws GuzzleException
*/
public function callback(Request $request)
{
$state = $request->session()->pull('state');
if (strlen($state) > 0 && $state !== $request->state) {
return redirect()->route('login');
}
// if access_denied
if ($request->error) {
return redirect()->route('home');
}
$http = new Client;
try {
$authorize = $http->post($this->openIDLogic->token_url, [
'form_params' => [
'grant_type' => 'authorization_code',
'client_id' => config('oauth.client_id'),
'client_secret' => config('oauth.client_secret'),
'redirect_uri' => $this->callback_url,
'code' => $request->code,
],
]);
} catch (ClientException $e) {
return redirect()->route('home');
}
$authorize = json_decode($authorize->getBody());
$oauth_user = $http->get($this->openIDLogic->user_url, [
'headers' => [
'Accept' => 'application/json',
'Authorization' => 'Bearer '.$authorize->access_token,
],
])->getBody();
$oauth_user = json_decode($oauth_user);
$user_sql = User::where('email', $oauth_user->email);
$user = $user_sql->first();
if (is_null($user)) {
$name = $oauth_user->name;
$email = $oauth_user->email;
$email_verified_at = $oauth_user->email_verified ? now() : null;
$api_token = Str::random(50);
$user = User::create([
'name' => $name,
'email' => $email,
'email_verified_at' => $email_verified_at,
'api_token' => $api_token,
'password' => Hash::make(Str::random(50)),
]);
$request->session()->put('auth.password_confirmed_at', time());
} else {
if ($user->name != $oauth_user->name) {
User::where('email', $oauth_user->email)->update([
'name' => $oauth_user->name,
]);
}
}
Auth::loginUsingId($user->id, true);
return redirect()->route('home');
}
}