48 lines
2.0 KiB
PHP
48 lines
2.0 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Controllers;
|
|
|
|
use App\Services\Parcel2Go;
|
|
use Illuminate\Http\RedirectResponse;
|
|
use Illuminate\Http\Request;
|
|
use Throwable;
|
|
|
|
class Parcel2GoConnectionController extends Controller
|
|
{
|
|
public function connect(Request $request, Parcel2Go $parcel2Go): RedirectResponse
|
|
{
|
|
abort_unless($request->user()->role === 'admin', 403);
|
|
if (! $parcel2Go->profileClientConfigured()) {
|
|
return redirect()->route('settings.index')->withErrors(['parcel2go' => 'Save the Parcel2Go Authorization Code Client ID first.']);
|
|
}
|
|
|
|
$state = bin2hex(random_bytes(24));
|
|
$verifier = rtrim(strtr(base64_encode(random_bytes(48)), '+/', '-_'), '=');
|
|
$request->session()->put('parcel2go_oauth', ['state' => $state, 'verifier' => $verifier, 'started' => time()]);
|
|
|
|
return redirect()->away($parcel2Go->authorizationUrl($state, $verifier));
|
|
}
|
|
|
|
public function callback(Request $request, Parcel2Go $parcel2Go): RedirectResponse
|
|
{
|
|
abort_unless($request->user()->role === 'admin', 403);
|
|
$pending = $request->session()->pull('parcel2go_oauth');
|
|
if (! is_array($pending) || time() - ($pending['started'] ?? 0) > 600
|
|
|| ! is_string($request->query('state'))
|
|
|| ! hash_equals($pending['state'] ?? '', $request->query('state'))
|
|
|| ! is_string($request->query('code'))) {
|
|
return redirect()->route('settings.index')->withErrors(['parcel2go' => 'Parcel2Go consent expired or was not verified. Please try again.']);
|
|
}
|
|
|
|
try {
|
|
$parcel2Go->connectProfile($request->query('code'), $pending['verifier']);
|
|
|
|
return redirect()->route('settings.index')->with('status', 'Parcel2Go account connected. Shipment history is available in Shipping.');
|
|
} catch (Throwable $exception) {
|
|
report($exception);
|
|
|
|
return redirect()->route('settings.index')->withErrors(['parcel2go' => 'Parcel2Go rejected the account connection. Check the Client ID, scopes and callback URL.']);
|
|
}
|
|
}
|
|
}
|