Merge remote-tracking branch 'origin/main' into feature/email-lowercase-fixes

# Conflicts:
#	app/Service/UserService.php
This commit is contained in:
Constantin Graf
2026-11-19 13:13:18 +01:00
68 changed files with 2235 additions and 200 deletions

View File

@@ -38,6 +38,12 @@ CACHE_DRIVER=file
# Queue
QUEUE_CONNECTION=sync
# Heartbeat (optional push/heartbeat monitor URLs to check that the scheduler and queue are running)
# The queue URL may contain the placeholder {latency_ms}, which is replaced with the queue latency.
# The queue heartbeat is skipped if the queue connection uses the sync driver.
# HEARTBEAT_SCHEDULER_URL=
# HEARTBEAT_QUEUE_URL=
# Session
SESSION_DRIVER=database
SESSION_LIFETIME=120

View File

@@ -105,6 +105,8 @@ jobs:
echo "invoicing_ref=$(jq -r '.Invoicing.ref' extensions/manifest.json)"
echo "auditing_repository=$(jq -r '.Auditing.repository' extensions/manifest.json)"
echo "auditing_ref=$(jq -r '.Auditing.ref' extensions/manifest.json)"
echo "sso_repository=$(jq -r '.SSO.repository' extensions/manifest.json)"
echo "sso_ref=$(jq -r '.SSO.ref' extensions/manifest.json)"
} >> "$GITHUB_OUTPUT"
- name: "Checkout invoicing extension"
@@ -135,12 +137,26 @@ jobs:
- name: "Install npm dependencies in auditing extension"
run: cd extensions/Auditing && npm ci
- name: "Checkout SSO extension"
uses: actions/checkout@v7
with:
repository: ${{ steps.extension-manifest.outputs.sso_repository }}
ref: ${{ steps.extension-manifest.outputs.sso_ref }}
path: extensions/SSO
ssh-key: ${{ secrets.SSH_PRIVATE_KEY_SSO_EXTENSION }}
- name: "Install composer dependencies in SSO extension"
run: cd extensions/SSO && composer install --no-dev --no-ansi --no-interaction --prefer-dist --ignore-platform-reqs --classmap-authoritative
- name: "Activate invoicing extension"
run: php artisan module:enable Invoicing
- name: "Activate auditing extension"
run: php artisan module:enable Auditing
- name: "Activate SSO extension"
run: php artisan module:enable SSO
- name: "Install npm dependencies"
run: npm ci

View File

@@ -87,6 +87,8 @@ jobs:
echo "invoicing_ref=$(jq -r '.Invoicing.ref' extensions/manifest.json)"
echo "auditing_repository=$(jq -r '.Auditing.repository' extensions/manifest.json)"
echo "auditing_ref=$(jq -r '.Auditing.ref' extensions/manifest.json)"
echo "sso_repository=$(jq -r '.SSO.repository' extensions/manifest.json)"
echo "sso_ref=$(jq -r '.SSO.ref' extensions/manifest.json)"
} >> "$GITHUB_OUTPUT"
- name: "Checkout billing extension"
@@ -167,6 +169,22 @@ jobs:
- name: "Install npm dependencies in auditing extension"
run: cd extensions/Auditing && npm ci
- name: "Checkout SSO extension"
uses: actions/checkout@v7
with:
repository: ${{ steps.extension-manifest.outputs.sso_repository }}
ref: ${{ steps.extension-manifest.outputs.sso_ref }}
path: extensions/SSO
ssh-key: ${{ secrets.SSH_PRIVATE_KEY_SSO_EXTENSION }}
- name: "Install composer dependencies in SSO extension"
uses: php-actions/composer@v6
with:
working_dir: "extensions/SSO"
command: install
only_args: --no-dev --no-ansi --no-interaction --prefer-dist --ignore-platform-reqs --classmap-authoritative
php_version: 8.3
- name: "Setup PHP with PECL extension"
uses: shivammathur/setup-php@v2
with:
@@ -193,6 +211,9 @@ jobs:
- name: "Activate auditing extension"
run: php artisan module:enable Auditing
- name: "Activate SSO extension"
run: php artisan module:enable SSO
- name: "Install npm dependencies"
run: npm ci

View File

@@ -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,
);
});

View File

@@ -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();

View File

@@ -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(),

View File

@@ -69,13 +69,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 */

View File

@@ -0,0 +1,82 @@
<?php
declare(strict_types=1);
namespace App\Console\Commands\Heartbeat;
use App\Jobs\HeartbeatQueueJob;
use Illuminate\Console\Command;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Throwable;
class HeartbeatSendCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'heartbeat:send';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Sends the scheduler heartbeat and dispatches the queue heartbeat job to the configured monitoring URLs.';
/**
* Execute the console command.
*/
public function handle(): int
{
$schedulerUrl = config('heartbeat.scheduler_url');
$queueUrl = config('heartbeat.queue_url');
if (! is_string($schedulerUrl) || $schedulerUrl === '') {
$schedulerUrl = null;
}
if (! is_string($queueUrl) || $queueUrl === '') {
$queueUrl = null;
}
if ($schedulerUrl === null && $queueUrl === null) {
$this->info('No heartbeat URLs configured, nothing to do.');
return self::SUCCESS;
}
if ($schedulerUrl !== null) {
try {
Http::timeout((int) config('heartbeat.timeout'))
->connectTimeout(2)
->get($schedulerUrl)
->throw();
$this->info('Scheduler heartbeat sent.');
} catch (Throwable $exception) {
Log::warning('Failed to send scheduler heartbeat', [
'exception' => $exception->getMessage(),
]);
$this->warn('Failed to send scheduler heartbeat, check the logs for more information.');
}
}
if ($queueUrl !== null) {
$queueConnection = config('queue.default');
if (config('queue.connections.'.$queueConnection.'.driver') === 'sync') {
// With the sync driver the job would run inline in the scheduler, so the heartbeat would not prove that a queue worker is running.
Log::warning('Skipped queue heartbeat, because the queue connection uses the sync driver', [
'queue_connection' => $queueConnection,
]);
$this->warn('Skipped queue heartbeat, because the queue connection uses the sync driver.');
} else {
HeartbeatQueueJob::dispatch(Carbon::now()->getTimestampMs());
$this->info('Queue heartbeat job dispatched.');
}
}
return self::SUCCESS;
}
}

View File

@@ -47,6 +47,11 @@ class Kernel extends ConsoleKernel
$schedule->command('self-host:database-consistency')
->when(fn (): bool => config('scheduling.tasks.self_hosting_database_consistency'))
->everySixHours();
$schedule->command('heartbeat:send')
->when(fn (): bool => filled(config('heartbeat.scheduler_url')) || filled(config('heartbeat.queue_url')))
->everyMinute()
->onOneServer();
}
/**

View File

@@ -0,0 +1,20 @@
<?php
declare(strict_types=1);
namespace App\Events;
use App\Models\User;
use Illuminate\Foundation\Events\Dispatchable;
class BeforeUserDeletion
{
use Dispatchable;
public User $user;
public function __construct(User $user)
{
$this->user = $user;
}
}

View File

@@ -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;

View File

@@ -31,6 +31,19 @@ class ReportController extends Controller
}
}
/**
* Public reports aggregate all time entries of the organization and are not scoped to the visibility of
* the user that created them, so only users that can see all projects and time entries may create or
* update (and thereby publish) reports.
*
* @throws AuthorizationException
*/
private function checkCanExposeOrganizationData(Organization $organization): void
{
$this->checkPermission($organization, 'projects:view:all');
$this->checkPermission($organization, 'time-entries:view:all');
}
/**
* Get reports
*
@@ -77,6 +90,7 @@ class ReportController extends Controller
public function store(Organization $organization, ReportStoreRequest $request, TimezoneService $timezoneService, ReportService $reportService): DetailedReportResource
{
$this->checkPermission($organization, 'reports:create');
$this->checkCanExposeOrganizationData($organization);
$user = $this->user();
$report = new Report;
@@ -136,6 +150,7 @@ class ReportController extends Controller
public function update(Organization $organization, Report $report, ReportUpdateRequest $request, ReportService $reportService): DetailedReportResource
{
$this->checkPermission($organization, 'reports:update', $report);
$this->checkCanExposeOrganizationData($organization);
if ($request->has('name')) {
$report->name = $request->getName();

View File

@@ -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));

View File

@@ -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);

View File

@@ -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)

View File

@@ -8,6 +8,7 @@ use App\Service\BillingContract;
use Illuminate\Http\Request;
use Inertia\Middleware;
use Nwidart\Modules\Facades\Module;
use STS\FilamentImpersonate\ImpersonateManager;
class HandleInertiaRequests extends Middleware
{
@@ -62,6 +63,7 @@ class HandleInertiaRequests extends Middleware
'goal_limit' => $billing->getGoalLimit($currentOrganization),
'can_use_billable_rates' => $billing->canUseBillableRates($currentOrganization),
] : null,
'is_impersonating' => app(ImpersonateManager::class)->isImpersonating(),
'flash' => [
'message' => fn () => $request->session()->get('message'),
'bannerText' => fn () => $request->session()->get('bannerText'),

View File

@@ -0,0 +1,59 @@
<?php
declare(strict_types=1);
namespace App\Http\Requests\V1\Concerns;
use App\Models\User;
use App\Service\IdentityConfirmationService;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Validator;
/**
* Requires the user's "password". Users who can't confirm with a password can't do the action themselves.
*/
trait ConfirmsIdentity
{
/**
* @return array<string, array<string>>
*/
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.'));
}
}
}

View File

@@ -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),
];
}
}

View File

@@ -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),
];
}
}

View File

@@ -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<string, array<string|\Illuminate\Contracts\Validation\Rule|ValidationRule>>
* @return array<string, array<string|\Illuminate\Contracts\Validation\Rule|ValidationRule|Closure>>
*/
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',

View File

@@ -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),
];
}
}

View File

@@ -0,0 +1,58 @@
<?php
declare(strict_types=1);
namespace App\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Throwable;
class HeartbeatQueueJob implements ShouldQueue
{
use Dispatchable;
use InteractsWithQueue;
use Queueable;
/**
* A heartbeat is not retried, since a retried heartbeat would be stale.
*/
public int $tries = 1;
/**
* @param int $dispatchedAtMs Unix timestamp in milliseconds of when the job was dispatched
*/
public function __construct(
public readonly int $dispatchedAtMs
) {}
/**
* Execute the job.
*/
public function handle(): void
{
$queueUrl = config('heartbeat.queue_url');
if (! is_string($queueUrl) || $queueUrl === '') {
return;
}
$latencyMs = max(0, Carbon::now()->getTimestampMs() - $this->dispatchedAtMs);
$url = str_replace('{latency_ms}', (string) $latencyMs, $queueUrl);
try {
Http::timeout((int) config('heartbeat.timeout'))
->connectTimeout(2)
->get($url)
->throw();
} catch (Throwable $exception) {
Log::warning('Failed to send queue heartbeat', [
'exception' => $exception->getMessage(),
]);
}
}
}

View File

@@ -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')) {

View File

@@ -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,

View File

@@ -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 string 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());

View File

@@ -0,0 +1,45 @@
<?php
declare(strict_types=1);
namespace App\Service;
use App\Models\User;
/**
* Decides how users authenticate. Core only has password login.
* The SSO extension rebinds this to add single sign-on.
*/
class AuthenticationContract
{
public const string PASSWORD_REGISTRATION_DISABLED_MESSAGE = 'Create your account by signing in with single sign-on.';
public const string EMAIL_CHANGE_LOCKED_MESSAGE = 'Your email address comes from the identity provider you sign in with. Changes there are taken over on your next sign-in.';
/**
* Whether the user may use their local password: to log in, to reset it and to confirm their identity.
* Returning false for a user without a password also keeps "forgot password" from creating their first one.
*/
public function isPasswordLoginAllowed(User $user): bool
{
return true;
}
/**
* Whether people may create an account with a password on the register page. It is separate from
* the registration mode (app.enable_registration), which the register action checks first.
*/
public function isPasswordRegistrationAllowed(): bool
{
return true;
}
/**
* Whether the user may change their own email address. It is false when something else manages it,
* e.g. their organization's identity provider.
*/
public function canChangeEmail(User $user): bool
{
return true;
}
}

View File

@@ -6,6 +6,7 @@ namespace App\Service;
use App\Enums\Role;
use App\Events\BeforeOrganizationDeletion;
use App\Events\BeforeUserDeletion;
use App\Exceptions\Api\CanNotDeleteUserWhoIsOwnerOfOrganizationWithMultipleMembers;
use App\Models\Client;
use App\Models\Goal;
@@ -164,6 +165,8 @@ class DeletionService
}
}
BeforeUserDeletion::dispatch($user);
/** @var Member $member */
foreach ($members as $member) {
if ($member->role === Role::Owner->value) {

View File

@@ -0,0 +1,35 @@
<?php
declare(strict_types=1);
namespace App\Service;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
/**
* Confirms the account owner before sensitive actions like deleting an account or organization.
* Users confirm by re-entering their password. Users without one (or with one they may not log in with)
* can't confirm, so an administrator has to do these actions for them.
*/
class IdentityConfirmationService
{
/**
* Whether the user may confirm with their local password: they need one, and it must be one
* they may log in with. A password should not be an easier proof of identity than logging in.
*/
public function confirmsWithPassword(User $user): bool
{
return $user->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);
}
}

View File

@@ -79,6 +79,7 @@ class InvitationService
$invitations = OrganizationInvitation::query()
->whereRaw('lower(email) = ?', [Str::lower($user->email)])
->whereNotNull('accepted_at')
->with('organization')
->get();
foreach ($invitations as $invitation) {

View File

@@ -27,10 +27,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,
@@ -39,12 +44,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 = Str::lower($email);
$user->password = Hash::make($password);
$user->password = $password !== null ? Hash::make($password) : null;
$user->timezone = $timezone;
$user->week_start = $weekStart;
if ($verifyEmail) {
@@ -52,9 +59,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,

View File

@@ -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', ''),

View File

@@ -31,7 +31,7 @@ return [
*/
'bcrypt' => [
'rounds' => env('BCRYPT_ROUNDS', 12),
'rounds' => 12,
'verify' => true,
],

34
config/heartbeat.php Normal file
View File

@@ -0,0 +1,34 @@
<?php
declare(strict_types=1);
return [
/*
|--------------------------------------------------------------------------
| Heartbeat URLs
|--------------------------------------------------------------------------
|
| URLs of an external monitoring service (push/heartbeat monitors) that are
| called regularly to signal that the scheduler and the queue are working.
| If a URL is not set, the corresponding heartbeat is disabled.
|
| The queue URL may contain the placeholder "{latency_ms}", which is replaced
| with the time in milliseconds between dispatching and executing the job.
|
| The queue heartbeat is skipped if the queue connection uses the "sync"
| driver, since there is no queue worker to monitor in that case.
|
*/
'scheduler_url' => env('HEARTBEAT_SCHEDULER_URL'),
'queue_url' => env('HEARTBEAT_QUEUE_URL'),
/*
| Timeout in seconds for the HTTP request to the heartbeat URLs.
| An empty or zero value falls back to the default, since a timeout of 0
| would disable the timeout.
*/
'timeout' => max(1, (int) (env('HEARTBEAT_TIMEOUT') ?: 5)),
];

57
e2e/impersonation.spec.ts Normal file
View File

@@ -0,0 +1,57 @@
import { adminTest as test, expect } from '../playwright/fixtures';
import { PLAYWRIGHT_BASE_URL } from '../playwright/config';
import { registerUser } from './utils/members';
test.describe('Impersonation', () => {
test.beforeEach(async ({ page }) => {
// The seeded super admin's timezone differs from the browser's, which opens a modal over the app.
await page.addInitScript(() => {
window.sessionStorage.setItem('hide-timezone-mismatch-modal', 'true');
});
});
test('test that a super admin can exit an impersonation from the user menu', async ({
page,
browser,
}) => {
const userName = 'Impersonated User';
const userEmail = `impersonated+${Date.now()}_${Math.floor(Math.random() * 10000)}@doe.com`;
// Contexts inherit the super admin's storage state, so the new user registers in an empty one.
const user = await registerUser(browser, userName, userEmail, {
storageState: { cookies: [], origins: [] },
});
await user.close();
try {
await page.goto(
PLAYWRIGHT_BASE_URL + '/admin/users?search=' + encodeURIComponent(userEmail)
);
const userRow = page.getByRole('row').filter({ hasText: userEmail });
await userRow.getByRole('button', { name: 'Impersonate' }).click();
await expect(page.getByTestId('dashboard_view')).toBeVisible();
await page.getByRole('button', { name: userName }).click();
await page.getByRole('menuitem', { name: 'Exit impersonation' }).click();
await expect(page).toHaveURL(new RegExp('/admin/users'));
await expect(page.getByRole('heading', { name: 'Users', level: 1 })).toBeVisible();
} finally {
// The admin session is shared by all tests of this worker, so it must never stay impersonating.
await page.goto(PLAYWRIGHT_BASE_URL + '/filament-impersonate/leave');
}
});
test('test that the exit impersonation menu item is hidden without an impersonation', async ({
page,
}) => {
await page.goto(PLAYWRIGHT_BASE_URL + '/dashboard');
await expect(page.getByTestId('dashboard_view')).toBeVisible();
// The seeded super admin's name is unknown here, so the trigger has no stable accessible name.
await page.getByTestId('current_user_button').click();
await expect(page.getByRole('menuitem', { name: 'Log Out' })).toBeVisible();
await expect(page.getByRole('menuitem', { name: 'Exit impersonation' })).toHaveCount(0);
});
});

View File

@@ -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');

View File

@@ -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);

View File

@@ -1,5 +1,5 @@
import { expect } from '@playwright/test';
import type { Browser, Page } from '@playwright/test';
import type { Browser, BrowserContextOptions, Page } from '@playwright/test';
import { PLAYWRIGHT_BASE_URL } from '../../playwright/config';
import { getInvitationAcceptUrl } from './mailpit';
import type { TestContext } from './api';
@@ -10,9 +10,10 @@ import type { TestContext } from './api';
export async function registerUser(
browser: Browser,
name: string,
email: string
email: string,
contextOptions: BrowserContextOptions = {}
): Promise<{ page: Page; close: () => Promise<void> }> {
const context = await browser.newContext();
const context = await browser.newContext(contextOptions);
const page = await context.newPage();
await page.goto(PLAYWRIGHT_BASE_URL + '/register');

View File

@@ -1,18 +1,22 @@
{
"Billing": {
"repository": "solidtime-io/extension-billing",
"ref": "v0.0.15"
"ref": "v0.0.16"
},
"Services": {
"repository": "solidtime-io/extension-services",
"ref": "v0.0.8"
"ref": "v0.0.10"
},
"Invoicing": {
"repository": "solidtime-io/extension-invoicing",
"ref": "v0.0.13"
"ref": "v0.0.15"
},
"Auditing": {
"repository": "solidtime-io/extension-auditing",
"ref": "v0.0.5"
},
"SSO": {
"repository": "solidtime-io/extension-sso",
"ref": "v0.0.1"
}
}

View File

@@ -0,0 +1,41 @@
<script setup lang="ts">
import { ref } from 'vue';
import { Field, FieldError } from '@/packages/ui/src/field';
import TextInput from '@/packages/ui/src/Input/TextInput.vue';
const password = defineModel<string>('password', { required: true });
defineProps<{
confirmsWithPassword: boolean;
error: string;
}>();
const emit = defineEmits<{
submit: [];
}>();
const passwordInput = ref<InstanceType<typeof TextInput> | null>(null);
defineExpose({ focus: () => passwordInput.value?.focus() });
</script>
<template>
<Field v-if="confirmsWithPassword" class="mt-4">
<TextInput
ref="passwordInput"
v-model="password"
type="password"
class="block w-3/4"
placeholder="Password"
autocomplete="current-password"
@keyup.enter="emit('submit')" />
<FieldError v-if="error">{{ error }}</FieldError>
</Field>
<div v-else class="mt-4 text-sm">
<p>Your account has no password to confirm this with. Contact your administrator.</p>
<FieldError v-if="error" class="mt-2">{{ error }}</FieldError>
</div>
</template>

View File

@@ -12,12 +12,14 @@ import {
UserCircleIcon,
ArrowLeftOnRectangleIcon,
ChatBubbleLeftRightIcon,
ArrowUturnLeftIcon,
} from '@heroicons/vue/24/solid';
import { openFeedback } from '@/utils/feedback';
const page = usePage<{
has_services_extension?: boolean;
has_billing_extension?: boolean;
is_impersonating?: boolean;
auth: {
user: User & {
all_teams: Organization[];
@@ -64,6 +66,16 @@ const logout = () => {
</button>
</DropdownMenuItem>
<!-- A full page load, since leaving returns to the admin panel, which is not an Inertia page. -->
<DropdownMenuItem v-if="page.props.is_impersonating" as-child>
<a
:href="route('filament-impersonate.leave')"
class="inline-flex items-center gap-2.5 w-full">
<ArrowUturnLeftIcon class="w-5 h-5 text-icon-default" />
<span>Exit impersonation</span>
</a>
</DropdownMenuItem>
<form class="w-full" @submit.prevent="logout">
<DropdownMenuItem as-child class="inline-flex items-center gap-2.5 w-full">
<button type="submit" data-testid="logout_button">

View File

@@ -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;
};
}>();
</script>
@@ -61,6 +67,9 @@ const page = usePage<{
{{ page.props.flash?.message }}
</div>
<!-- Extension seam: alternative-auth errors (e.g. SSO callback failures) -->
<slot name="error" />
<form @submit.prevent="submit">
<Field>
<FieldLabel for="email">Email</FieldLabel>
@@ -103,5 +112,8 @@ const page = usePage<{
</PrimaryButton>
</div>
</form>
<!-- Extension seam: alternative auth methods (e.g. SSO providers) -->
<slot name="alternatives" />
</AuthenticationCard>
</template>

View File

@@ -1,29 +1,32 @@
<script setup lang="ts">
import { ref } from 'vue';
import ActionSection from '@/Components/ActionSection.vue';
import IdentityConfirmationInput from '@/Components/Common/IdentityConfirmation/IdentityConfirmationInput.vue';
import DangerButton from '@/packages/ui/src/Buttons/DangerButton.vue';
import DialogModal from '@/packages/ui/src/DialogModal.vue';
import { Field, FieldError } from '@/packages/ui/src/field';
import SecondaryButton from '@/packages/ui/src/Buttons/SecondaryButton.vue';
import TextInput from '@/packages/ui/src/Input/TextInput.vue';
import { useDeleteUserMutation } from '@/utils/useUserQuery';
import { getCurrentUserId } from '@/utils/useUser';
const props = defineProps<{
confirmsWithPassword: boolean;
}>();
const deleteUserMutation = useDeleteUserMutation();
const confirmingUserDeletion = ref(false);
const passwordInput = ref<HTMLInputElement | null>(null);
const confirmationInput = ref<InstanceType<typeof IdentityConfirmationInput> | null>(null);
const password = ref('');
const passwordError = ref('');
const processing = ref(false);
function confirmUserDeletion() {
confirmingUserDeletion.value = true;
setTimeout(() => passwordInput.value?.focus(), 250);
setTimeout(() => confirmationInput.value?.focus(), 250);
}
async function deleteUser() {
if (processing.value) return;
if (processing.value || !props.confirmsWithPassword) return;
processing.value = true;
passwordError.value = '';
try {
@@ -41,7 +44,7 @@ async function deleteUser() {
}
}
processing.value = false;
passwordInput.value?.focus();
confirmationInput.value?.focus();
}
}
@@ -75,21 +78,18 @@ function closeModal() {
<template #content>
Are you sure you want to delete your account? Once your account is deleted, all
of its resources and data will be permanently deleted. Please enter your
password to confirm you would like to permanently delete your account.
of its resources and data will be permanently deleted.
<template v-if="confirmsWithPassword">
Please enter your password to confirm you would like to permanently delete
your account.
</template>
<Field class="mt-4">
<TextInput
ref="passwordInput"
v-model="password"
type="password"
class="block w-3/4"
placeholder="Password"
autocomplete="current-password"
@keyup.enter="deleteUser" />
<FieldError v-if="passwordError">{{ passwordError }}</FieldError>
</Field>
<IdentityConfirmationInput
ref="confirmationInput"
v-model:password="password"
:confirms-with-password="confirmsWithPassword"
:error="passwordError"
@submit="deleteUser" />
</template>
<template #footer>
@@ -97,8 +97,8 @@ function closeModal() {
<DangerButton
class="ms-3"
:class="{ 'opacity-25': processing }"
:disabled="processing"
:class="{ 'opacity-25': processing || !confirmsWithPassword }"
:disabled="processing || !confirmsWithPassword"
@click="deleteUser">
Delete Account
</DangerButton>

View File

@@ -4,18 +4,19 @@ import { useForm } from '@inertiajs/vue3';
import ActionMessage from '@/Components/ActionMessage.vue';
import ActionSection from '@/Components/ActionSection.vue';
import DialogModal from '@/packages/ui/src/DialogModal.vue';
import { Field, FieldError } from '@/packages/ui/src/field';
import { FieldError } from '@/packages/ui/src/field';
import IdentityConfirmationInput from '@/Components/Common/IdentityConfirmation/IdentityConfirmationInput.vue';
import PrimaryButton from '@/packages/ui/src/Buttons/PrimaryButton.vue';
import SecondaryButton from '@/packages/ui/src/Buttons/SecondaryButton.vue';
import TextInput from '@/packages/ui/src/Input/TextInput.vue';
import type { Session } from '@/types/jetstream';
defineProps<{
const props = defineProps<{
sessions: Session[];
confirmsWithPassword: boolean;
}>();
const confirmingLogout = ref(false);
const passwordInput = ref<HTMLElement | null>(null);
const confirmationInput = ref<InstanceType<typeof IdentityConfirmationInput> | null>(null);
const form = useForm({
password: '',
@@ -23,23 +24,27 @@ const form = useForm({
const confirmLogout = () => {
confirmingLogout.value = true;
setTimeout(() => passwordInput.value?.focus(), 250);
setTimeout(() => confirmationInput.value?.focus(), 250);
};
const logoutOtherBrowserSessions = () => {
form.delete(route('other-browser-sessions.destroy'), {
preserveScroll: true,
onSuccess: () => closeModal(),
onError: () => passwordInput.value?.focus(),
onFinish: () => form.reset(),
});
if (form.processing) return;
// Users without a password log out other sessions without confirming, see OtherBrowserSessionsController.
form.transform(() => (props.confirmsWithPassword ? { password: form.password } : {})).delete(
route('other-browser-sessions.destroy'),
{
preserveScroll: true,
onSuccess: () => closeModal(),
onError: () => confirmationInput.value?.focus(),
onFinish: () => form.reset(),
}
);
};
const closeModal = () => {
confirmingLogout.value = false;
form.reset();
form.clearErrors();
};
</script>
@@ -55,8 +60,11 @@ const closeModal = () => {
<div class="max-w-xl text-sm text-text-secondary">
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.
<template v-if="confirmsWithPassword">
If you feel your account has been compromised, you should also update your
password.
</template>
</div>
<!-- Other Browser Sessions -->
@@ -128,23 +136,21 @@ const closeModal = () => {
<template #title> Log Out Other Browser Sessions </template>
<template #content>
Please enter your password to confirm you would like to log out of your other
browser sessions across all of your devices.
Log out of your other browser sessions across all of your devices.
<template v-if="confirmsWithPassword"
>Please enter your password to confirm.</template
>
<Field class="mt-4">
<TextInput
ref="passwordInput"
v-model="form.password"
type="password"
class="block w-3/4"
placeholder="Password"
autocomplete="current-password"
@keyup.enter="logoutOtherBrowserSessions" />
<FieldError v-if="form.errors.password">{{
form.errors.password
}}</FieldError>
</Field>
<IdentityConfirmationInput
v-if="confirmsWithPassword"
ref="confirmationInput"
v-model:password="form.password"
:confirms-with-password="confirmsWithPassword"
:error="form.errors.password ?? ''"
@submit="logoutOtherBrowserSessions" />
<FieldError v-else-if="form.errors.password" class="mt-4">{{
form.errors.password
}}</FieldError>
</template>
<template #footer>

View File

@@ -250,11 +250,19 @@ onBeforeUnmount(() => {
type="email"
class="block w-full"
required
:disabled="!isUserLoaded"
:disabled="!user?.can_change_email"
autocomplete="username" />
<FieldError v-if="fieldErrors.email">{{ fieldErrors.email }}</FieldError>
<!-- The email is managed elsewhere, e.g. by the organization's identity provider. -->
<p
v-if="user && !user.can_change_email"
class="mt-2 text-sm text-text-secondary"
data-testid="email_change_locked">
Your email address comes from the identity provider you sign in with. Changes
there are taken over on your next sign-in.
</p>
<div v-if="pendingEmail" class="mt-2 text-sm">
<div v-else-if="pendingEmail" class="mt-2 text-sm">
<p class="text-text-primary">
A verification link was sent to
<span class="font-medium">{{ pendingEmail }}</span

View File

@@ -1,4 +1,5 @@
<script setup lang="ts">
import ActionSection from '@/Components/ActionSection.vue';
import AppLayout from '@/Layouts/AppLayout.vue';
import DeleteUserForm from '@/Pages/Profile/Partials/DeleteUserForm.vue';
import LogoutOtherBrowserSessionsForm from '@/Pages/Profile/Partials/LogoutOtherBrowserSessionsForm.vue';
@@ -10,11 +11,16 @@ import type { Session } from '@/types/jetstream';
import ApiTokensForm from '@/Pages/Profile/Partials/ApiTokensForm.vue';
import ThemeForm from '@/Pages/Profile/Partials/ThemeForm.vue';
import NotificationSettingsForm from '@/Pages/Profile/Partials/NotificationSettingsForm.vue';
import { useUserQuery } from '@/utils/useUserQuery';
import { computed } from 'vue';
defineProps<{
confirmsTwoFactorAuthentication: boolean;
sessions: Session[];
}>();
const { user } = useUserQuery();
const confirmsWithPassword = computed(() => user.value?.confirms_with_password ?? false);
</script>
<template>
@@ -43,28 +49,52 @@ defineProps<{
<SectionBorder />
</div>
<div>
<UpdatePasswordForm class="mt-10 sm:mt-0" />
<template v-if="confirmsWithPassword">
<div>
<UpdatePasswordForm class="mt-10 sm:mt-0" />
<SectionBorder />
</div>
<div>
<TwoFactorAuthenticationForm
:requires-confirmation="confirmsTwoFactorAuthentication"
class="mt-10 sm:mt-0" />
<SectionBorder />
</div>
</template>
<!-- Without a password the user may sign in with (e.g. SSO), neither form can be used. -->
<div v-else-if="user">
<ActionSection class="mt-10 sm:mt-0">
<template #title> Password and Two Factor Authentication </template>
<template #description> How you sign in to your account. </template>
<template #content>
<div
class="max-w-xl text-sm text-text-secondary"
data-testid="sign_in_managed_externally">
You sign in through your identity provider. Your password and two
factor authentication are managed there.
</div>
</template>
</ActionSection>
<SectionBorder />
</div>
<div>
<TwoFactorAuthenticationForm
:requires-confirmation="confirmsTwoFactorAuthentication"
class="mt-10 sm:mt-0" />
<SectionBorder />
</div>
<LogoutOtherBrowserSessionsForm :sessions="sessions" class="mt-10 sm:mt-0" />
<LogoutOtherBrowserSessionsForm
:sessions="sessions"
:confirms-with-password="confirmsWithPassword"
class="mt-10 sm:mt-0" />
<SectionBorder />
<ApiTokensForm></ApiTokensForm>
<SectionBorder />
<DeleteUserForm class="mt-10 sm:mt-0" />
<DeleteUserForm
class="mt-10 sm:mt-0"
:confirms-with-password="confirmsWithPassword" />
</div>
</div>
</AppLayout>

View File

@@ -2,19 +2,19 @@
import { ref } from 'vue';
import { router } from '@inertiajs/vue3';
import ActionSection from '@/Components/ActionSection.vue';
import IdentityConfirmationInput from '@/Components/Common/IdentityConfirmation/IdentityConfirmationInput.vue';
import DangerButton from '@/packages/ui/src/Buttons/DangerButton.vue';
import DialogModal from '@/packages/ui/src/DialogModal.vue';
import { Field, FieldError } from '@/packages/ui/src/field';
import SecondaryButton from '@/packages/ui/src/Buttons/SecondaryButton.vue';
import TextInput from '@/packages/ui/src/Input/TextInput.vue';
import { useOrganizationStore } from '@/utils/useOrganization';
const props = defineProps<{
team: { id: string };
confirmsWithPassword: boolean;
}>();
const confirmingTeamDeletion = ref(false);
const passwordInput = ref<HTMLInputElement | null>(null);
const confirmationInput = ref<InstanceType<typeof IdentityConfirmationInput> | null>(null);
const password = ref('');
const passwordError = ref('');
const processing = ref(false);
@@ -22,11 +22,11 @@ const organizationStore = useOrganizationStore();
const confirmTeamDeletion = () => {
confirmingTeamDeletion.value = true;
setTimeout(() => passwordInput.value?.focus(), 250);
setTimeout(() => confirmationInput.value?.focus(), 250);
};
const deleteTeam = async () => {
if (processing.value) return;
if (processing.value || !props.confirmsWithPassword) return;
processing.value = true;
passwordError.value = '';
try {
@@ -44,7 +44,7 @@ const deleteTeam = async () => {
}
}
processing.value = false;
passwordInput.value?.focus();
confirmationInput.value?.focus();
}
};
@@ -78,21 +78,18 @@ const closeModal = () => {
<template #content>
Are you sure you want to delete this organization? Once a organization is
deleted, all of its resources and data will be permanently deleted. Please enter
your password to confirm you would like to permanently delete this organization.
deleted, all of its resources and data will be permanently deleted.
<template v-if="confirmsWithPassword">
Please enter your password to confirm you would like to permanently delete
this organization.
</template>
<Field class="mt-4">
<TextInput
ref="passwordInput"
v-model="password"
type="password"
class="block w-3/4"
placeholder="Password"
autocomplete="current-password"
@keyup.enter="deleteTeam" />
<FieldError v-if="passwordError">{{ passwordError }}</FieldError>
</Field>
<IdentityConfirmationInput
ref="confirmationInput"
v-model:password="password"
:confirms-with-password="confirmsWithPassword"
:error="passwordError"
@submit="deleteTeam" />
</template>
<template #footer>
@@ -100,8 +97,8 @@ const closeModal = () => {
<DangerButton
class="ms-3"
:class="{ 'opacity-25': processing }"
:disabled="processing"
:class="{ 'opacity-25': processing || !confirmsWithPassword }"
:disabled="processing || !confirmsWithPassword"
@click="deleteTeam">
Delete Organization
</DangerButton>

View File

@@ -11,15 +11,19 @@ import OrganizationTimeEntrySettings from '@/Pages/Teams/Partials/OrganizationTi
import OrganizationTrial from '@/Pages/Teams/Partials/OrganizationTrial.vue';
import { isBillingActivated, isInTrial } from '@/utils/billing';
import { canManageBilling } from '@/utils/permissions';
import { onMounted, ref } from 'vue';
import { computed, onMounted, ref } from 'vue';
import { useOrganizationStore } from '@/utils/useOrganization';
import { storeToRefs } from 'pinia';
import { useUserQuery } from '@/utils/useUserQuery';
defineProps<{
team: Organization;
permissions: Permissions;
}>();
const { user } = useUserQuery();
const confirmsWithPassword = computed(() => user.value?.confirms_with_password ?? false);
const loading = ref(true);
const orgStore = useOrganizationStore();
const { organization } = storeToRefs(orgStore);
@@ -62,7 +66,10 @@ onMounted(async () => {
<template v-if="permissions.canDeleteTeam">
<SectionBorder />
<DeleteTeamForm class="mt-10 sm:mt-0" :team="team" />
<DeleteTeamForm
class="mt-10 sm:mt-0"
:team="team"
:confirms-with-password="confirmsWithPassword" />
</template>
</template>
</div>

View File

@@ -10,35 +10,73 @@ import { QueryClient, VueQueryPlugin } from '@tanstack/vue-query';
import { type DefineComponent } from 'vue';
import { setupPrefetching } from '@/utils/prefetch';
interface ExtensionManifest {
name?: string;
alias?: string;
}
const appName = import.meta.env.VITE_APP_NAME || 'Laravel';
const pinia = createPinia();
const queryClient = new QueryClient();
const extensionManifests = import.meta.glob('../../extensions/**/module.json', {
eager: true,
import: 'default',
}) as Record<string, ExtensionManifest>;
// BillingPortal is a Vue 2 component and must not be bundled into the Vue 3 app.
const extensionPages = import.meta.glob<DefineComponent>([
'../../extensions/**/resources/js/Pages/**/*.vue',
'!**/BillingPortal.vue',
]);
const extensionDirectories = Object.entries(extensionManifests).reduce<Record<string, string>>(
(directories, [path, manifest]) => {
const match = path.match(/^\.\.\/\.\.\/extensions\/([^/]+)\/module\.json$/);
const extensionDirectory = match?.[1];
if (extensionDirectory === undefined) {
return directories;
}
for (const key of [manifest.name, manifest.alias, extensionDirectory]) {
if (typeof key !== 'string' || key === '') {
continue;
}
directories[key] = extensionDirectory;
directories[key.toLowerCase()] = extensionDirectory;
}
return directories;
},
{}
);
function resolveExtensionDirectory(moduleName: string): string {
return (
extensionDirectories[moduleName] ??
extensionDirectories[moduleName.toLowerCase()] ??
moduleName
);
}
createInertiaApp({
title: (title) => `${title} - ${appName}`,
resolve: (name) => {
if (name.includes('Invoicing::')) {
const [module, page] = name.split('::');
// "Module::Page" (both halves present) resolves to that extension's page
// directory; everything else is a host page under resources/js/Pages.
const [module, ...pageSegments] = name.split('::');
const page = pageSegments.join('::');
const pagePath = module
? `../../extensions/${module}/resources/js/Pages/${page}.vue`
: `./Pages/${page}.vue`;
if (module && page) {
const extensionDirectory = resolveExtensionDirectory(module);
const pagePath = `../../extensions/${extensionDirectory}/resources/js/Pages/${page}.vue`;
// BillingPortal is a Vue 2 Component and therefore should not be imported
const pages = module
? import.meta.glob<DefineComponent>([
'../../extensions/**/resources/js/Pages/*.vue',
'!**/BillingPortal.vue',
])
: import.meta.glob<DefineComponent>('./Pages/**/*.vue');
return resolvePageComponent(pagePath, pages);
} else {
return resolvePageComponent(
`./Pages/${name}.vue`,
import.meta.glob<DefineComponent>('./Pages/**/*.vue')
);
return resolvePageComponent(pagePath, extensionPages);
}
return resolvePageComponent(
`./Pages/${name}.vue`,
import.meta.glob<DefineComponent>('./Pages/**/*.vue')
);
},
setup({ el, App, props, plugin }) {
const app = createApp({ render: () => h(App, props) });

View File

@@ -37,7 +37,11 @@ const ClientStoreRequest = z.object({ name: z.string().min(1).max(255) }).passth
const ClientUpdateRequest = z
.object({ name: z.string().min(1).max(255), is_archived: z.boolean().optional() })
.passthrough();
const DestroyWithPasswordRequest = z.object({ password: z.string() }).passthrough();
const DestroyWithPasswordRequest = z
.object({
password: z.string().nullish(),
})
.passthrough();
const ImportRequest = z.object({ type: z.string(), data: z.string() }).passthrough();
const InvitationResource = z
.object({ id: z.string(), email: z.string(), role: z.string() })
@@ -106,6 +110,7 @@ const InvoiceStoreRequest = z
.object({
due_at: z.union([z.string(), z.null()]).optional(),
paid_date: z.union([z.string(), z.null()]).optional(),
seller_logo: z.union([z.string(), z.null()]).optional(),
seller_name: z.string(),
seller_vatin: z.union([z.string(), z.null()]).optional(),
seller_address_line_1: z.union([z.string(), z.null()]).optional(),
@@ -173,6 +178,7 @@ const DetailedInvoiceResource = z
seller_address_country: z.string(),
seller_phone: z.string(),
seller_email: z.string(),
seller_logo_url: z.union([z.string(), z.null()]),
recipient: InvoiceRecipientResource,
paid_date: z.string(),
due_at: z.string(),
@@ -200,6 +206,7 @@ const InvoiceUpdateRequest = z
status: InvoiceStatus,
due_at: z.union([z.string(), z.null()]),
paid_date: z.union([z.string(), z.null()]),
seller_logo: z.union([z.string(), z.null()]),
seller_name: z.string(),
seller_vatin: z.union([z.string(), z.null()]),
seller_address_line_1: z.union([z.string(), z.null()]),
@@ -255,6 +262,7 @@ const InvoiceSettingResource = z
notes_default: z.union([z.string(), z.null()]),
tax_rate_default: z.union([z.number(), z.null()]),
e_invoicing_enabled: z.boolean(),
logo_url: z.union([z.string(), z.null()]),
organization_id: z.string(),
})
.passthrough();
@@ -274,6 +282,7 @@ const InvoiceSettingUpdateRequest = z
notes_default: z.union([z.string(), z.null()]),
tax_rate_default: z.union([z.number(), z.null()]),
e_invoicing_enabled: z.boolean(),
logo: z.union([z.string(), z.null()]),
})
.partial()
.passthrough();
@@ -800,6 +809,8 @@ const UserResource = z
timezone: z.string(),
week_start: Weekday,
send_time_entry_still_running_email: z.boolean(),
confirms_with_password: z.boolean(),
can_change_email: z.boolean(),
})
.passthrough();
const UserUpdateRequest = z

View File

@@ -129,6 +129,9 @@ export function canViewAllTimeEntries() {
export function canViewInvoices() {
return currentUserHasPermission('invoices:view');
}
export function canUpdateInvoiceSettings() {
return currentUserHasPermission('invoice-settings:update');
}
export function canCreateReports() {
return currentUserHasPermission('reports:create');
}

View File

@@ -6,7 +6,9 @@ namespace Tests\Feature;
use App\Models\User;
use App\Providers\RouteServiceProvider;
use App\Service\AuthenticationContract;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Mockery\MockInterface;
use Tests\TestCase;
class AuthenticationTest extends TestCase
@@ -44,4 +46,67 @@ class AuthenticationTest extends TestCase
$this->assertGuest();
}
public function test_users_can_not_authenticate_with_an_unknown_email(): void
{
$this->post('/login', [
'email' => 'nobody@example.com',
'password' => 'password',
]);
$this->assertGuest();
}
public function test_users_without_a_local_password_can_not_authenticate(): void
{
$user = User::factory()->create();
$user->forceFill(['password' => null])->save();
$this->post('/login', [
'email' => $user->email,
'password' => '',
]);
$this->assertGuest();
}
public function test_users_without_a_local_password_can_not_authenticate_with_a_null_password(): void
{
$user = User::factory()->create();
$user->forceFill(['password' => null])->save();
$this->post('/login', [
'email' => $user->email,
'password' => null,
]);
$this->assertGuest();
}
public function test_users_without_a_local_password_can_not_authenticate_without_a_password_field(): void
{
$user = User::factory()->create();
$user->forceFill(['password' => null])->save();
$this->post('/login', [
'email' => $user->email,
]);
$this->assertGuest();
}
public function test_users_can_not_authenticate_with_a_valid_password_if_password_login_is_not_allowed(): void
{
$user = User::factory()->create();
$this->partialMock(AuthenticationContract::class, function (MockInterface $mock): void {
$mock->shouldReceive('isPasswordLoginAllowed')->andReturn(false);
});
$this->post('/login', [
'email' => $user->email,
'password' => 'password',
]);
$this->assertGuest();
}
}

View File

@@ -5,8 +5,10 @@ declare(strict_types=1);
namespace Tests\Feature;
use App\Models\User;
use App\Service\AuthenticationContract;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Hash;
use Mockery\MockInterface;
use Tests\TestCase;
class PasswordConfirmationTest extends TestCase
@@ -83,4 +85,37 @@ class PasswordConfirmationTest extends TestCase
$response->assertSessionHasErrors();
$this->assertFalse($this->app['session']->has('auth.password_confirmed_at'));
}
public function test_password_is_not_confirmed_for_users_who_may_not_log_in_with_their_password(): void
{
// Arrange
$user = User::factory()->create();
$this->partialMock(AuthenticationContract::class, function (MockInterface $mock): void {
$mock->shouldReceive('isPasswordLoginAllowed')->andReturn(false);
});
// Act
$response = $this->actingAs($user)->post('/user/confirm-password', [
'password' => 'password',
]);
// Assert
$response->assertSessionHasErrors();
$this->assertFalse($this->app['session']->has('auth.password_confirmed_at'));
}
public function test_password_is_not_confirmed_for_users_without_a_password(): void
{
// Arrange
$user = User::factory()->create(['password' => null]);
// Act
$response = $this->actingAs($user)->post('/user/confirm-password', [
'password' => '',
]);
// Assert
$response->assertSessionHasErrors();
$this->assertFalse($this->app['session']->has('auth.password_confirmed_at'));
}
}

View File

@@ -5,11 +5,13 @@ declare(strict_types=1);
namespace Tests\Feature;
use App\Models\User;
use App\Service\AuthenticationContract;
use Illuminate\Auth\Notifications\ResetPassword;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Notification;
use Laravel\Fortify\Features;
use Mockery\MockInterface;
use Tests\TestCase;
class PasswordResetTest extends TestCase
@@ -152,4 +154,36 @@ class PasswordResetTest extends TestCase
$response->assertSessionHasErrors('email');
Notification::assertNothingSent();
}
public function test_password_can_not_be_reset_if_password_login_is_not_allowed(): void
{
Notification::fake();
$user = User::factory()->create();
$passwordBefore = $user->password;
$this->post('/forgot-password', [
'email' => $user->email,
]);
$this->partialMock(AuthenticationContract::class, function (MockInterface $mock): void {
$mock->shouldReceive('isPasswordLoginAllowed')->andReturn(false);
});
Notification::assertSentTo($user, ResetPassword::class, function (ResetPassword $notification) use ($user) {
$response = $this->post('/reset-password', [
'token' => $notification->token,
'email' => $user->email,
'password' => 'new-password-123',
'password_confirmation' => 'new-password-123',
]);
$response->assertSessionHasErrors('email');
$this->assertDatabaseMissing('password_reset_tokens', ['email' => $user->email]);
return true;
});
$this->assertSame($passwordBefore, $user->refresh()->password);
}
}

View File

@@ -5,8 +5,10 @@ declare(strict_types=1);
namespace Tests\Feature;
use App\Models\User;
use App\Service\AuthenticationContract;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Hash;
use Mockery\MockInterface;
use Tests\TestCase;
class UpdatePasswordTest extends TestCase
@@ -55,4 +57,41 @@ class UpdatePasswordTest extends TestCase
$this->assertTrue(Hash::check('password', $user->fresh()->password));
}
public function test_password_cannot_be_updated_by_users_who_may_not_log_in_with_it(): void
{
// Arrange
$user = User::factory()->create();
$this->partialMock(AuthenticationContract::class, function (MockInterface $mock): void {
$mock->shouldReceive('isPasswordLoginAllowed')->andReturn(false);
});
// Act
$response = $this->actingAs($user)->put('/user/password', [
'current_password' => 'password',
'password' => 'new-password',
'password_confirmation' => 'new-password',
]);
// Assert
$response->assertSessionHasErrorsIn('updatePassword', ['current_password']);
$this->assertTrue(Hash::check('password', $user->fresh()->password));
}
public function test_password_cannot_be_set_by_users_without_a_password(): void
{
// Arrange
$user = User::factory()->create(['password' => null]);
// Act
$response = $this->actingAs($user)->put('/user/password', [
'current_password' => '',
'password' => 'new-password',
'password_confirmation' => 'new-password',
]);
// Assert
$response->assertSessionHasErrorsIn('updatePassword', ['current_password']);
$this->assertNull($user->fresh()->password);
}
}

View File

@@ -4,6 +4,7 @@ declare(strict_types=1);
namespace Tests;
use App\Service\AuthenticationContract;
use App\Service\BillableRateService;
use App\Service\BillingContract;
use App\Service\PermissionStore;
@@ -36,6 +37,16 @@ abstract class TestCase extends BaseTestCase
// $this->travelTo(Carbon::now()->timezone('Europe/Vienna')->setHour(0)->setMinute(59)->setSecond(0));
}
/**
* Act as if an extension, like SSO, manages the email address of every user.
*/
protected function lockEmailChanges(): void
{
$this->partialMock(AuthenticationContract::class, function (MockInterface $mock): void {
$mock->shouldReceive('canChangeEmail')->andReturn(false);
});
}
protected function mockPrivateStorage(): void
{
Storage::fake(config('filesystems.private'));

View File

@@ -0,0 +1,177 @@
<?php
declare(strict_types=1);
namespace Tests\Unit\Console\Commands\Heartbeat;
use App\Console\Commands\Heartbeat\HeartbeatSendCommand;
use App\Jobs\HeartbeatQueueJob;
use Illuminate\Console\Command;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Queue;
use PHPUnit\Framework\Attributes\CoversClass;
use Tests\TestCase;
use TiMacDonald\Log\LogEntry;
#[CoversClass(HeartbeatSendCommand::class)]
class HeartbeatSendCommandTest extends TestCase
{
public function test_sends_scheduler_heartbeat_and_dispatches_queue_job_if_both_urls_are_configured(): void
{
// Arrange
Carbon::setTestNow(Carbon::createFromTimestampMs(1_700_000_000_123));
config([
'heartbeat.scheduler_url' => 'https://monitor.example.com/scheduler',
'heartbeat.queue_url' => 'https://monitor.example.com/queue',
'queue.default' => 'database',
]);
Http::fake([
'https://monitor.example.com/scheduler' => Http::response('OK', 200),
]);
Queue::fake();
// Act
$exitCode = $this->withoutMockingConsoleOutput()->artisan('heartbeat:send');
// Assert
$this->assertSame(Command::SUCCESS, $exitCode);
Http::assertSentCount(1);
Http::assertSent(fn (Request $request): bool => $request->url() === 'https://monitor.example.com/scheduler'
&& $request->method() === 'GET');
Queue::assertPushed(HeartbeatQueueJob::class, fn (HeartbeatQueueJob $job): bool => $job->dispatchedAtMs === 1_700_000_000_123);
}
public function test_only_sends_scheduler_heartbeat_if_queue_url_is_not_configured(): void
{
// Arrange
config([
'heartbeat.scheduler_url' => 'https://monitor.example.com/scheduler',
'heartbeat.queue_url' => null,
]);
Http::fake([
'https://monitor.example.com/scheduler' => Http::response('OK', 200),
]);
Queue::fake();
// Act
$exitCode = $this->withoutMockingConsoleOutput()->artisan('heartbeat:send');
// Assert
$this->assertSame(Command::SUCCESS, $exitCode);
Http::assertSentCount(1);
Queue::assertNotPushed(HeartbeatQueueJob::class);
}
public function test_only_dispatches_queue_job_if_scheduler_url_is_not_configured(): void
{
// Arrange
config([
'heartbeat.scheduler_url' => null,
'heartbeat.queue_url' => 'https://monitor.example.com/queue',
'queue.default' => 'database',
]);
Http::fake();
Queue::fake();
// Act
$exitCode = $this->withoutMockingConsoleOutput()->artisan('heartbeat:send');
// Assert
$this->assertSame(Command::SUCCESS, $exitCode);
Http::assertNothingSent();
Queue::assertPushed(HeartbeatQueueJob::class);
}
public function test_does_nothing_if_no_url_is_configured(): void
{
// Arrange
config([
'heartbeat.scheduler_url' => null,
'heartbeat.queue_url' => '',
]);
Http::fake();
Queue::fake();
// Act
$exitCode = $this->withoutMockingConsoleOutput()->artisan('heartbeat:send');
// Assert
$this->assertSame(Command::SUCCESS, $exitCode);
Http::assertNothingSent();
Queue::assertNothingPushed();
}
public function test_succeeds_and_still_dispatches_queue_job_if_scheduler_heartbeat_returns_error_status(): void
{
// Arrange
config([
'heartbeat.scheduler_url' => 'https://monitor.example.com/scheduler',
'heartbeat.queue_url' => 'https://monitor.example.com/queue',
'queue.default' => 'database',
]);
Http::fake([
'https://monitor.example.com/scheduler' => Http::response(null, 500),
]);
Queue::fake();
// Act
$exitCode = $this->withoutMockingConsoleOutput()->artisan('heartbeat:send');
// Assert
$this->assertSame(Command::SUCCESS, $exitCode);
Queue::assertPushed(HeartbeatQueueJob::class);
}
public function test_succeeds_if_scheduler_heartbeat_times_out(): void
{
// Arrange
config([
'heartbeat.scheduler_url' => 'https://monitor.example.com/scheduler',
'heartbeat.queue_url' => null,
]);
Http::fake([
'https://monitor.example.com/scheduler' => function (): void {
throw new ConnectionException('Connection timed out');
},
]);
Queue::fake();
// Act
$exitCode = $this->withoutMockingConsoleOutput()->artisan('heartbeat:send');
// Assert
$this->assertSame(Command::SUCCESS, $exitCode);
}
public function test_skips_queue_heartbeat_if_queue_connection_uses_sync_driver(): void
{
// Arrange
config([
'heartbeat.scheduler_url' => 'https://monitor.example.com/scheduler',
'heartbeat.queue_url' => 'https://monitor.example.com/queue',
'queue.default' => 'sync',
]);
Http::fake([
'https://monitor.example.com/scheduler' => Http::response('OK', 200),
]);
Queue::fake();
// Act
$exitCode = $this->withoutMockingConsoleOutput()->artisan('heartbeat:send');
// Assert
$this->assertSame(Command::SUCCESS, $exitCode);
Http::assertSentCount(1);
Http::assertSent(fn (Request $request): bool => $request->url() === 'https://monitor.example.com/scheduler');
Queue::assertNotPushed(HeartbeatQueueJob::class);
Log::assertLoggedTimes(fn (LogEntry $log): bool => $log->level === 'warning'
&& $log->message === 'Skipped queue heartbeat, because the queue connection uses the sync driver'
&& $log->context === ['queue_connection' => 'sync'],
1
);
}
}

View File

@@ -111,4 +111,41 @@ class KernelTest extends TestCase
// Assert
$this->assertCount(0, $events);
}
public function test_heartbeat_runs_every_minute_if_a_heartbeat_url_is_configured(): void
{
// Arrange
config([
'heartbeat.scheduler_url' => null,
'heartbeat.queue_url' => 'https://monitor.example.com/queue',
]);
// Act
$schedule = app()->make(Kernel::class)->resolveConsoleSchedule();
$events = collect($schedule->events())->filter(fn ($event) => str_contains($event->command, 'heartbeat:send'))->values();
// Assert
$this->assertCount(1, $events);
$this->assertSame('* * * * *', $events[0]->expression);
$this->assertTrue($events[0]->onOneServer);
$this->assertFalse($events[0]->withoutOverlapping);
$this->assertTrue($events[0]->filtersPass(app()));
}
public function test_heartbeat_does_not_run_if_no_heartbeat_url_is_configured(): void
{
// Arrange
config([
'heartbeat.scheduler_url' => null,
'heartbeat.queue_url' => null,
]);
// Act
$schedule = app()->make(Kernel::class)->resolveConsoleSchedule();
$events = collect($schedule->events())->filter(fn ($event) => str_contains($event->command, 'heartbeat:send'))->values();
// Assert
$this->assertCount(1, $events);
$this->assertFalse($events[0]->filtersPass(app()));
}
}

View File

@@ -649,4 +649,24 @@ class OrganizationEndpointTest extends ApiEndpointTestAbstract
$response->assertOk();
$response->assertJsonPath('data.can_use_billable_rates', false);
}
public function test_delete_endpoint_fails_for_passwordless_user(): void
{
// Arrange
$data = $this->createUserWithPermission([
'organizations:delete',
]);
$data->user->forceFill(['password' => null])->save();
Passport::actingAs($data->user);
// Act
$response = $this->deleteJson(route('api.v1.organizations.destroy', [$data->organization->getKey()]));
// Assert
$response->assertUnprocessable();
$response->assertJsonValidationErrors(['password']);
$this->assertDatabaseHas(Organization::class, [
'id' => $data->organization->getKey(),
]);
}
}

View File

@@ -89,11 +89,67 @@ class ReportEndpointTest extends ApiEndpointTestAbstract
$response->assertForbidden();
}
public function test_store_endpoint_fails_if_user_can_not_view_all_projects(): void
{
// Arrange
$data = $this->createUserWithPermission([
'reports:create',
'time-entries:view:all',
]);
Passport::actingAs($data->user);
// Act
$response = $this->postJson(route('api.v1.reports.store', [$data->organization->getKey()]), [
'name' => 'Test Report',
'is_public' => true,
'properties' => [
'group' => TimeEntryAggregationType::Project->value,
'sub_group' => TimeEntryAggregationType::Task->value,
'history_group' => TimeEntryAggregationType::Day->value,
'start' => Carbon::now()->subDays(30)->toIso8601ZuluString(),
'end' => Carbon::now()->toIso8601ZuluString(),
],
]);
// Assert
$response->assertForbidden();
$this->assertDatabaseCount(Report::class, 0);
}
public function test_store_endpoint_fails_if_user_can_not_view_all_time_entries(): void
{
// Arrange
$data = $this->createUserWithPermission([
'reports:create',
'projects:view:all',
]);
Passport::actingAs($data->user);
// Act
$response = $this->postJson(route('api.v1.reports.store', [$data->organization->getKey()]), [
'name' => 'Test Report',
'is_public' => true,
'properties' => [
'group' => TimeEntryAggregationType::Project->value,
'sub_group' => TimeEntryAggregationType::Task->value,
'history_group' => TimeEntryAggregationType::Day->value,
'start' => Carbon::now()->subDays(30)->toIso8601ZuluString(),
'end' => Carbon::now()->toIso8601ZuluString(),
],
]);
// Assert
$response->assertForbidden();
$this->assertDatabaseCount(Report::class, 0);
}
public function test_store_endpoint_creates_new_report_with_minimal_properties(): void
{
// Arrange
$data = $this->createUserWithPermission([
'reports:create',
'projects:view:all',
'time-entries:view:all',
]);
Passport::actingAs($data->user);
@@ -128,6 +184,8 @@ class ReportEndpointTest extends ApiEndpointTestAbstract
// Arrange
$data = $this->createUserWithPermission([
'reports:create',
'projects:view:all',
'time-entries:view:all',
]);
Passport::actingAs($data->user);
@@ -175,6 +233,8 @@ class ReportEndpointTest extends ApiEndpointTestAbstract
// Arrange
$data = $this->createUserWithPermission([
'reports:create',
'projects:view:all',
'time-entries:view:all',
]);
Passport::actingAs($data->user);
@@ -230,6 +290,8 @@ class ReportEndpointTest extends ApiEndpointTestAbstract
// Arrange
$data = $this->createUserWithPermission([
'reports:create',
'projects:view:all',
'time-entries:view:all',
]);
Passport::actingAs($data->user);
@@ -263,6 +325,8 @@ class ReportEndpointTest extends ApiEndpointTestAbstract
// Arrange
$data = $this->createUserWithPermission([
'reports:create',
'projects:view:all',
'time-entries:view:all',
]);
Passport::actingAs($data->user);
@@ -301,11 +365,57 @@ class ReportEndpointTest extends ApiEndpointTestAbstract
$response->assertForbidden();
}
public function test_update_endpoint_fails_if_user_can_not_view_all_projects(): void
{
// Arrange
$data = $this->createUserWithPermission([
'reports:update',
'time-entries:view:all',
]);
$report = Report::factory()->forOrganization($data->organization)->private()->create();
Passport::actingAs($data->user);
// Act
$response = $this->putJson(route('api.v1.reports.update', [$data->organization->getKey(), $report->getKey()]), [
'is_public' => true,
]);
// Assert
$response->assertForbidden();
$report->refresh();
$this->assertFalse($report->is_public);
$this->assertNull($report->share_secret);
}
public function test_update_endpoint_fails_if_user_can_not_view_all_time_entries(): void
{
// Arrange
$data = $this->createUserWithPermission([
'reports:update',
'projects:view:all',
]);
$report = Report::factory()->forOrganization($data->organization)->private()->create();
Passport::actingAs($data->user);
// Act
$response = $this->putJson(route('api.v1.reports.update', [$data->organization->getKey(), $report->getKey()]), [
'is_public' => true,
]);
// Assert
$response->assertForbidden();
$report->refresh();
$this->assertFalse($report->is_public);
$this->assertNull($report->share_secret);
}
public function test_update_endpoint_fails_if_report_does_not_exist(): void
{
// Arrange
$data = $this->createUserWithPermission([
'reports:update',
'projects:view:all',
'time-entries:view:all',
]);
Passport::actingAs($data->user);
@@ -323,6 +433,8 @@ class ReportEndpointTest extends ApiEndpointTestAbstract
// Arrange
$data = $this->createUserWithPermission([
'reports:update',
'projects:view:all',
'time-entries:view:all',
]);
$report = Report::factory()->create();
Passport::actingAs($data->user);
@@ -341,6 +453,8 @@ class ReportEndpointTest extends ApiEndpointTestAbstract
// Arrange
$data = $this->createUserWithPermission([
'reports:update',
'projects:view:all',
'time-entries:view:all',
]);
$report = Report::factory()->forOrganization($data->organization)->create();
Passport::actingAs($data->user);
@@ -365,6 +479,8 @@ class ReportEndpointTest extends ApiEndpointTestAbstract
// Arrange
$data = $this->createUserWithPermission([
'reports:update',
'projects:view:all',
'time-entries:view:all',
]);
$report = Report::factory()->forOrganization($data->organization)->create();
Passport::actingAs($data->user);
@@ -389,6 +505,8 @@ class ReportEndpointTest extends ApiEndpointTestAbstract
// Arrange
$data = $this->createUserWithPermission([
'reports:update',
'projects:view:all',
'time-entries:view:all',
]);
$report = Report::factory()->private()->forOrganization($data->organization)->create();
Passport::actingAs($data->user);
@@ -415,6 +533,8 @@ class ReportEndpointTest extends ApiEndpointTestAbstract
// Arrange
$data = $this->createUserWithPermission([
'reports:update',
'projects:view:all',
'time-entries:view:all',
]);
$report = Report::factory()->public()->forOrganization($data->organization)->create();
Passport::actingAs($data->user);
@@ -441,6 +561,8 @@ class ReportEndpointTest extends ApiEndpointTestAbstract
// Arrange
$data = $this->createUserWithPermission([
'reports:update',
'projects:view:all',
'time-entries:view:all',
]);
$report = Report::factory()->public()->forOrganization($data->organization)->create();
$secret = $report->share_secret;
@@ -468,6 +590,8 @@ class ReportEndpointTest extends ApiEndpointTestAbstract
// Arrange
$data = $this->createUserWithPermission([
'reports:update',
'projects:view:all',
'time-entries:view:all',
]);
$report = Report::factory()->forOrganization($data->organization)->create();
Passport::actingAs($data->user);
@@ -498,6 +622,8 @@ class ReportEndpointTest extends ApiEndpointTestAbstract
// Arrange
$data = $this->createUserWithPermission([
'reports:update',
'projects:view:all',
'time-entries:view:all',
]);
$report = Report::factory()->public()->forOrganization($data->organization)->create([
'public_until' => null,
@@ -523,6 +649,8 @@ class ReportEndpointTest extends ApiEndpointTestAbstract
// Arrange
$data = $this->createUserWithPermission([
'reports:update',
'projects:view:all',
'time-entries:view:all',
]);
$report = Report::factory()->public()->forOrganization($data->organization)->create([
'public_until' => Carbon::now()->addDays(30),
@@ -611,6 +739,8 @@ class ReportEndpointTest extends ApiEndpointTestAbstract
// Arrange
$data = $this->createUserWithPermission([
'reports:create',
'projects:view:all',
'time-entries:view:all',
]);
Passport::actingAs($data->user);
@@ -656,6 +786,8 @@ class ReportEndpointTest extends ApiEndpointTestAbstract
// Arrange
$data = $this->createUserWithPermission([
'reports:create',
'projects:view:all',
'time-entries:view:all',
]);
Passport::actingAs($data->user);
@@ -691,6 +823,8 @@ class ReportEndpointTest extends ApiEndpointTestAbstract
// Arrange
$data = $this->createUserWithPermission([
'reports:create',
'projects:view:all',
'time-entries:view:all',
]);
$project = Project::factory()->forOrganization($data->organization)->create();
$client = Client::factory()->forOrganization($data->organization)->create();
@@ -798,6 +932,8 @@ class ReportEndpointTest extends ApiEndpointTestAbstract
// Arrange
$data = $this->createUserWithPermission([
'reports:create',
'projects:view:all',
'time-entries:view:all',
]);
$tag = Tag::factory()->forOrganization($data->organization)->create();
Passport::actingAs($data->user);
@@ -831,6 +967,8 @@ class ReportEndpointTest extends ApiEndpointTestAbstract
// Arrange
$data = $this->createUserWithPermission([
'reports:create',
'projects:view:all',
'time-entries:view:all',
]);
Passport::actingAs($data->user);

View File

@@ -10,6 +10,7 @@ use App\Mail\VerifyUpdatedEmailMail;
use App\Models\Member;
use App\Models\Organization;
use App\Models\User;
use App\Service\AuthenticationContract;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Storage;
use Laravel\Passport\Passport;
@@ -46,10 +47,42 @@ class UserEndpointTest extends ApiEndpointTestAbstract
'timezone' => $data->user->timezone,
'week_start' => $data->user->week_start->value,
'send_time_entry_still_running_email' => true,
'confirms_with_password' => true,
'can_change_email' => true,
],
]);
}
public function test_me_returns_that_users_without_a_password_cannot_confirm_with_it(): void
{
// Arrange
$data = $this->createUserWithPermission();
$data->user->forceFill(['password' => null])->save();
Passport::actingAs($data->user);
// Act
$response = $this->getJson(route('api.v1.users.me'));
// Assert
$response->assertSuccessful();
$response->assertJsonPath('data.confirms_with_password', false);
}
public function test_me_returns_that_the_email_cannot_be_changed_when_it_is_managed_elsewhere(): void
{
// Arrange
$data = $this->createUserWithPermission();
$this->lockEmailChanges();
Passport::actingAs($data->user);
// Act
$response = $this->getJson(route('api.v1.users.me'));
// Assert
$response->assertSuccessful();
$response->assertJsonPath('data.can_change_email', false);
}
public function test_update_current_organization_fails_when_not_authenticated(): void
{
// Arrange
@@ -245,6 +278,52 @@ class UserEndpointTest extends ApiEndpointTestAbstract
Mail::assertNothingSent();
}
public function test_update_email_fails_when_an_extension_locks_the_email(): void
{
// Arrange
Mail::fake();
$data = $this->createUserWithPermission();
$data->user->email = 'current@example.com';
$data->user->save();
$this->lockEmailChanges();
Passport::actingAs($data->user);
// Act
$response = $this->putJson(route('api.v1.users.update', $data->user->getKey()), [
'email' => 'new@example.com',
'name' => 'New Name',
]);
// Assert
$response->assertStatus(422);
$response->assertJsonValidationErrors(['email' => AuthenticationContract::EMAIL_CHANGE_LOCKED_MESSAGE]);
$user = $data->user->fresh();
$this->assertNull($user->pending_email);
$this->assertNotSame('New Name', $user->name);
Mail::assertNothingSent();
}
public function test_update_with_the_current_email_succeeds_when_an_extension_locks_the_email(): void
{
// Arrange
// The profile form sends the unchanged address along with other fields.
$data = $this->createUserWithPermission();
$data->user->email = 'current@example.com';
$data->user->save();
$this->lockEmailChanges();
Passport::actingAs($data->user);
// Act
$response = $this->putJson(route('api.v1.users.update', $data->user->getKey()), [
'email' => 'Current@Example.com',
'name' => 'New Name',
]);
// Assert
$response->assertSuccessful();
$this->assertSame('New Name', $data->user->fresh()->name);
}
public function test_update_fails_if_email_is_already_used_by_another_user(): void
{
// Arrange
@@ -333,6 +412,26 @@ class UserEndpointTest extends ApiEndpointTestAbstract
});
}
public function test_resend_email_verification_fails_when_an_extension_locks_the_email(): void
{
// Arrange
// E.g. a change requested before the user's organization started managing it.
Mail::fake();
$data = $this->createUserWithPermission();
$data->user->pending_email = 'new.email@example.com';
$data->user->save();
$this->lockEmailChanges();
Passport::actingAs($data->user);
// Act
$response = $this->postJson(route('api.v1.users.resend-email-verification', $data->user->getKey()));
// Assert
$response->assertStatus(422);
$response->assertJsonValidationErrors(['email' => AuthenticationContract::EMAIL_CHANGE_LOCKED_MESSAGE]);
Mail::assertNothingOutgoing();
}
public function test_resend_email_verification_fails_if_given_id_is_not_the_authenticated_user(): void
{
// Arrange
@@ -789,4 +888,20 @@ class UserEndpointTest extends ApiEndpointTestAbstract
$response->assertNoContent();
$this->assertDatabaseMissing(User::class, ['id' => $data->user->getKey()]);
}
public function test_delete_fails_for_passwordless_user(): void
{
// Arrange
$data = $this->createUserWithPermission();
$data->user->forceFill(['password' => null])->save();
Passport::actingAs($data->user);
// Act
$response = $this->deleteJson(route('api.v1.users.destroy', $data->user->getKey()));
// Assert
$response->assertUnprocessable();
$response->assertJsonValidationErrors(['password']);
$this->assertDatabaseHas(User::class, ['id' => $data->user->getKey()]);
}
}

View File

@@ -6,8 +6,10 @@ namespace Tests\Unit\Endpoint\Web;
use App\Http\Controllers\Web\OtherBrowserSessionsController;
use App\Models\User;
use App\Service\AuthenticationContract;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Mockery\MockInterface;
use PHPUnit\Framework\Attributes\CoversClass;
#[CoversClass(OtherBrowserSessionsController::class)]
@@ -100,4 +102,65 @@ class OtherBrowserSessionsEndpointTest extends EndpointTestAbstract
$this->assertDatabaseMissing('sessions', ['id' => 'other-session-of-current-user']);
$this->assertDatabaseHas('sessions', ['id' => 'session-of-another-user']);
}
private function seedOtherSession(User $user, string $id = 'other-session'): void
{
DB::table('sessions')->insert([
'id' => $id,
'user_id' => $user->getKey(),
'ip_address' => '192.0.2.10',
'user_agent' => '',
'payload' => '',
'last_activity' => now()->timestamp,
]);
}
public function test_passwordless_user_can_revoke_other_sessions_without_confirming(): void
{
config(['session.driver' => 'database']);
$user = User::factory()->create(['password' => null]);
$otherUser = User::factory()->create();
$this->actingAs($user)->withSession(['current-session' => true]);
$currentId = app('session.store')->getId();
$this->withCookie(config('session.cookie'), $currentId);
$this->seedOtherSession($user, $currentId);
$this->seedOtherSession($user);
$this->seedOtherSession($otherUser, 'unrelated-session');
$response = $this->delete('/user/other-browser-sessions');
$response->assertRedirect()->assertSessionHasNoErrors();
$this->assertAuthenticatedAs($user);
$this->assertDatabaseHas('sessions', ['id' => $currentId]);
$this->assertDatabaseHas('sessions', ['id' => 'unrelated-session']);
$this->assertDatabaseMissing('sessions', ['id' => 'other-session']);
$this->assertNull($user->fresh()->password);
}
public function test_user_with_a_disallowed_local_password_revokes_other_sessions_without_confirming(): void
{
config(['session.driver' => 'database']);
$user = User::factory()->create();
$originalPasswordHash = $user->password;
$this->actingAs($user);
$this->seedOtherSession($user);
$this->partialMock(AuthenticationContract::class, function (MockInterface $mock): void {
$mock->shouldReceive('isPasswordLoginAllowed')->andReturn(false);
});
$this->delete('/user/other-browser-sessions')->assertRedirect()->assertSessionHasNoErrors();
$this->assertDatabaseMissing('sessions', ['id' => 'other-session']);
// The password they may not use is not rehashed with whatever they entered
$this->assertSame($originalPasswordHash, $user->fresh()->password);
}
public function test_passwordless_logout_does_not_report_success_for_unsupported_session_storage(): void
{
config(['session.driver' => 'array']);
$user = User::factory()->create(['password' => null]);
$this->actingAs($user);
$this->delete('/user/other-browser-sessions')->assertSessionHasErrors('password');
}
}

View File

@@ -6,6 +6,7 @@ namespace Tests\Unit\Endpoint\Web;
use App\Http\Controllers\Web\UserController;
use App\Models\User;
use App\Service\AuthenticationContract;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\URL;
use PHPUnit\Framework\Attributes\CoversClass;
@@ -46,6 +47,37 @@ class UserEndpointTest extends EndpointTestAbstract
$this->assertTrue(now()->equalTo($user->email_verified_at));
}
public function test_pending_email_verification_is_refused_and_cleared_when_an_extension_locks_the_email(): void
{
// Arrange
$user = User::factory()->create([
'email' => 'current@example.com',
'pending_email' => 'new@example.com',
]);
$this->lockEmailChanges();
$this->actingAs($user);
$verificationUrl = URL::temporarySignedRoute(
'users.verify-email-change',
now()->addMinutes(60),
[
'user' => $user->getKey(),
'email' => 'new@example.com',
],
false
);
// Act
$response = $this->get($verificationUrl);
// Assert
$response->assertRedirect(route('dashboard'));
$response->assertSessionHas('bannerStyle', 'danger');
$response->assertSessionHas('bannerText', AuthenticationContract::EMAIL_CHANGE_LOCKED_MESSAGE);
$user->refresh();
$this->assertSame('current@example.com', $user->email);
$this->assertNull($user->pending_email);
}
public function test_pending_email_verification_is_rejected_for_another_authenticated_user(): void
{
// Arrange

View File

@@ -0,0 +1,124 @@
<?php
declare(strict_types=1);
namespace Tests\Unit\Jobs;
use App\Jobs\HeartbeatQueueJob;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Http;
use PHPUnit\Framework\Attributes\CoversClass;
use Tests\TestCase;
#[CoversClass(HeartbeatQueueJob::class)]
class HeartbeatQueueJobTest extends TestCase
{
public function test_replaces_latency_placeholder_with_time_between_dispatch_and_execution(): void
{
// Arrange
Carbon::setTestNow(Carbon::createFromTimestampMs(1_700_000_001_500));
config([
'heartbeat.queue_url' => 'https://monitor.example.com/queue?status=up&ping={latency_ms}',
]);
Http::fake();
$job = new HeartbeatQueueJob(1_700_000_000_250);
// Act
$job->handle();
// Assert
Http::assertSentCount(1);
Http::assertSent(fn (Request $request): bool => $request->url() === 'https://monitor.example.com/queue?status=up&ping=1250'
&& $request->method() === 'GET');
}
public function test_calls_url_unchanged_if_it_has_no_placeholder(): void
{
// Arrange
config([
'heartbeat.queue_url' => 'https://monitor.example.com/queue',
]);
Http::fake();
$job = new HeartbeatQueueJob(Carbon::now()->getTimestampMs());
// Act
$job->handle();
// Assert
Http::assertSentCount(1);
Http::assertSent(fn (Request $request): bool => $request->url() === 'https://monitor.example.com/queue');
}
public function test_latency_is_never_negative(): void
{
// Arrange
Carbon::setTestNow(Carbon::createFromTimestampMs(1_700_000_000_000));
config([
'heartbeat.queue_url' => 'https://monitor.example.com/queue?ping={latency_ms}',
]);
Http::fake();
$job = new HeartbeatQueueJob(1_700_000_005_000);
// Act
$job->handle();
// Assert
Http::assertSent(fn (Request $request): bool => $request->url() === 'https://monitor.example.com/queue?ping=0');
}
public function test_does_nothing_if_queue_url_is_not_configured(): void
{
// Arrange
config([
'heartbeat.queue_url' => null,
]);
Http::fake();
$job = new HeartbeatQueueJob(Carbon::now()->getTimestampMs());
// Act
$job->handle();
// Assert
Http::assertNothingSent();
}
public function test_does_not_throw_if_request_fails(): void
{
// Arrange
config([
'heartbeat.queue_url' => 'https://monitor.example.com/queue',
]);
Http::fake([
'https://monitor.example.com/queue' => function (): void {
throw new ConnectionException('Connection timed out');
},
]);
$job = new HeartbeatQueueJob(Carbon::now()->getTimestampMs());
// Act
$job->handle();
// Assert
Http::assertSentCount(0);
}
public function test_does_not_throw_if_response_has_error_status(): void
{
// Arrange
config([
'heartbeat.queue_url' => 'https://monitor.example.com/queue',
]);
Http::fake([
'https://monitor.example.com/queue' => Http::response(null, 500),
]);
$job = new HeartbeatQueueJob(Carbon::now()->getTimestampMs());
// Act
$job->handle();
// Assert
Http::assertSentCount(1);
}
}

View File

@@ -0,0 +1,87 @@
<?php
declare(strict_types=1);
namespace Tests\Unit\Models;
use App\Models\User;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Config;
use PHPUnit\Framework\Attributes\CoversClass;
use Tests\TestCase;
#[CoversClass(User::class)]
class UserTest extends TestCase
{
public function test_is_super_admin_is_true_for_configured_and_verified_email(): void
{
Config::set('auth.super_admins', ['admin@example.com']);
$user = User::factory()->make([
'email' => 'admin@example.com',
'email_verified_at' => Carbon::now(),
]);
$this->assertTrue($user->isSuperAdmin());
}
public function test_is_super_admin_ignores_the_case_of_the_users_email(): void
{
Config::set('auth.super_admins', ['other@example.com', 'admin@example.com']);
$user = User::factory()->make([
'email' => 'admin@EXAMPLE.com',
'email_verified_at' => Carbon::now(),
]);
$this->assertTrue($user->isSuperAdmin());
}
public function test_super_admins_from_the_environment_are_trimmed_and_lowercased(): void
{
// Arrange
$previousEnv = $_ENV;
$previousServer = $_SERVER;
$_ENV['SUPER_ADMINS'] = $_SERVER['SUPER_ADMINS'] = ' Admin@Example.com,, other@example.com ';
// Act
try {
$config = require config_path('auth.php');
} finally {
$_ENV = $previousEnv;
$_SERVER = $previousServer;
}
// Assert
$this->assertSame(['admin@example.com', 'other@example.com'], $config['super_admins']);
}
public function test_is_super_admin_is_false_when_email_is_not_verified(): void
{
Config::set('auth.super_admins', ['admin@example.com']);
$user = User::factory()->make([
'email' => 'admin@example.com',
'email_verified_at' => null,
]);
$this->assertFalse($user->isSuperAdmin());
}
public function test_is_super_admin_is_false_for_a_non_configured_email(): void
{
Config::set('auth.super_admins', ['admin@example.com']);
$user = User::factory()->make([
'email' => 'someone@example.com',
'email_verified_at' => Carbon::now(),
]);
$this->assertFalse($user->isSuperAdmin());
}
public function test_has_local_password_reflects_password_presence(): void
{
$withPassword = User::factory()->make(['password' => bcrypt('secret-password')]);
$passwordless = User::factory()->make(['password' => null]);
$this->assertTrue($withPassword->hasLocalPassword());
$this->assertFalse($passwordless->hasLocalPassword());
}
}

View File

@@ -6,6 +6,7 @@ namespace Tests\Unit\Service;
use App\Enums\Role;
use App\Events\BeforeOrganizationDeletion;
use App\Events\BeforeUserDeletion;
use App\Exceptions\Api\CanNotDeleteUserWhoIsOwnerOfOrganizationWithMultipleMembers;
use App\Models\Audit;
use App\Models\Client;
@@ -43,6 +44,7 @@ class DeletionServiceTest extends TestCaseWithDatabase
parent::setUp();
Event::fake([
BeforeOrganizationDeletion::class,
BeforeUserDeletion::class,
]);
$this->deletionService = app(DeletionService::class);
}
@@ -255,6 +257,7 @@ class DeletionServiceTest extends TestCaseWithDatabase
// Assert
$this->assertTrue(true);
}
Event::assertNotDispatched(BeforeUserDeletion::class);
}
public function test_delete_user_rolls_back_on_error_if_transaction_is_active(): void
@@ -312,6 +315,7 @@ class DeletionServiceTest extends TestCaseWithDatabase
$this->deletionService->deleteUser($user);
// Assert
Event::assertDispatched(fn (BeforeUserDeletion $event): bool => $event->user->is($user), 1);
$this->assertDatabaseMissing(User::class, [
'id' => $user->getKey(),
]);

View File

@@ -0,0 +1,93 @@
<?php
declare(strict_types=1);
namespace Tests\Unit\Service;
use App\Models\User;
use App\Service\AuthenticationContract;
use App\Service\IdentityConfirmationService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Mockery\MockInterface;
use PHPUnit\Framework\Attributes\CoversClass;
use Tests\TestCase;
#[CoversClass(IdentityConfirmationService::class)]
class IdentityConfirmationServiceTest extends TestCase
{
use RefreshDatabase;
public function test_users_with_a_password_confirm_with_it(): void
{
// Arrange
$user = User::factory()->create();
// Act
$confirmsWithPassword = app(IdentityConfirmationService::class)->confirmsWithPassword($user);
// Assert
$this->assertTrue($confirmsWithPassword);
}
public function test_users_without_a_password_cannot_confirm(): void
{
// Arrange
$user = User::factory()->create();
$user->forceFill(['password' => null])->save();
// Act
$confirmsWithPassword = app(IdentityConfirmationService::class)->confirmsWithPassword($user);
// Assert
$this->assertFalse($confirmsWithPassword);
}
public function test_users_who_may_not_log_in_with_their_password_cannot_confirm_with_it(): void
{
// Arrange
$service = app(IdentityConfirmationService::class);
$user = User::factory()->create();
$this->partialMock(AuthenticationContract::class, function (MockInterface $mock): void {
$mock->shouldReceive('isPasswordLoginAllowed')->andReturn(false);
});
// Act
$confirmsWithPassword = $service->confirmsWithPassword($user);
// Assert
$this->assertFalse($confirmsWithPassword);
}
public function test_confirm_password_accepts_only_the_correct_password(): void
{
// Arrange
$service = app(IdentityConfirmationService::class);
$user = User::factory()->create();
// Act
$correct = $service->confirmPassword($user, 'password');
$wrong = $service->confirmPassword($user, 'wrong-password');
$missing = $service->confirmPassword($user, null);
// Assert
$this->assertTrue($correct);
$this->assertFalse($wrong);
$this->assertFalse($missing);
}
public function test_confirm_password_rejects_the_correct_password_of_users_who_may_not_log_in_with_it(): void
{
// Arrange
$service = app(IdentityConfirmationService::class);
$user = User::factory()->create();
$this->partialMock(AuthenticationContract::class, function (MockInterface $mock): void {
$mock->shouldReceive('isPasswordLoginAllowed')->andReturn(false);
});
// Act
$confirmed = $service->confirmPassword($user, 'password');
// Assert
$this->assertFalse($confirmed);
}
}

View File

@@ -8,6 +8,7 @@ use App\Enums\Role;
use App\Enums\Weekday;
use App\Models\Member;
use App\Models\Organization;
use App\Models\OrganizationInvitation;
use App\Models\Project;
use App\Models\ProjectMember;
use App\Models\TimeEntry;
@@ -16,6 +17,7 @@ use App\Service\UserService;
use Illuminate\Auth\Events\Verified;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Hash;
use PHPUnit\Framework\Attributes\CoversClass;
use Tests\TestCase;
@@ -174,4 +176,139 @@ class UserServiceTest extends TestCase
$this->assertSame(Role::Owner->value, $newMember->role);
$this->assertSame($newOrganization->getKey(), $user->currentOrganization->getKey());
}
public function test_create_user_hashes_the_password_and_creates_own_organization(): void
{
// Act
$user = $this->userService->createUser(
name: 'Solo User',
email: 'solo@example.com',
password: 'secret-password-123',
timezone: 'UTC',
weekStart: Weekday::Monday,
currency: null,
);
// Assert
$user->refresh();
$this->assertTrue(Hash::check('secret-password-123', $user->password));
$this->assertSame(1, $user->organizations()->count());
$this->assertSame($user->getKey(), $user->currentOrganization->user_id);
}
public function test_create_user_without_password_joins_accepted_invitation_organization_instead_of_creating_own_one(): void
{
// Arrange
$organization = Organization::factory()->create();
OrganizationInvitation::factory()
->forOrganization($organization)
->role(Role::Employee)
->accepted()
->create([
'email' => 'invitee@example.com',
]);
// Act
$user = $this->userService->createUser(
name: 'Invitee',
email: 'Invitee@Example.com',
password: null,
timezone: 'UTC',
weekStart: Weekday::Monday,
currency: null,
);
// Assert
$this->assertNull($user->password);
$this->assertDatabaseMissing(OrganizationInvitation::class, [
'email' => 'invitee@example.com',
]);
$user->refresh();
$this->assertSame(1, $user->organizations()->count());
$this->assertSame($organization->getKey(), $user->organizations()->first()->getKey());
$member = Member::whereBelongsTo($user)->whereBelongsTo($organization)->firstOrFail();
$this->assertSame(Role::Employee->value, $member->role);
}
public function test_create_user_without_password_creates_own_organization_when_no_invitation_exists(): void
{
// Act
$user = $this->userService->createUser(
name: 'Solo User',
email: 'solo@example.com',
password: null,
timezone: 'UTC',
weekStart: Weekday::Monday,
currency: null,
);
// Assert
$user->refresh();
$this->assertNull($user->password);
$this->assertSame(1, $user->organizations()->count());
$organization = $user->organizations()->first();
$this->assertTrue($organization->personal_team);
$this->assertSame($user->getKey(), $organization->user_id);
$this->assertSame($organization->getKey(), $user->currentOrganization->getKey());
}
public function test_create_user_joins_the_given_organization_instead_of_creating_own_one(): void
{
// Arrange
$organization = Organization::factory()->create();
// Act
$user = $this->userService->createUser(
name: 'SSO User',
email: 'sso@example.com',
password: null,
timezone: 'UTC',
weekStart: Weekday::Monday,
currency: null,
organization: $organization,
role: Role::Manager,
);
// Assert
$user->refresh();
$this->assertSame(1, $user->organizations()->count());
$this->assertSame($organization->getKey(), $user->currentOrganization->getKey());
$member = Member::whereBelongsTo($user)->whereBelongsTo($organization)->firstOrFail();
$this->assertSame(Role::Manager->value, $member->role);
}
public function test_create_user_keeps_the_invited_role_when_the_given_organization_also_invited_them(): void
{
// Arrange
$invitedOrganization = Organization::factory()->create();
$organization = Organization::factory()->create();
foreach ([$invitedOrganization, $organization] as $inviting) {
OrganizationInvitation::factory()
->forOrganization($inviting)
->role(Role::Admin)
->accepted()
->create([
'email' => 'sso@example.com',
]);
}
// Act
$user = $this->userService->createUser(
name: 'SSO User',
email: 'sso@example.com',
password: null,
timezone: 'UTC',
weekStart: Weekday::Monday,
currency: null,
organization: $organization,
role: Role::Employee,
);
// Assert
$user->refresh();
$this->assertSame(2, $user->organizations()->count());
$this->assertSame($organization->getKey(), $user->currentOrganization->getKey());
$member = Member::whereBelongsTo($user)->whereBelongsTo($organization)->firstOrFail();
$this->assertSame(Role::Admin->value, $member->role);
}
}

View File

@@ -24,5 +24,7 @@
"extensions/Invoicing/resources/js/**/*.ts",
"extensions/Invoicing/resources/js/**/*.d.ts",
"extensions/Invoicing/resources/js/**/*.vue",
"extensions/SSO/resources/js/**/*.ts",
"extensions/SSO/resources/js/**/*.vue",
]
}