mirror of
https://github.com/solidtime-io/solidtime.git
synced 2026-12-06 17:52:16 +00:00
Add core support for extendable authentication and passwordless user
creation
This commit is contained in:
@@ -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,
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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(),
|
||||
|
||||
@@ -59,13 +59,13 @@ class UserCreateCommand extends Command
|
||||
$user = null;
|
||||
DB::transaction(function () use (&$user, $name, $email, $password, $verifyEmail): void {
|
||||
$user = app(UserService::class)->createUser(
|
||||
$name,
|
||||
$email,
|
||||
$password,
|
||||
'UTC',
|
||||
Weekday::Monday,
|
||||
null,
|
||||
verifyEmail: $verifyEmail
|
||||
name: $name,
|
||||
email: $email,
|
||||
password: $password,
|
||||
timezone: 'UTC',
|
||||
weekStart: Weekday::Monday,
|
||||
currency: null,
|
||||
verifyEmail: $verifyEmail,
|
||||
);
|
||||
});
|
||||
/** @var Organization|null $organization */
|
||||
|
||||
20
app/Events/BeforeUserDeletion.php
Normal file
20
app/Events/BeforeUserDeletion.php
Normal 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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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));
|
||||
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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)
|
||||
|
||||
59
app/Http/Requests/V1/Concerns/ConfirmsIdentity.php
Normal file
59
app/Http/Requests/V1/Concerns/ConfirmsIdentity.php
Normal 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.'));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -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),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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')) {
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -11,6 +11,8 @@ use App\Actions\Fortify\UpdateUserProfileInformation;
|
||||
use App\Extensions\Fortify\CustomLoginResponse;
|
||||
use App\Extensions\Fortify\CustomTwoFactorLoginResponse;
|
||||
use App\Models\User;
|
||||
use App\Service\AuthenticationContract;
|
||||
use App\Service\IdentityConfirmationService;
|
||||
use Illuminate\Cache\RateLimiting\Limit;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
@@ -25,6 +27,12 @@ use Laravel\Fortify\Fortify;
|
||||
|
||||
class FortifyServiceProvider extends ServiceProvider
|
||||
{
|
||||
/**
|
||||
* Hash of a random value that is checked when no user exists for the email,
|
||||
* so login takes the same time whether the email is registered or not.
|
||||
*/
|
||||
private const ABSENT_USER_PASSWORD_HASH = '$2y$12$PtSQLk/QWOJJpg42pGEkt.TTR7NwCq0.g/0EOWb2B6eDww4zR92.2';
|
||||
|
||||
/**
|
||||
* Register any application services.
|
||||
*/
|
||||
@@ -44,6 +52,13 @@ class FortifyServiceProvider extends ServiceProvider
|
||||
Fortify::resetUserPasswordsUsing(ResetUserPassword::class);
|
||||
|
||||
Fortify::registerView(function () {
|
||||
if (! app(AuthenticationContract::class)->isPasswordRegistrationAllowed()) {
|
||||
// Keeps flashed banners, like an invitation's "finish joining {org}", across the redirect.
|
||||
session()->reflash();
|
||||
|
||||
return redirect()->route('login')->with('status', __(AuthenticationContract::PASSWORD_REGISTRATION_DISABLED_MESSAGE));
|
||||
}
|
||||
|
||||
return Inertia::render('Auth/Register', [
|
||||
'email' => session('registration_email', ''),
|
||||
'terms_url' => config('auth.terms_url'),
|
||||
@@ -93,13 +108,24 @@ class FortifyServiceProvider extends ServiceProvider
|
||||
->where('is_placeholder', '=', false)
|
||||
->first();
|
||||
|
||||
if ($user !== null && Hash::check($request->password, $user->password)) {
|
||||
// Always check a hash so the response time doesn't reveal whether the user exists
|
||||
$hasLocalPassword = $user !== null && $user->hasLocalPassword();
|
||||
$existingPasswordHash = $hasLocalPassword ? $user->password : self::ABSENT_USER_PASSWORD_HASH;
|
||||
|
||||
$passwordIsValid = Hash::check((string) $request->password, $existingPasswordHash);
|
||||
|
||||
if ($hasLocalPassword && $passwordIsValid && app(AuthenticationContract::class)->isPasswordLoginAllowed($user)) {
|
||||
return $user;
|
||||
}
|
||||
|
||||
return null;
|
||||
});
|
||||
|
||||
// Used by the password confirmation screen (e.g. before enabling 2FA) and OtherBrowserSessionsController
|
||||
Fortify::confirmPasswordsUsing(function (mixed $user, ?string $password): bool {
|
||||
return $user instanceof User && app(IdentityConfirmationService::class)->confirmPassword($user, $password);
|
||||
});
|
||||
|
||||
RateLimiter::for('login', function (Request $request) {
|
||||
$throttleKey = Str::transliterate(Str::lower($request->input(Fortify::username())).'|'.$request->ip());
|
||||
|
||||
|
||||
45
app/Service/AuthenticationContract.php
Normal file
45
app/Service/AuthenticationContract.php
Normal 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 is managed by your organization and cannot be changed here. Ask your administrator to change it.';
|
||||
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
}
|
||||
@@ -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) {
|
||||
|
||||
35
app/Service/IdentityConfirmationService.php
Normal file
35
app/Service/IdentityConfirmationService.php
Normal 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);
|
||||
}
|
||||
}
|
||||
@@ -78,6 +78,7 @@ class InvitationService
|
||||
$invitations = OrganizationInvitation::query()
|
||||
->whereRaw('lower(email) = ?', [strtolower($user->email)])
|
||||
->whereNotNull('accepted_at')
|
||||
->with('organization')
|
||||
->get();
|
||||
|
||||
foreach ($invitations as $invitation) {
|
||||
|
||||
@@ -26,10 +26,15 @@ use InvalidArgumentException;
|
||||
|
||||
class UserService
|
||||
{
|
||||
/**
|
||||
* Create a user. Without a password, the user can only sign in another way (e.g. via SSO).
|
||||
* The user joins the organizations of their accepted invitations. If an organization is given,
|
||||
* they also join it; otherwise they get their own organization if no invitation placed them anywhere.
|
||||
*/
|
||||
public function createUser(
|
||||
string $name,
|
||||
string $email,
|
||||
string $password,
|
||||
?string $password,
|
||||
string $timezone,
|
||||
Weekday $weekStart,
|
||||
?string $currency,
|
||||
@@ -38,12 +43,14 @@ class UserService
|
||||
?DateFormat $dateFormat = null,
|
||||
?IntervalFormat $intervalFormat = null,
|
||||
?TimeFormat $timeFormat = null,
|
||||
bool $verifyEmail = false
|
||||
bool $verifyEmail = false,
|
||||
?Organization $organization = null,
|
||||
Role $role = Role::Employee,
|
||||
): User {
|
||||
$user = new User;
|
||||
$user->name = $name;
|
||||
$user->email = strtolower($email);
|
||||
$user->password = Hash::make($password);
|
||||
$user->password = $password !== null ? Hash::make($password) : null;
|
||||
$user->timezone = $timezone;
|
||||
$user->week_start = $weekStart;
|
||||
if ($verifyEmail) {
|
||||
@@ -51,9 +58,16 @@ class UserService
|
||||
}
|
||||
$user->save();
|
||||
|
||||
$organizations = app(InvitationService::class)->processAcceptedInvitations($user);
|
||||
$invitedOrganizations = app(InvitationService::class)->processAcceptedInvitations($user);
|
||||
|
||||
if ($organizations->isEmpty()) {
|
||||
if ($organization !== null) {
|
||||
// An accepted invitation may already have added the user to the organization
|
||||
if ($invitedOrganizations->doesntContain(fn (Organization $invited): bool => $invited->is($organization))) {
|
||||
app(MemberService::class)->addMember($user, $organization, $role);
|
||||
} else {
|
||||
$this->switchCurrentOrganization($user, $organization);
|
||||
}
|
||||
} elseif ($invitedOrganizations->isEmpty()) {
|
||||
$organization = app(OrganizationService::class)->createOrganization(
|
||||
$this->getOrganizationNameForUserName($user->name),
|
||||
$user,
|
||||
|
||||
@@ -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', ''),
|
||||
|
||||
|
||||
@@ -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');
|
||||
|
||||
@@ -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);
|
||||
|
||||
|
||||
@@ -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>
|
||||
@@ -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>
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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 is managed by your organization and cannot be changed here.
|
||||
Ask your administrator to change it.
|
||||
</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
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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) });
|
||||
|
||||
@@ -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() })
|
||||
@@ -800,6 +804,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
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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'));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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'));
|
||||
|
||||
@@ -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(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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()]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
87
tests/Unit/Models/UserTest.php
Normal file
87
tests/Unit/Models/UserTest.php
Normal 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());
|
||||
}
|
||||
}
|
||||
@@ -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(),
|
||||
]);
|
||||
|
||||
93
tests/Unit/Service/IdentityConfirmationServiceTest.php
Normal file
93
tests/Unit/Service/IdentityConfirmationServiceTest.php
Normal 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);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -165,4 +167,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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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",
|
||||
]
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user