Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 18 additions & 6 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,15 @@ LOG_STACK=single
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug

DB_CONNECTION=sqlite
# DB_HOST=127.0.0.1
# DB_PORT=3306
# DB_DATABASE=laravel
# DB_USERNAME=root
# DB_PASSWORD=
# `deploy.php` shares only `storage` and `.env`, so a SQLite file under
# `database/` is replaced on every release, taking the shops and orders with
# it. MySQL in production, always.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=salesreport
DB_USERNAME=salesreport
DB_PASSWORD=

SESSION_DRIVER=database
SESSION_LIFETIME=120
Expand Down Expand Up @@ -77,3 +80,12 @@ WOOCOMMERCE_SYNC_OVERLAP_MINUTES=10
WOOCOMMERCE_SYNC_AFTER_MINUTES=15

VITE_APP_NAME="${APP_NAME}"

# Sign in with 3AG Accounts. Register this app as a client there
# (`php artisan db:seed --class=ClientSeeder` in the Accounts repo) and paste
# the id and secret it prints. THREE_AG_SSO_ONLY=true removes this app's own
# login, registration and password reset.
THREE_AG_BASE_URL=https://accounts.3ag.app
THREE_AG_CLIENT_ID=
THREE_AG_CLIENT_SECRET=
THREE_AG_SSO_ONLY=false
24 changes: 24 additions & 0 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,30 @@ jobs:
ci:
runs-on: ubuntu-latest

# Production runs MySQL. SQLite would wave through the constraints and
# column types the real engine enforces, so the suite uses the real engine.
services:
mysql:
image: mysql:8.4
env:
MYSQL_ALLOW_EMPTY_PASSWORD: 'yes'
MYSQL_DATABASE: salesreport
ports:
- 3306:3306
options: >-
--health-cmd="mysqladmin ping --silent"
--health-interval=10s
--health-timeout=5s
--health-retries=10

env:
DB_CONNECTION: mysql
DB_HOST: 127.0.0.1
DB_PORT: 3306
DB_DATABASE: salesreport
DB_USERNAME: root
DB_PASSWORD: ''

steps:
- name: Checkout code
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
Expand Down
97 changes: 97 additions & 0 deletions app/Http/Controllers/Auth/ThreeAgCallbackController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
<?php

namespace App\Http\Controllers\Auth;

use App\Http\Middleware\ThreeAgSingleSignOn;
use App\Http\Responses\Concerns\RedirectsToCurrentOrganization;
use App\Models\User;
use App\Services\Auth\ThreeAgProvider;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;
use Laravel\Fortify\Fortify;
use Laravel\Socialite\Two\InvalidStateException;
use Laravel\Socialite\Two\User as SocialiteUser;

/**
* Completes a sign-in that started at 3AG Accounts.
*/
class ThreeAgCallbackController
{
use RedirectsToCurrentOrganization;

public function __invoke(Request $request): RedirectResponse
{
$provider = ThreeAgProvider::resolve();

try {
$identity = $provider->user();
} catch (InvalidStateException) {
return redirect()->route('login')->withErrors([
'email' => 'That sign-in attempt expired. Please try again.',
]);
}

$user = $this->resolveUser($identity);

if ($user === null) {
return redirect()->route('login')->withErrors([
'email' => 'Your 3AG Accounts email address has not been verified yet.',
]);
}

Auth::login($user, remember: true);

$request->session()->regenerate();
$request->session()->put(ThreeAgSingleSignOn::ID_TOKEN, $provider->idToken());

return redirect()->intended(
$this->redirectPathForCurrentOrganization($request, Fortify::redirects('login'))
);
}

/**
* Find, link or create the local account behind the given identity.
*
* Returns null when the account cannot be trusted to belong to this
* person.
*/
protected function resolveUser(SocialiteUser $identity): ?User
{
$existing = User::query()->where('oidc_sub', $identity->getId())->first();

if ($existing instanceof User) {
return tap($existing)->update(['name' => $identity->getName()]);
}

// Matching an existing local account by email is only safe once the
// provider says it owns that address; otherwise anyone who can set an
// unverified email at the provider could claim someone else's account.
if (! ($identity->user['email_verified'] ?? false)) {
return null;
}

$byEmail = User::query()->where('email', $identity->getEmail())->first();

if ($byEmail instanceof User) {
$byEmail->forceFill([
'oidc_sub' => $identity->getId(),
'email_verified_at' => $byEmail->email_verified_at ?? now(),
])->save();

return $byEmail;
}

return tap(User::query()->create([
'name' => $identity->getName() ?? $identity->getEmail(),
'email' => $identity->getEmail(),
'password' => Str::password(32),
]), function (User $user) use ($identity): void {
$user->forceFill([
'oidc_sub' => $identity->getId(),
'email_verified_at' => now(),
])->save();
});
}
}
18 changes: 18 additions & 0 deletions app/Http/Controllers/Auth/ThreeAgRedirectController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php

namespace App\Http\Controllers\Auth;

use Illuminate\Http\RedirectResponse;
use Laravel\Socialite\Facades\Socialite;
use Symfony\Component\HttpFoundation\RedirectResponse as SymfonyRedirectResponse;

/**
* Sends the user to 3AG Accounts to sign in.
*/
class ThreeAgRedirectController
{
public function __invoke(): RedirectResponse|SymfonyRedirectResponse
{
return Socialite::driver('3ag')->redirect();
}
}
73 changes: 73 additions & 0 deletions app/Http/Middleware/ThreeAgSingleSignOn.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

/**
* Keeps this app's session in step with 3AG Accounts.
*
* Two jobs, both about the boundary between the local session and the identity
* provider's: carrying the ID token past the point where logging out destroys
* the session, and — once SSO is the only way in — closing the local routes
* that would let someone sign in without the provider.
*/
class ThreeAgSingleSignOn
{
/**
* The session key holding the ID token from the last sign-in.
*/
public const ID_TOKEN = '3ag.id_token';

/**
* Routes that offer a local alternative to signing in with 3AG.
*
* @var array<int, string>
*/
protected const REDIRECTED = [
'login',
'register',
'password.request',
'password.reset',
];

/**
* Routes that would authenticate or enrol someone without the provider.
*
* @var array<int, string>
*/
protected const BLOCKED = [
'login.store',
'register.store',
'password.email',
'password.update',
];

/**
* Handle an incoming request.
*
* @param Closure(Request): Response $next
*/
public function handle(Request $request, Closure $next): Response
{
// Fortify invalidates the session before the logout response is built,
// so the ID token has to be lifted out of it first.
if ($request->routeIs('logout')) {
$request->attributes->set(self::ID_TOKEN, $request->session()->get(self::ID_TOKEN));
}

if (! config('services.3ag.sso_only')) {
return $next($request);
}

if ($request->routeIs(...self::REDIRECTED)) {
return redirect()->route('auth.accounts.redirect');
}

abort_if($request->routeIs(...self::BLOCKED), Response::HTTP_NOT_FOUND);

return $next($request);
}
}
36 changes: 36 additions & 0 deletions app/Http/Responses/LogoutResponse.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<?php

namespace App\Http\Responses;

use App\Http\Middleware\ThreeAgSingleSignOn;
use App\Services\Auth\ThreeAgProvider;
use Illuminate\Http\JsonResponse;
use Laravel\Fortify\Contracts\LogoutResponse as LogoutResponseContract;
use Laravel\Fortify\Fortify;
use Symfony\Component\HttpFoundation\Response;

/**
* Ends the session at 3AG Accounts as well as here.
*
* Without this, signing out of this app and then signing back in would silently
* reuse the still-open session at the identity provider, which is not what
* anyone means by "log out".
*
* Only sign-ins that came from the provider divert; everything else keeps
* Fortify's own behaviour, JSON branch included.
*/
class LogoutResponse implements LogoutResponseContract
{
public function toResponse($request): Response
{
$idToken = $request->attributes->get(ThreeAgSingleSignOn::ID_TOKEN);

if (config('services.3ag.sso_only') && $idToken !== null) {
return redirect()->away(ThreeAgProvider::resolve()->logoutUrl($idToken));
}

return $request->wantsJson()
? new JsonResponse('', 204)
: redirect(Fortify::redirects('logout', '/'));
}
}
13 changes: 13 additions & 0 deletions app/Providers/AppServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@

namespace App\Providers;

use App\Services\Auth\ThreeAgProvider;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\Date;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\ServiceProvider;
use Illuminate\Validation\Rules\Password;
use Laravel\Socialite\Facades\Socialite;

class AppServiceProvider extends ServiceProvider
{
Expand All @@ -24,6 +26,17 @@ public function register(): void
public function boot(): void
{
$this->configureDefaults();
$this->configureSingleSignOn();
}

/**
* Register 3AG Accounts as a Socialite driver.
*/
protected function configureSingleSignOn(): void
{
Socialite::extend('3ag', fn ($app) => Socialite::buildProvider(
ThreeAgProvider::class, $app['config']['services.3ag']
));
}

/**
Expand Down
3 changes: 3 additions & 0 deletions app/Providers/FortifyServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use App\Actions\Fortify\CreateNewUser;
use App\Actions\Fortify\ResetUserPassword;
use App\Http\Responses\LoginResponse;
use App\Http\Responses\LogoutResponse;
use App\Http\Responses\PasskeyLoginResponse;
use App\Http\Responses\RegisterResponse;
use App\Http\Responses\TwoFactorLoginResponse;
Expand All @@ -17,6 +18,7 @@
use Illuminate\Support\Str;
use Inertia\Inertia;
use Laravel\Fortify\Contracts\LoginResponse as LoginResponseContract;
use Laravel\Fortify\Contracts\LogoutResponse as LogoutResponseContract;
use Laravel\Fortify\Contracts\RegisterResponse as RegisterResponseContract;
use Laravel\Fortify\Contracts\TwoFactorLoginResponse as TwoFactorLoginResponseContract;
use Laravel\Fortify\Contracts\VerifyEmailResponse as VerifyEmailResponseContract;
Expand All @@ -32,6 +34,7 @@ class FortifyServiceProvider extends ServiceProvider
public function register(): void
{
$this->app->singleton(LoginResponseContract::class, LoginResponse::class);
$this->app->singleton(LogoutResponseContract::class, LogoutResponse::class);
$this->app->singleton(PasskeyLoginResponseContract::class, PasskeyLoginResponse::class);
$this->app->singleton(RegisterResponseContract::class, RegisterResponse::class);
$this->app->singleton(TwoFactorLoginResponseContract::class, TwoFactorLoginResponse::class);
Expand Down
Loading
Loading