From f845c9001bd6026918db855ecc59de51ba272300 Mon Sep 17 00:00:00 2001 From: Gregor Vostrak Date: Mon, 26 Oct 2026 13:52:22 +0100 Subject: [PATCH] Add core support for extendable authentication and passwordless user creation --- app/Actions/Fortify/CreateNewUser.php | 29 ++-- app/Actions/Fortify/ResetUserPassword.php | 14 ++ app/Actions/Fortify/UpdateUserPassword.php | 9 ++ .../Commands/Admin/UserCreateCommand.php | 14 +- app/Events/BeforeUserDeletion.php | 20 +++ .../UserResource/Pages/CreateUser.php | 14 +- .../Controllers/Api/V1/UserController.php | 10 +- .../Web/OtherBrowserSessionsController.php | 23 ++- app/Http/Controllers/Web/UserController.php | 13 +- .../Requests/V1/Concerns/ConfirmsIdentity.php | 59 ++++++++ .../OrganizationDestroyRequest.php | 24 +-- .../Requests/V1/User/UserDestroyRequest.php | 24 +-- .../Requests/V1/User/UserUpdateRequest.php | 14 +- app/Http/Resources/V1/User/UserResource.php | 6 + app/Models/User.php | 30 +++- app/Providers/AppServiceProvider.php | 2 + app/Providers/FortifyServiceProvider.php | 28 +++- app/Service/AuthenticationContract.php | 45 ++++++ app/Service/DeletionService.php | 3 + app/Service/IdentityConfirmationService.php | 35 +++++ app/Service/InvitationService.php | 1 + app/Service/UserService.php | 24 ++- config/auth.php | 6 +- e2e/organization.spec.ts | 23 +++ e2e/profile.spec.ts | 38 +++++ .../IdentityConfirmationInput.vue | 41 ++++++ resources/js/Pages/Auth/Login.vue | 24 ++- .../Pages/Profile/Partials/DeleteUserForm.vue | 44 +++--- .../LogoutOtherBrowserSessionsForm.vue | 68 +++++---- .../Partials/UpdateProfileInformationForm.vue | 12 +- resources/js/Pages/Profile/Show.vue | 54 +++++-- .../Pages/Teams/Partials/DeleteTeamForm.vue | 41 +++--- resources/js/Pages/Teams/Show.vue | 11 +- resources/js/app.ts | 76 +++++++--- .../packages/api/src/openapi.json.client.ts | 8 +- tests/Feature/AuthenticationTest.php | 65 +++++++++ tests/Feature/PasswordConfirmationTest.php | 35 +++++ tests/Feature/PasswordResetTest.php | 34 +++++ tests/Feature/UpdatePasswordTest.php | 39 +++++ tests/TestCase.php | 11 ++ .../Api/V1/OrganizationEndpointTest.php | 20 +++ .../Unit/Endpoint/Api/V1/UserEndpointTest.php | 115 +++++++++++++++ .../Web/OtherBrowserSessionsEndpointTest.php | 63 ++++++++ tests/Unit/Endpoint/Web/UserEndpointTest.php | 32 ++++ tests/Unit/Models/UserTest.php | 87 +++++++++++ tests/Unit/Service/DeletionServiceTest.php | 4 + .../IdentityConfirmationServiceTest.php | 93 ++++++++++++ tests/Unit/Service/UserServiceTest.php | 137 ++++++++++++++++++ tsconfig.json | 2 + 49 files changed, 1431 insertions(+), 193 deletions(-) create mode 100644 app/Events/BeforeUserDeletion.php create mode 100644 app/Http/Requests/V1/Concerns/ConfirmsIdentity.php create mode 100644 app/Service/AuthenticationContract.php create mode 100644 app/Service/IdentityConfirmationService.php create mode 100644 resources/js/Components/Common/IdentityConfirmation/IdentityConfirmationInput.vue create mode 100644 tests/Unit/Models/UserTest.php create mode 100644 tests/Unit/Service/IdentityConfirmationServiceTest.php diff --git a/app/Actions/Fortify/CreateNewUser.php b/app/Actions/Fortify/CreateNewUser.php index 7f36236e..4a4975c1 100644 --- a/app/Actions/Fortify/CreateNewUser.php +++ b/app/Actions/Fortify/CreateNewUser.php @@ -8,6 +8,7 @@ use App\Enums\RegistrationMode; use App\Enums\Weekday; use App\Events\NewsletterRegistered; use App\Models\User; +use App\Service\AuthenticationContract; use App\Service\InvitationService; use App\Service\IpLookup\IpLookupServiceContract; use App\Service\TimezoneService; @@ -40,6 +41,12 @@ class CreateNewUser implements CreatesNewUsers ]); } + if (! app(AuthenticationContract::class)->isPasswordRegistrationAllowed()) { + throw ValidationException::withMessages([ + 'email' => [__(AuthenticationContract::PASSWORD_REGISTRATION_DISABLED_MESSAGE)], + ]); + } + $validated = Validator::make($input, [ 'name' => [ 'required', @@ -109,17 +116,17 @@ class CreateNewUser implements CreatesNewUsers DB::transaction(function () use (&$user, $input, $timezone, $startOfWeek, $currency, $numberFormat, $currencyFormat, $dateFormat, $intervalFormat, $timeFormat): void { $userService = app(UserService::class); $user = $userService->createUser( - $input['name'], - $input['email'], - $input['password'], - $timezone ?? 'UTC', - $startOfWeek, - $currency, - $numberFormat, - $currencyFormat, - $dateFormat, - $intervalFormat, - $timeFormat + name: $input['name'], + email: $input['email'], + password: $input['password'], + timezone: $timezone ?? 'UTC', + weekStart: $startOfWeek, + currency: $currency, + numberFormat: $numberFormat, + currencyFormat: $currencyFormat, + dateFormat: $dateFormat, + intervalFormat: $intervalFormat, + timeFormat: $timeFormat, ); }); diff --git a/app/Actions/Fortify/ResetUserPassword.php b/app/Actions/Fortify/ResetUserPassword.php index bed8016d..21574669 100644 --- a/app/Actions/Fortify/ResetUserPassword.php +++ b/app/Actions/Fortify/ResetUserPassword.php @@ -5,8 +5,12 @@ declare(strict_types=1); namespace App\Actions\Fortify; use App\Models\User; +use App\Service\AuthenticationContract; +use Illuminate\Auth\Passwords\PasswordBroker; use Illuminate\Support\Facades\Hash; +use Illuminate\Support\Facades\Password; use Illuminate\Support\Facades\Validator; +use Illuminate\Validation\ValidationException; use Laravel\Fortify\Contracts\ResetsUserPasswords; class ResetUserPassword implements ResetsUserPasswords @@ -20,6 +24,16 @@ class ResetUserPassword implements ResetsUserPasswords */ public function reset(User $user, array $input): void { + if (! app(AuthenticationContract::class)->isPasswordLoginAllowed($user)) { + /** @var PasswordBroker $broker */ + $broker = Password::broker(config('fortify.passwords')); + $broker->deleteToken($user); + + throw ValidationException::withMessages([ + 'email' => [__('This password reset link is invalid.')], + ]); + } + Validator::make($input, [ 'password' => $this->passwordRules(), ])->validate(); diff --git a/app/Actions/Fortify/UpdateUserPassword.php b/app/Actions/Fortify/UpdateUserPassword.php index 27951604..d7d70ed8 100644 --- a/app/Actions/Fortify/UpdateUserPassword.php +++ b/app/Actions/Fortify/UpdateUserPassword.php @@ -5,8 +5,10 @@ declare(strict_types=1); namespace App\Actions\Fortify; use App\Models\User; +use App\Service\IdentityConfirmationService; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Validator; +use Illuminate\Validation\ValidationException; use Laravel\Fortify\Contracts\UpdatesUserPasswords; class UpdateUserPassword implements UpdatesUserPasswords @@ -20,6 +22,13 @@ class UpdateUserPassword implements UpdatesUserPasswords */ public function update(User $user, array $input): void { + // Users who may not log in with their password (e.g. SSO) have no password to change + if (! app(IdentityConfirmationService::class)->confirmsWithPassword($user)) { + throw ValidationException::withMessages([ + 'current_password' => [__('Your account has no password to confirm this with. Contact your administrator.')], + ])->errorBag('updatePassword'); + } + Validator::make($input, [ 'current_password' => ['required', 'string', 'current_password:web'], 'password' => $this->passwordRules(), diff --git a/app/Console/Commands/Admin/UserCreateCommand.php b/app/Console/Commands/Admin/UserCreateCommand.php index 43670d09..da4cb308 100644 --- a/app/Console/Commands/Admin/UserCreateCommand.php +++ b/app/Console/Commands/Admin/UserCreateCommand.php @@ -59,13 +59,13 @@ class UserCreateCommand extends Command $user = null; DB::transaction(function () use (&$user, $name, $email, $password, $verifyEmail): void { $user = app(UserService::class)->createUser( - $name, - $email, - $password, - 'UTC', - Weekday::Monday, - null, - verifyEmail: $verifyEmail + name: $name, + email: $email, + password: $password, + timezone: 'UTC', + weekStart: Weekday::Monday, + currency: null, + verifyEmail: $verifyEmail, ); }); /** @var Organization|null $organization */ diff --git a/app/Events/BeforeUserDeletion.php b/app/Events/BeforeUserDeletion.php new file mode 100644 index 00000000..e926cdef --- /dev/null +++ b/app/Events/BeforeUserDeletion.php @@ -0,0 +1,20 @@ +user = $user; + } +} diff --git a/app/Filament/Resources/UserResource/Pages/CreateUser.php b/app/Filament/Resources/UserResource/Pages/CreateUser.php index 831eadcd..291c43a1 100644 --- a/app/Filament/Resources/UserResource/Pages/CreateUser.php +++ b/app/Filament/Resources/UserResource/Pages/CreateUser.php @@ -18,13 +18,13 @@ class CreateUser extends CreateRecord { $userService = app(UserService::class); $user = $userService->createUser( - $data['name'], - $data['email'], - $data['password_create'], - $data['timezone'], - $data['week_start'] instanceof Weekday ? $data['week_start'] : Weekday::from($data['week_start']), - $data['currency'], - verifyEmail: (bool) $data['is_email_verified'] + name: $data['name'], + email: $data['email'], + password: $data['password_create'], + timezone: $data['timezone'], + weekStart: $data['week_start'] instanceof Weekday ? $data['week_start'] : Weekday::from($data['week_start']), + currency: $data['currency'], + verifyEmail: (bool) $data['is_email_verified'], ); return $user; diff --git a/app/Http/Controllers/Api/V1/UserController.php b/app/Http/Controllers/Api/V1/UserController.php index 4d1dd3e9..a99102e4 100644 --- a/app/Http/Controllers/Api/V1/UserController.php +++ b/app/Http/Controllers/Api/V1/UserController.php @@ -13,6 +13,7 @@ use App\Http\Resources\V1\User\UserResource; use App\Mail\VerifyUpdatedEmailMail; use App\Models\Organization; use App\Models\User; +use App\Service\AuthenticationContract; use App\Service\DeletionService; use App\Service\UserService; use App\Support\Base64File; @@ -21,6 +22,7 @@ use Illuminate\Http\JsonResponse; use Illuminate\Support\Facades\Mail; use Illuminate\Support\Facades\Storage; use Illuminate\Support\Str; +use Illuminate\Validation\ValidationException; class UserController extends Controller { @@ -167,8 +169,9 @@ class UserController extends Controller * * @throws AuthorizationException Thrown when the authenticated user does not match the user whose email is pending verification. * @throws UserResendEmailVerificationNoPendingEmailApiException Thrown when the user does not have a pending email to verify. + * @throws ValidationException Thrown when the user's email is locked, e.g. managed by their organization's identity provider. */ - public function resendEmailVerification(User $user): JsonResponse + public function resendEmailVerification(User $user, AuthenticationContract $authentication): JsonResponse { if ($user->getKey() !== $this->user()->getKey()) { throw new AuthorizationException; @@ -178,6 +181,11 @@ class UserController extends Controller throw new UserResendEmailVerificationNoPendingEmailApiException; } + // A change requested before the email was locked can no longer be confirmed. + if (! $authentication->canChangeEmail($user)) { + throw ValidationException::withMessages(['email' => AuthenticationContract::EMAIL_CHANGE_LOCKED_MESSAGE]); + } + Mail::to($user->pending_email) ->queue(new VerifyUpdatedEmailMail($user, $user->pending_email)); diff --git a/app/Http/Controllers/Web/OtherBrowserSessionsController.php b/app/Http/Controllers/Web/OtherBrowserSessionsController.php index 0ad71ce7..9393abb2 100644 --- a/app/Http/Controllers/Web/OtherBrowserSessionsController.php +++ b/app/Http/Controllers/Web/OtherBrowserSessionsController.php @@ -4,6 +4,8 @@ declare(strict_types=1); namespace App\Http\Controllers\Web; +use App\Models\User; +use App\Service\IdentityConfirmationService; use Illuminate\Contracts\Auth\StatefulGuard; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; @@ -17,8 +19,27 @@ class OtherBrowserSessionsController extends Controller /** * Log the user out of their other browser sessions across all devices. */ - public function destroy(Request $request, StatefulGuard $guard): RedirectResponse + public function destroy(Request $request, StatefulGuard $guard, IdentityConfirmationService $identityConfirmationService): RedirectResponse { + /** @var User $user */ + $user = $request->user(); + + // Users who can't confirm with a password (e.g. SSO) may log out other sessions without confirming. + // Someone with a stolen session could only end the user's other sessions, while asking for a + // confirmation would keep the user from ending the stolen one. + if (! $identityConfirmationService->confirmsWithPassword($user)) { + // Without a password to rehash, other sessions can only be removed from the database + if (config('session.driver') !== 'database') { + throw ValidationException::withMessages([ + 'password' => __('Signing out other sessions is unavailable on this instance. Contact your administrator.'), + ]); + } + + $this->deleteOtherSessionRecords($request); + + return back(303); + } + $password = (string) $request->string('password'); $confirmed = app(ConfirmPassword::class)($guard, $request->user(), $password); diff --git a/app/Http/Controllers/Web/UserController.php b/app/Http/Controllers/Web/UserController.php index 0b400985..6ec99604 100644 --- a/app/Http/Controllers/Web/UserController.php +++ b/app/Http/Controllers/Web/UserController.php @@ -5,6 +5,7 @@ declare(strict_types=1); namespace App\Http\Controllers\Web; use App\Models\User; +use App\Service\AuthenticationContract; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; use Illuminate\Support\Carbon; @@ -12,7 +13,7 @@ use Illuminate\Support\Str; class UserController extends Controller { - public function verifyEmailChange(Request $request, User $user): RedirectResponse + public function verifyEmailChange(Request $request, User $user, AuthenticationContract $authentication): RedirectResponse { if ($request->user()?->getAuthIdentifier() !== $user->getKey()) { abort(403); @@ -29,6 +30,16 @@ class UserController extends Controller abort(403); } + // A change requested before the email was locked can no longer be confirmed. + if (! $authentication->canChangeEmail($user)) { + $user->pending_email = null; + $user->save(); + + return redirect(route('dashboard')) + ->with('bannerStyle', 'danger') + ->with('bannerText', AuthenticationContract::EMAIL_CHANGE_LOCKED_MESSAGE); + } + $emailAlreadyInUse = User::query() ->where('email', '=', $email) ->where('is_placeholder', '=', false) diff --git a/app/Http/Requests/V1/Concerns/ConfirmsIdentity.php b/app/Http/Requests/V1/Concerns/ConfirmsIdentity.php new file mode 100644 index 00000000..df7b893b --- /dev/null +++ b/app/Http/Requests/V1/Concerns/ConfirmsIdentity.php @@ -0,0 +1,59 @@ +> + */ + protected function identityConfirmationRules(): array + { + $user = $this->user(); + $requiresPassword = ! $user instanceof User + || app(IdentityConfirmationService::class)->confirmsWithPassword($user); + + return [ + 'password' => [ + $requiresPassword ? 'required' : 'nullable', + 'string', + ], + ]; + } + + protected function validateIdentityConfirmation(Validator $validator): void + { + if ($validator->errors()->has('password')) { + return; + } + + $user = $this->user(); + if (! $user instanceof User) { + $validator->errors()->add('password', __('The password is incorrect.')); + + return; + } + + if (! app(IdentityConfirmationService::class)->confirmsWithPassword($user)) { + $validator->errors()->add('password', __('Your account has no password to confirm this with. Contact your administrator.')); + + return; + } + + $password = $this->input('password'); + + if (! is_string($password) || ! Hash::check($password, (string) $user->password)) { + $validator->errors()->add('password', __('The password is incorrect.')); + } + } +} diff --git a/app/Http/Requests/V1/Organization/OrganizationDestroyRequest.php b/app/Http/Requests/V1/Organization/OrganizationDestroyRequest.php index b8f8686c..6a2432bf 100644 --- a/app/Http/Requests/V1/Organization/OrganizationDestroyRequest.php +++ b/app/Http/Requests/V1/Organization/OrganizationDestroyRequest.php @@ -5,11 +5,13 @@ declare(strict_types=1); namespace App\Http\Requests\V1\Organization; use App\Http\Requests\V1\BaseFormRequest; -use Illuminate\Support\Facades\Hash; +use App\Http\Requests\V1\Concerns\ConfirmsIdentity; use Illuminate\Validation\Validator; class OrganizationDestroyRequest extends BaseFormRequest { + use ConfirmsIdentity; + /** * Get the validation rules that apply to the request. * @@ -17,12 +19,7 @@ class OrganizationDestroyRequest extends BaseFormRequest */ public function rules(): array { - return [ - 'password' => [ - 'required', - 'string', - ], - ]; + return $this->identityConfirmationRules(); } /** @@ -31,18 +28,7 @@ class OrganizationDestroyRequest extends BaseFormRequest public function after(): array { return [ - function (Validator $validator): void { - if ($validator->errors()->has('password')) { - return; - } - - $user = $this->user(); - $password = $this->input('password'); - - if (! is_string($password) || $user === null || ! Hash::check($password, (string) $user->password)) { - $validator->errors()->add('password', __('The password is incorrect.')); - } - }, + fn (Validator $validator) => $this->validateIdentityConfirmation($validator), ]; } } diff --git a/app/Http/Requests/V1/User/UserDestroyRequest.php b/app/Http/Requests/V1/User/UserDestroyRequest.php index 2a86fd18..f0951e92 100644 --- a/app/Http/Requests/V1/User/UserDestroyRequest.php +++ b/app/Http/Requests/V1/User/UserDestroyRequest.php @@ -5,11 +5,13 @@ declare(strict_types=1); namespace App\Http\Requests\V1\User; use App\Http\Requests\V1\BaseFormRequest; -use Illuminate\Support\Facades\Hash; +use App\Http\Requests\V1\Concerns\ConfirmsIdentity; use Illuminate\Validation\Validator; class UserDestroyRequest extends BaseFormRequest { + use ConfirmsIdentity; + /** * Get the validation rules that apply to the request. * @@ -17,12 +19,7 @@ class UserDestroyRequest extends BaseFormRequest */ public function rules(): array { - return [ - 'password' => [ - 'required', - 'string', - ], - ]; + return $this->identityConfirmationRules(); } /** @@ -31,18 +28,7 @@ class UserDestroyRequest extends BaseFormRequest public function after(): array { return [ - function (Validator $validator): void { - if ($validator->errors()->has('password')) { - return; - } - - $user = $this->user(); - $password = $this->input('password'); - - if (! is_string($password) || $user === null || ! Hash::check($password, (string) $user->password)) { - $validator->errors()->add('password', __('The password is incorrect.')); - } - }, + fn (Validator $validator) => $this->validateIdentityConfirmation($validator), ]; } } diff --git a/app/Http/Requests/V1/User/UserUpdateRequest.php b/app/Http/Requests/V1/User/UserUpdateRequest.php index e167b8ea..64f137ce 100644 --- a/app/Http/Requests/V1/User/UserUpdateRequest.php +++ b/app/Http/Requests/V1/User/UserUpdateRequest.php @@ -8,6 +8,8 @@ use App\Enums\Weekday; use App\Http\Requests\V1\BaseFormRequest; use App\Models\User; use App\Rules\Base64ImageRule; +use App\Service\AuthenticationContract; +use Closure; use Illuminate\Contracts\Validation\ValidationRule; use Illuminate\Database\Eloquent\Builder; use Illuminate\Support\Str; @@ -31,7 +33,7 @@ class UserUpdateRequest extends BaseFormRequest /** * Get the validation rules that apply to the request. * - * @return array> + * @return array> */ public function rules(): array { @@ -48,6 +50,16 @@ class UserUpdateRequest extends BaseFormRequest return $query->where('is_placeholder', '=', false) ->whereKeyNot($this->user->getKey()); }), + function (string $attribute, mixed $value, Closure $fail): void { + // Sending the current address back unchanged is not a change. + if (! is_string($value) || $value === Str::lower($this->user->email)) { + return; + } + + if (! app(AuthenticationContract::class)->canChangeEmail($this->user)) { + $fail(AuthenticationContract::EMAIL_CHANGE_LOCKED_MESSAGE); + } + }, ], 'photo' => [ 'nullable', diff --git a/app/Http/Resources/V1/User/UserResource.php b/app/Http/Resources/V1/User/UserResource.php index fb94ed17..2e09b5f5 100644 --- a/app/Http/Resources/V1/User/UserResource.php +++ b/app/Http/Resources/V1/User/UserResource.php @@ -7,6 +7,8 @@ namespace App\Http\Resources\V1\User; use App\Enums\Weekday; use App\Http\Resources\V1\BaseResource; use App\Models\User; +use App\Service\AuthenticationContract; +use App\Service\IdentityConfirmationService; use Illuminate\Http\Request; /** @@ -38,6 +40,10 @@ class UserResource extends BaseResource 'week_start' => $this->resource->week_start->value, /** Whether to email the user when a time entry has been running for more than 8 hours */ 'send_time_entry_still_running_email' => $this->resource->send_time_entry_still_running_email, + /** Whether the user confirms sensitive actions (like deleting their account) with their password. If not, an administrator has to do these actions for them. */ + 'confirms_with_password' => app(IdentityConfirmationService::class)->confirmsWithPassword($this->resource), + /** Whether the user may change their email address. If not, it is managed elsewhere (e.g. by the organization's identity provider). */ + 'can_change_email' => app(AuthenticationContract::class)->canChangeEmail($this->resource), ]; } } diff --git a/app/Models/User.php b/app/Models/User.php index 9cfd8b9d..23872a53 100644 --- a/app/Models/User.php +++ b/app/Models/User.php @@ -9,9 +9,11 @@ use App\Enums\Weekday; use App\Models\Concerns\CustomAuditable; use App\Models\Concerns\HasUuids; use App\Models\Passport\Token; +use App\Service\AuthenticationContract; use Database\Factories\UserFactory; use Filament\Models\Contracts\FilamentUser; use Filament\Panel; +use Illuminate\Auth\Notifications\ResetPassword; use Illuminate\Contracts\Auth\MustVerifyEmail; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Casts\Attribute; @@ -24,6 +26,7 @@ use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; use Illuminate\Support\Carbon; use Illuminate\Support\Facades\Storage; +use Illuminate\Support\Str; use Laravel\Fortify\TwoFactorAuthenticatable; use Laravel\Passport\AuthCode; use Laravel\Passport\Contracts\OAuthenticatable; @@ -160,13 +163,36 @@ class User extends Authenticatable implements AuditableContract, FilamentUser, M return 'https://ui-avatars.com/api/?name='.urlencode($name).'&color=7F9CF5&background=EBF4FF'; } - public function canAccessPanel(Panel $panel): bool + public function isSuperAdmin(): bool { return $this->is_placeholder === false - && in_array($this->email, config('auth.super_admins', []), true) + && in_array(Str::lower($this->email), config()->array('auth.super_admins'), true) && $this->hasVerifiedEmail(); } + /** + * Sends the reset link, unless the user may not use a password. The unsent token stays, so Fortify throttles + * them like everyone else and doesn't reveal SSO-only accounts; ResetUserPassword refuses it anyway. + */ + public function sendPasswordResetNotification(#[\SensitiveParameter] $token): void + { + if (! app(AuthenticationContract::class)->isPasswordLoginAllowed($this)) { + return; + } + + $this->notify(new ResetPassword($token)); + } + + public function hasLocalPassword(): bool + { + return is_string($this->password) && $this->password !== ''; + } + + public function canAccessPanel(Panel $panel): bool + { + return $this->isSuperAdmin(); + } + public function isMemberOfOrganization(Organization $organization): bool { if ($this->relationLoaded('organizations')) { diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php index d8580b3c..782a3bed 100644 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -16,6 +16,7 @@ use App\Models\Tag; use App\Models\Task; use App\Models\TimeEntry; use App\Models\User; +use App\Service\AuthenticationContract; use App\Service\BillingContract; use App\Service\GoalsContract; use App\Service\IpLookup\IpLookupServiceContract; @@ -109,6 +110,7 @@ class AppServiceProvider extends ServiceProvider $this->app->bind(IpLookupServiceContract::class, NoIpLookupService::class); $this->app->bind(BillingContract::class); $this->app->bind(GoalsContract::class); + $this->app->bind(AuthenticationContract::class); // Storage // The local driver ignores the ResponseContentDisposition option of temporaryUrl, diff --git a/app/Providers/FortifyServiceProvider.php b/app/Providers/FortifyServiceProvider.php index 7d39862f..4800c7df 100644 --- a/app/Providers/FortifyServiceProvider.php +++ b/app/Providers/FortifyServiceProvider.php @@ -11,6 +11,8 @@ use App\Actions\Fortify\UpdateUserProfileInformation; use App\Extensions\Fortify\CustomLoginResponse; use App\Extensions\Fortify\CustomTwoFactorLoginResponse; use App\Models\User; +use App\Service\AuthenticationContract; +use App\Service\IdentityConfirmationService; use Illuminate\Cache\RateLimiting\Limit; use Illuminate\Http\Request; use Illuminate\Support\Facades\Hash; @@ -25,6 +27,12 @@ use Laravel\Fortify\Fortify; class FortifyServiceProvider extends ServiceProvider { + /** + * Hash of a random value that is checked when no user exists for the email, + * so login takes the same time whether the email is registered or not. + */ + private const ABSENT_USER_PASSWORD_HASH = '$2y$12$PtSQLk/QWOJJpg42pGEkt.TTR7NwCq0.g/0EOWb2B6eDww4zR92.2'; + /** * Register any application services. */ @@ -44,6 +52,13 @@ class FortifyServiceProvider extends ServiceProvider Fortify::resetUserPasswordsUsing(ResetUserPassword::class); Fortify::registerView(function () { + if (! app(AuthenticationContract::class)->isPasswordRegistrationAllowed()) { + // Keeps flashed banners, like an invitation's "finish joining {org}", across the redirect. + session()->reflash(); + + return redirect()->route('login')->with('status', __(AuthenticationContract::PASSWORD_REGISTRATION_DISABLED_MESSAGE)); + } + return Inertia::render('Auth/Register', [ 'email' => session('registration_email', ''), 'terms_url' => config('auth.terms_url'), @@ -93,13 +108,24 @@ class FortifyServiceProvider extends ServiceProvider ->where('is_placeholder', '=', false) ->first(); - if ($user !== null && Hash::check($request->password, $user->password)) { + // Always check a hash so the response time doesn't reveal whether the user exists + $hasLocalPassword = $user !== null && $user->hasLocalPassword(); + $existingPasswordHash = $hasLocalPassword ? $user->password : self::ABSENT_USER_PASSWORD_HASH; + + $passwordIsValid = Hash::check((string) $request->password, $existingPasswordHash); + + if ($hasLocalPassword && $passwordIsValid && app(AuthenticationContract::class)->isPasswordLoginAllowed($user)) { return $user; } return null; }); + // Used by the password confirmation screen (e.g. before enabling 2FA) and OtherBrowserSessionsController + Fortify::confirmPasswordsUsing(function (mixed $user, ?string $password): bool { + return $user instanceof User && app(IdentityConfirmationService::class)->confirmPassword($user, $password); + }); + RateLimiter::for('login', function (Request $request) { $throttleKey = Str::transliterate(Str::lower($request->input(Fortify::username())).'|'.$request->ip()); diff --git a/app/Service/AuthenticationContract.php b/app/Service/AuthenticationContract.php new file mode 100644 index 00000000..96c9ab3c --- /dev/null +++ b/app/Service/AuthenticationContract.php @@ -0,0 +1,45 @@ +role === Role::Owner->value) { diff --git a/app/Service/IdentityConfirmationService.php b/app/Service/IdentityConfirmationService.php new file mode 100644 index 00000000..37bf429e --- /dev/null +++ b/app/Service/IdentityConfirmationService.php @@ -0,0 +1,35 @@ +hasLocalPassword() && app(AuthenticationContract::class)->isPasswordLoginAllowed($user); + } + + /** + * Whether the given password confirms the user's identity. + */ + public function confirmPassword(User $user, ?string $password): bool + { + return $password !== null + && $this->confirmsWithPassword($user) + && Hash::check($password, (string) $user->password); + } +} diff --git a/app/Service/InvitationService.php b/app/Service/InvitationService.php index c5d86451..71f7ced9 100644 --- a/app/Service/InvitationService.php +++ b/app/Service/InvitationService.php @@ -78,6 +78,7 @@ class InvitationService $invitations = OrganizationInvitation::query() ->whereRaw('lower(email) = ?', [strtolower($user->email)]) ->whereNotNull('accepted_at') + ->with('organization') ->get(); foreach ($invitations as $invitation) { diff --git a/app/Service/UserService.php b/app/Service/UserService.php index e430ecd3..77f406f8 100644 --- a/app/Service/UserService.php +++ b/app/Service/UserService.php @@ -26,10 +26,15 @@ use InvalidArgumentException; class UserService { + /** + * Create a user. Without a password, the user can only sign in another way (e.g. via SSO). + * The user joins the organizations of their accepted invitations. If an organization is given, + * they also join it; otherwise they get their own organization if no invitation placed them anywhere. + */ public function createUser( string $name, string $email, - string $password, + ?string $password, string $timezone, Weekday $weekStart, ?string $currency, @@ -38,12 +43,14 @@ class UserService ?DateFormat $dateFormat = null, ?IntervalFormat $intervalFormat = null, ?TimeFormat $timeFormat = null, - bool $verifyEmail = false + bool $verifyEmail = false, + ?Organization $organization = null, + Role $role = Role::Employee, ): User { $user = new User; $user->name = $name; $user->email = strtolower($email); - $user->password = Hash::make($password); + $user->password = $password !== null ? Hash::make($password) : null; $user->timezone = $timezone; $user->week_start = $weekStart; if ($verifyEmail) { @@ -51,9 +58,16 @@ class UserService } $user->save(); - $organizations = app(InvitationService::class)->processAcceptedInvitations($user); + $invitedOrganizations = app(InvitationService::class)->processAcceptedInvitations($user); - if ($organizations->isEmpty()) { + if ($organization !== null) { + // An accepted invitation may already have added the user to the organization + if ($invitedOrganizations->doesntContain(fn (Organization $invited): bool => $invited->is($organization))) { + app(MemberService::class)->addMember($user, $organization, $role); + } else { + $this->switchCurrentOrganization($user, $organization); + } + } elseif ($invitedOrganizations->isEmpty()) { $organization = app(OrganizationService::class)->createOrganization( $this->getOrganizationNameForUserName($user->name), $user, diff --git a/config/auth.php b/config/auth.php index c97823b3..c2ac039c 100644 --- a/config/auth.php +++ b/config/auth.php @@ -116,7 +116,11 @@ return [ 'password_timeout' => env('AUTH_PASSWORD_TIMEOUT', 10800), - 'super_admins' => ! is_string(env('SUPER_ADMINS', null)) ? [] : explode(',', env('SUPER_ADMINS')), + // Trimmed and lowercased, so a stray space or capital letter can't lock a super admin out. + 'super_admins' => array_values(array_filter(array_map( + fn (string $email): string => strtolower(trim($email)), + explode(',', (string) env('SUPER_ADMINS', '')), + ))), 'terms_url' => env('TERMS_URL', ''), diff --git a/e2e/organization.spec.ts b/e2e/organization.spec.ts index 9e2a46b2..39da3de3 100644 --- a/e2e/organization.spec.ts +++ b/e2e/organization.spec.ts @@ -511,6 +511,29 @@ test.describe('Organization Create, Delete & Switch', () => { await expect(dialog).toBeVisible(); }); + test('delete organization submits when pressing Enter in the password field', async ({ + page, + }) => { + const orgName = 'DeleteOrgEnter' + Math.floor(Math.random() * 100000); + await createOrganization(page, orgName); + await goToOrganizationSettings(page); + + await page.getByRole('button', { name: 'Delete Organization' }).click(); + const dialog = page.getByRole('dialog'); + await dialog.getByPlaceholder('Password').fill('not-the-real-password'); + await Promise.all([ + page.waitForResponse( + (response) => + response.url().includes('/api/v1/organizations') && + response.request().method() === 'DELETE' && + response.status() === 422 + ), + dialog.getByPlaceholder('Password').press('Enter'), + ]); + + await expect(dialog.getByRole('alert')).toBeVisible(); + }); + test('can switch the current organization via the organization switcher', async ({ page }) => { await page.goto(PLAYWRIGHT_BASE_URL + '/dashboard'); const orgSwitcher = page.locator('[data-testid="organization_switcher"]:visible'); diff --git a/e2e/profile.spec.ts b/e2e/profile.spec.ts index df695b89..6a2edc9a 100644 --- a/e2e/profile.spec.ts +++ b/e2e/profile.spec.ts @@ -411,6 +411,23 @@ test('delete account shows an error when the password is wrong', async ({ page } await expect(dialog).toBeVisible(); }); +test('delete account submits when pressing Enter in the password field', async ({ page }) => { + await goToProfilePage(page); + await page.getByRole('button', { name: 'Delete Account' }).click(); + const dialog = page.getByRole('dialog'); + await dialog.getByPlaceholder('Password').fill('not-the-real-password'); + await Promise.all([ + page.waitForResponse( + (response) => + response.url().includes('/api/v1/users/') && + response.request().method() === 'DELETE' && + response.status() === 422 + ), + dialog.getByPlaceholder('Password').press('Enter'), + ]); + await expect(dialog.getByRole('alert')).toBeVisible(); +}); + test('delete account succeeds with the correct password and logs the user out', async ({ page, }) => { @@ -764,6 +781,27 @@ test('test that 2FA can be enabled with correct password', async ({ page }) => { // Logout Other Browser Sessions Tests // ============================================= +test('test that logout other browser sessions shows an error when the password is wrong', async ({ + page, +}) => { + await goToProfilePage(page); + + await page.getByRole('button', { name: 'Log Out Other Browser Sessions' }).click(); + const dialog = page.getByRole('dialog'); + await dialog.getByPlaceholder('Password').fill('not-the-real-password'); + // Inertia validation errors redirect back instead of returning a 422. + await Promise.all([ + page.waitForResponse( + (response) => + response.url().includes('/user/other-browser-sessions') && + response.request().method() === 'DELETE' + ), + dialog.getByPlaceholder('Password').press('Enter'), + ]); + await expect(dialog.getByRole('alert')).toBeVisible(); + await expect(dialog).toBeVisible(); +}); + test('test that logout other browser sessions works with correct password', async ({ page }) => { await goToProfilePage(page); diff --git a/resources/js/Components/Common/IdentityConfirmation/IdentityConfirmationInput.vue b/resources/js/Components/Common/IdentityConfirmation/IdentityConfirmationInput.vue new file mode 100644 index 00000000..938011f8 --- /dev/null +++ b/resources/js/Components/Common/IdentityConfirmation/IdentityConfirmationInput.vue @@ -0,0 +1,41 @@ + + + diff --git a/resources/js/Pages/Auth/Login.vue b/resources/js/Pages/Auth/Login.vue index edfd8f62..b0bf3f5a 100644 --- a/resources/js/Pages/Auth/Login.vue +++ b/resources/js/Pages/Auth/Login.vue @@ -7,10 +7,16 @@ import { Field, FieldLabel, FieldError } from '@/packages/ui/src/field'; import PrimaryButton from '@/packages/ui/src/Buttons/PrimaryButton.vue'; import TextInput from '@/packages/ui/src/Input/TextInput.vue'; -defineProps({ - canResetPassword: Boolean, - status: String, -}); +withDefaults( + defineProps<{ + canResetPassword?: boolean; + status?: string; + }>(), + { + canResetPassword: false, + status: '', + } +); const form = useForm({ email: '', @@ -28,8 +34,8 @@ const submit = () => { }; const page = usePage<{ - flash: { - message: string; + flash?: { + message?: string; }; }>(); @@ -61,6 +67,9 @@ const page = usePage<{ {{ page.props.flash?.message }} + + +
Email @@ -103,5 +112,8 @@ const page = usePage<{ + + + diff --git a/resources/js/Pages/Profile/Partials/DeleteUserForm.vue b/resources/js/Pages/Profile/Partials/DeleteUserForm.vue index 7ebc199f..4d9491c8 100644 --- a/resources/js/Pages/Profile/Partials/DeleteUserForm.vue +++ b/resources/js/Pages/Profile/Partials/DeleteUserForm.vue @@ -1,29 +1,32 @@ @@ -55,8 +60,11 @@ const closeModal = () => {
If necessary, you may log out of all of your other browser sessions across all of your devices. Some of your recent sessions are listed below; however, this list may - not be exhaustive. If you feel your account has been compromised, you should also - update your password. + not be exhaustive. +
@@ -128,23 +136,21 @@ const closeModal = () => {