The dual-cookie machinery (crewli_app_token + crewli_portal_token, Origin-based resolution) was load-bearing only when the second SPA existed. apps/portal/ was deleted in WS-3 PR-B1; the resolver code has been carrying dead branches since then. Collapse to one cookie. Cookie name retained as crewli_app_token — no session breakage on deploy. crewli_portal_token is fully purged from the server-side. CookieBearerToken middleware: - COOKIE_NAMES array → single COOKIE_NAME constant - resolveCookieName method (Origin/Referer parsing, host+port matching against frontend_app_url/frontend_portal_url) → removed - Body collapses to: skip if Authorization header present; else read crewli_app_token cookie and inject Bearer header SetAuthCookie trait: - COOKIE_MAP / resolveCookieName / originMatches → removed - makeAuthCookie / forgetAuthCookie now take only $token; the cookie name is the trait's private constant Five callers updated to drop the resolveCookieName($request) line and the cookie-name argument: LoginController (3 sites), MfaVerifyController (1 site), AuthRefreshController (1 site), LogoutController (1 site), InvitationController (1 site — caller list in the prompt missed this one but the same pattern applies). frontend_portal_url config key retained (per Phase A directive Q1): EmailChangeController, PasswordResetController, PersonController are non-auth consumers that build per-app URL maps for outbound emails. The map structure is now functionally redundant (production resolves all FRONTEND_* env vars to the same host) but stays structurally intact. Refactor tracked as TECH-FRONTEND-URL-CONSOLIDATE in the upcoming docs commit. HttpOnlyCookieAuthTest: - Removed 4 dual-cookie tests (login_sets_portal_cookie_for_portal_origin, app_cookie_does_not_authenticate_portal_requests, portal_cookie_does_not_authenticate_app_requests, correct_cookie_authenticates_with_matching_origin) - Renamed login_sets_app_cookie_for_unknown_origin → login_sets_app_cookie_regardless_of_origin; expanded to four Origin variants (none, app, unknown, foreign) — pins the new origin-agnostic contract - Removed Origin headers from request calls in remaining tests (now meaningless) Backend test count: 1491 → 1487 (-4 deleted, dual-cookie tests encoding the obsolete contract). Pint clean. Larastan clean. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
108 lines
3.8 KiB
PHP
108 lines
3.8 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Http\Controllers\Api\V1;
|
|
|
|
use App\Enums\MfaMethod;
|
|
use App\Http\Controllers\Api\V1\Traits\SetAuthCookie;
|
|
use App\Http\Controllers\Controller;
|
|
use App\Http\Requests\Api\V1\LoginRequest;
|
|
use App\Http\Resources\Api\V1\MeResource;
|
|
use App\Models\User;
|
|
use App\Services\MfaService;
|
|
use Illuminate\Http\JsonResponse;
|
|
use Illuminate\Support\Facades\Hash;
|
|
use Illuminate\Support\Facades\Log;
|
|
|
|
final class LoginController extends Controller
|
|
{
|
|
use SetAuthCookie;
|
|
|
|
public function __construct(
|
|
private MfaService $mfaService,
|
|
) {}
|
|
|
|
public function __invoke(LoginRequest $request): JsonResponse
|
|
{
|
|
// Validate credentials WITHOUT creating a session.
|
|
// Auth::attempt() must NOT be used here — it establishes a Laravel
|
|
// session, which could grant access before MFA verification.
|
|
$user = User::where('email', $request->validated('email'))->first();
|
|
|
|
if (! $user || ! Hash::check($request->validated('password'), $user->password)) {
|
|
Log::warning('Failed login attempt', [
|
|
'email' => $request->validated('email'),
|
|
'ip' => $request->ip(),
|
|
'user_agent' => $request->userAgent(),
|
|
]);
|
|
|
|
return $this->unauthorized('Invalid credentials');
|
|
}
|
|
|
|
// MFA enabled and confirmed — check trusted device or require MFA
|
|
if ($user->mfa_enabled && $user->mfa_confirmed_at) {
|
|
$fingerprint = $request->header('X-Device-Fingerprint');
|
|
if ($fingerprint && $this->mfaService->isDeviceTrusted($user, $fingerprint)) {
|
|
return $this->issueToken($user, $request);
|
|
}
|
|
|
|
// Revoke ALL existing tokens so old sessions cannot bypass MFA.
|
|
// The only way to get a new token is through MfaVerifyController
|
|
// after a successful code verification.
|
|
$user->tokens()->delete();
|
|
|
|
$mfaSession = $this->mfaService->createMfaSession($user, $request->ip());
|
|
|
|
// Auto-send email code if email is the preferred method
|
|
if ($user->mfa_method === MfaMethod::EMAIL->value) {
|
|
try {
|
|
$this->mfaService->sendEmailCode($user);
|
|
} catch (\DomainException) {
|
|
// Rate limited — code was already sent recently
|
|
}
|
|
}
|
|
|
|
// Return MFA challenge — NO auth token, NO auth cookie.
|
|
// Expire the auth cookie to invalidate any stale browser session.
|
|
return response()->json([
|
|
'success' => true,
|
|
'mfa_required' => true,
|
|
...$mfaSession,
|
|
])->withCookie($this->forgetAuthCookie());
|
|
}
|
|
|
|
// MFA required by policy but not yet set up — issue token with flag
|
|
if ($this->mfaService->isMfaRequired($user) && ! $user->mfa_enabled) {
|
|
$response = $this->issueToken($user, $request);
|
|
$data = $response->getData(true);
|
|
$data['mfa_setup_required'] = true;
|
|
|
|
$token = $user->createToken('auth-token')->plainTextToken;
|
|
|
|
return response()->json($data)
|
|
->withCookie($this->makeAuthCookie($token));
|
|
}
|
|
|
|
// No MFA — issue token as normal
|
|
return $this->issueToken($user, $request);
|
|
}
|
|
|
|
private function issueToken(User $user, LoginRequest $request): JsonResponse
|
|
{
|
|
$user->load([
|
|
'organisations',
|
|
'roles',
|
|
'permissions',
|
|
'persons' => fn ($q) => $q->with(['event:id,name,slug,start_date,end_date,organisation_id', 'event.organisation:id,name']),
|
|
]);
|
|
|
|
$token = $user->createToken('auth-token')->plainTextToken;
|
|
|
|
return $this->success([
|
|
'user' => new MeResource($user),
|
|
], 'Login successful')
|
|
->withCookie($this->makeAuthCookie($token));
|
|
}
|
|
}
|