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\Enums\Weekday;
|
||||||
use App\Events\NewsletterRegistered;
|
use App\Events\NewsletterRegistered;
|
||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
|
use App\Service\AuthenticationContract;
|
||||||
use App\Service\InvitationService;
|
use App\Service\InvitationService;
|
||||||
use App\Service\IpLookup\IpLookupServiceContract;
|
use App\Service\IpLookup\IpLookupServiceContract;
|
||||||
use App\Service\TimezoneService;
|
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, [
|
$validated = Validator::make($input, [
|
||||||
'name' => [
|
'name' => [
|
||||||
'required',
|
'required',
|
||||||
@@ -109,17 +116,17 @@ class CreateNewUser implements CreatesNewUsers
|
|||||||
DB::transaction(function () use (&$user, $input, $timezone, $startOfWeek, $currency, $numberFormat, $currencyFormat, $dateFormat, $intervalFormat, $timeFormat): void {
|
DB::transaction(function () use (&$user, $input, $timezone, $startOfWeek, $currency, $numberFormat, $currencyFormat, $dateFormat, $intervalFormat, $timeFormat): void {
|
||||||
$userService = app(UserService::class);
|
$userService = app(UserService::class);
|
||||||
$user = $userService->createUser(
|
$user = $userService->createUser(
|
||||||
$input['name'],
|
name: $input['name'],
|
||||||
$input['email'],
|
email: $input['email'],
|
||||||
$input['password'],
|
password: $input['password'],
|
||||||
$timezone ?? 'UTC',
|
timezone: $timezone ?? 'UTC',
|
||||||
$startOfWeek,
|
weekStart: $startOfWeek,
|
||||||
$currency,
|
currency: $currency,
|
||||||
$numberFormat,
|
numberFormat: $numberFormat,
|
||||||
$currencyFormat,
|
currencyFormat: $currencyFormat,
|
||||||
$dateFormat,
|
dateFormat: $dateFormat,
|
||||||
$intervalFormat,
|
intervalFormat: $intervalFormat,
|
||||||
$timeFormat
|
timeFormat: $timeFormat,
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -5,8 +5,12 @@ declare(strict_types=1);
|
|||||||
namespace App\Actions\Fortify;
|
namespace App\Actions\Fortify;
|
||||||
|
|
||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
|
use App\Service\AuthenticationContract;
|
||||||
|
use Illuminate\Auth\Passwords\PasswordBroker;
|
||||||
use Illuminate\Support\Facades\Hash;
|
use Illuminate\Support\Facades\Hash;
|
||||||
|
use Illuminate\Support\Facades\Password;
|
||||||
use Illuminate\Support\Facades\Validator;
|
use Illuminate\Support\Facades\Validator;
|
||||||
|
use Illuminate\Validation\ValidationException;
|
||||||
use Laravel\Fortify\Contracts\ResetsUserPasswords;
|
use Laravel\Fortify\Contracts\ResetsUserPasswords;
|
||||||
|
|
||||||
class ResetUserPassword implements ResetsUserPasswords
|
class ResetUserPassword implements ResetsUserPasswords
|
||||||
@@ -20,6 +24,16 @@ class ResetUserPassword implements ResetsUserPasswords
|
|||||||
*/
|
*/
|
||||||
public function reset(User $user, array $input): void
|
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, [
|
Validator::make($input, [
|
||||||
'password' => $this->passwordRules(),
|
'password' => $this->passwordRules(),
|
||||||
])->validate();
|
])->validate();
|
||||||
|
|||||||
@@ -5,8 +5,10 @@ declare(strict_types=1);
|
|||||||
namespace App\Actions\Fortify;
|
namespace App\Actions\Fortify;
|
||||||
|
|
||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
|
use App\Service\IdentityConfirmationService;
|
||||||
use Illuminate\Support\Facades\Hash;
|
use Illuminate\Support\Facades\Hash;
|
||||||
use Illuminate\Support\Facades\Validator;
|
use Illuminate\Support\Facades\Validator;
|
||||||
|
use Illuminate\Validation\ValidationException;
|
||||||
use Laravel\Fortify\Contracts\UpdatesUserPasswords;
|
use Laravel\Fortify\Contracts\UpdatesUserPasswords;
|
||||||
|
|
||||||
class UpdateUserPassword implements UpdatesUserPasswords
|
class UpdateUserPassword implements UpdatesUserPasswords
|
||||||
@@ -20,6 +22,13 @@ class UpdateUserPassword implements UpdatesUserPasswords
|
|||||||
*/
|
*/
|
||||||
public function update(User $user, array $input): void
|
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, [
|
Validator::make($input, [
|
||||||
'current_password' => ['required', 'string', 'current_password:web'],
|
'current_password' => ['required', 'string', 'current_password:web'],
|
||||||
'password' => $this->passwordRules(),
|
'password' => $this->passwordRules(),
|
||||||
|
|||||||
@@ -59,13 +59,13 @@ class UserCreateCommand extends Command
|
|||||||
$user = null;
|
$user = null;
|
||||||
DB::transaction(function () use (&$user, $name, $email, $password, $verifyEmail): void {
|
DB::transaction(function () use (&$user, $name, $email, $password, $verifyEmail): void {
|
||||||
$user = app(UserService::class)->createUser(
|
$user = app(UserService::class)->createUser(
|
||||||
$name,
|
name: $name,
|
||||||
$email,
|
email: $email,
|
||||||
$password,
|
password: $password,
|
||||||
'UTC',
|
timezone: 'UTC',
|
||||||
Weekday::Monday,
|
weekStart: Weekday::Monday,
|
||||||
null,
|
currency: null,
|
||||||
verifyEmail: $verifyEmail
|
verifyEmail: $verifyEmail,
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
/** @var Organization|null $organization */
|
/** @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);
|
$userService = app(UserService::class);
|
||||||
$user = $userService->createUser(
|
$user = $userService->createUser(
|
||||||
$data['name'],
|
name: $data['name'],
|
||||||
$data['email'],
|
email: $data['email'],
|
||||||
$data['password_create'],
|
password: $data['password_create'],
|
||||||
$data['timezone'],
|
timezone: $data['timezone'],
|
||||||
$data['week_start'] instanceof Weekday ? $data['week_start'] : Weekday::from($data['week_start']),
|
weekStart: $data['week_start'] instanceof Weekday ? $data['week_start'] : Weekday::from($data['week_start']),
|
||||||
$data['currency'],
|
currency: $data['currency'],
|
||||||
verifyEmail: (bool) $data['is_email_verified']
|
verifyEmail: (bool) $data['is_email_verified'],
|
||||||
);
|
);
|
||||||
|
|
||||||
return $user;
|
return $user;
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ use App\Http\Resources\V1\User\UserResource;
|
|||||||
use App\Mail\VerifyUpdatedEmailMail;
|
use App\Mail\VerifyUpdatedEmailMail;
|
||||||
use App\Models\Organization;
|
use App\Models\Organization;
|
||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
|
use App\Service\AuthenticationContract;
|
||||||
use App\Service\DeletionService;
|
use App\Service\DeletionService;
|
||||||
use App\Service\UserService;
|
use App\Service\UserService;
|
||||||
use App\Support\Base64File;
|
use App\Support\Base64File;
|
||||||
@@ -21,6 +22,7 @@ use Illuminate\Http\JsonResponse;
|
|||||||
use Illuminate\Support\Facades\Mail;
|
use Illuminate\Support\Facades\Mail;
|
||||||
use Illuminate\Support\Facades\Storage;
|
use Illuminate\Support\Facades\Storage;
|
||||||
use Illuminate\Support\Str;
|
use Illuminate\Support\Str;
|
||||||
|
use Illuminate\Validation\ValidationException;
|
||||||
|
|
||||||
class UserController extends Controller
|
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 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 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()) {
|
if ($user->getKey() !== $this->user()->getKey()) {
|
||||||
throw new AuthorizationException;
|
throw new AuthorizationException;
|
||||||
@@ -178,6 +181,11 @@ class UserController extends Controller
|
|||||||
throw new UserResendEmailVerificationNoPendingEmailApiException;
|
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)
|
Mail::to($user->pending_email)
|
||||||
->queue(new VerifyUpdatedEmailMail($user, $user->pending_email));
|
->queue(new VerifyUpdatedEmailMail($user, $user->pending_email));
|
||||||
|
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ declare(strict_types=1);
|
|||||||
|
|
||||||
namespace App\Http\Controllers\Web;
|
namespace App\Http\Controllers\Web;
|
||||||
|
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Service\IdentityConfirmationService;
|
||||||
use Illuminate\Contracts\Auth\StatefulGuard;
|
use Illuminate\Contracts\Auth\StatefulGuard;
|
||||||
use Illuminate\Http\RedirectResponse;
|
use Illuminate\Http\RedirectResponse;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
@@ -17,8 +19,27 @@ class OtherBrowserSessionsController extends Controller
|
|||||||
/**
|
/**
|
||||||
* Log the user out of their other browser sessions across all devices.
|
* 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');
|
$password = (string) $request->string('password');
|
||||||
|
|
||||||
$confirmed = app(ConfirmPassword::class)($guard, $request->user(), $password);
|
$confirmed = app(ConfirmPassword::class)($guard, $request->user(), $password);
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ declare(strict_types=1);
|
|||||||
namespace App\Http\Controllers\Web;
|
namespace App\Http\Controllers\Web;
|
||||||
|
|
||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
|
use App\Service\AuthenticationContract;
|
||||||
use Illuminate\Http\RedirectResponse;
|
use Illuminate\Http\RedirectResponse;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Illuminate\Support\Carbon;
|
use Illuminate\Support\Carbon;
|
||||||
@@ -12,7 +13,7 @@ use Illuminate\Support\Str;
|
|||||||
|
|
||||||
class UserController extends Controller
|
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()) {
|
if ($request->user()?->getAuthIdentifier() !== $user->getKey()) {
|
||||||
abort(403);
|
abort(403);
|
||||||
@@ -29,6 +30,16 @@ class UserController extends Controller
|
|||||||
abort(403);
|
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()
|
$emailAlreadyInUse = User::query()
|
||||||
->where('email', '=', $email)
|
->where('email', '=', $email)
|
||||||
->where('is_placeholder', '=', false)
|
->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;
|
namespace App\Http\Requests\V1\Organization;
|
||||||
|
|
||||||
use App\Http\Requests\V1\BaseFormRequest;
|
use App\Http\Requests\V1\BaseFormRequest;
|
||||||
use Illuminate\Support\Facades\Hash;
|
use App\Http\Requests\V1\Concerns\ConfirmsIdentity;
|
||||||
use Illuminate\Validation\Validator;
|
use Illuminate\Validation\Validator;
|
||||||
|
|
||||||
class OrganizationDestroyRequest extends BaseFormRequest
|
class OrganizationDestroyRequest extends BaseFormRequest
|
||||||
{
|
{
|
||||||
|
use ConfirmsIdentity;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get the validation rules that apply to the request.
|
* Get the validation rules that apply to the request.
|
||||||
*
|
*
|
||||||
@@ -17,12 +19,7 @@ class OrganizationDestroyRequest extends BaseFormRequest
|
|||||||
*/
|
*/
|
||||||
public function rules(): array
|
public function rules(): array
|
||||||
{
|
{
|
||||||
return [
|
return $this->identityConfirmationRules();
|
||||||
'password' => [
|
|
||||||
'required',
|
|
||||||
'string',
|
|
||||||
],
|
|
||||||
];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -31,18 +28,7 @@ class OrganizationDestroyRequest extends BaseFormRequest
|
|||||||
public function after(): array
|
public function after(): array
|
||||||
{
|
{
|
||||||
return [
|
return [
|
||||||
function (Validator $validator): void {
|
fn (Validator $validator) => $this->validateIdentityConfirmation($validator),
|
||||||
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.'));
|
|
||||||
}
|
|
||||||
},
|
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,11 +5,13 @@ declare(strict_types=1);
|
|||||||
namespace App\Http\Requests\V1\User;
|
namespace App\Http\Requests\V1\User;
|
||||||
|
|
||||||
use App\Http\Requests\V1\BaseFormRequest;
|
use App\Http\Requests\V1\BaseFormRequest;
|
||||||
use Illuminate\Support\Facades\Hash;
|
use App\Http\Requests\V1\Concerns\ConfirmsIdentity;
|
||||||
use Illuminate\Validation\Validator;
|
use Illuminate\Validation\Validator;
|
||||||
|
|
||||||
class UserDestroyRequest extends BaseFormRequest
|
class UserDestroyRequest extends BaseFormRequest
|
||||||
{
|
{
|
||||||
|
use ConfirmsIdentity;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get the validation rules that apply to the request.
|
* Get the validation rules that apply to the request.
|
||||||
*
|
*
|
||||||
@@ -17,12 +19,7 @@ class UserDestroyRequest extends BaseFormRequest
|
|||||||
*/
|
*/
|
||||||
public function rules(): array
|
public function rules(): array
|
||||||
{
|
{
|
||||||
return [
|
return $this->identityConfirmationRules();
|
||||||
'password' => [
|
|
||||||
'required',
|
|
||||||
'string',
|
|
||||||
],
|
|
||||||
];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -31,18 +28,7 @@ class UserDestroyRequest extends BaseFormRequest
|
|||||||
public function after(): array
|
public function after(): array
|
||||||
{
|
{
|
||||||
return [
|
return [
|
||||||
function (Validator $validator): void {
|
fn (Validator $validator) => $this->validateIdentityConfirmation($validator),
|
||||||
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.'));
|
|
||||||
}
|
|
||||||
},
|
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,6 +8,8 @@ use App\Enums\Weekday;
|
|||||||
use App\Http\Requests\V1\BaseFormRequest;
|
use App\Http\Requests\V1\BaseFormRequest;
|
||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
use App\Rules\Base64ImageRule;
|
use App\Rules\Base64ImageRule;
|
||||||
|
use App\Service\AuthenticationContract;
|
||||||
|
use Closure;
|
||||||
use Illuminate\Contracts\Validation\ValidationRule;
|
use Illuminate\Contracts\Validation\ValidationRule;
|
||||||
use Illuminate\Database\Eloquent\Builder;
|
use Illuminate\Database\Eloquent\Builder;
|
||||||
use Illuminate\Support\Str;
|
use Illuminate\Support\Str;
|
||||||
@@ -31,7 +33,7 @@ class UserUpdateRequest extends BaseFormRequest
|
|||||||
/**
|
/**
|
||||||
* Get the validation rules that apply to the request.
|
* 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
|
public function rules(): array
|
||||||
{
|
{
|
||||||
@@ -48,6 +50,16 @@ class UserUpdateRequest extends BaseFormRequest
|
|||||||
return $query->where('is_placeholder', '=', false)
|
return $query->where('is_placeholder', '=', false)
|
||||||
->whereKeyNot($this->user->getKey());
|
->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' => [
|
'photo' => [
|
||||||
'nullable',
|
'nullable',
|
||||||
|
|||||||
@@ -7,6 +7,8 @@ namespace App\Http\Resources\V1\User;
|
|||||||
use App\Enums\Weekday;
|
use App\Enums\Weekday;
|
||||||
use App\Http\Resources\V1\BaseResource;
|
use App\Http\Resources\V1\BaseResource;
|
||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
|
use App\Service\AuthenticationContract;
|
||||||
|
use App\Service\IdentityConfirmationService;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -38,6 +40,10 @@ class UserResource extends BaseResource
|
|||||||
'week_start' => $this->resource->week_start->value,
|
'week_start' => $this->resource->week_start->value,
|
||||||
/** Whether to email the user when a time entry has been running for more than 8 hours */
|
/** 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,
|
'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\CustomAuditable;
|
||||||
use App\Models\Concerns\HasUuids;
|
use App\Models\Concerns\HasUuids;
|
||||||
use App\Models\Passport\Token;
|
use App\Models\Passport\Token;
|
||||||
|
use App\Service\AuthenticationContract;
|
||||||
use Database\Factories\UserFactory;
|
use Database\Factories\UserFactory;
|
||||||
use Filament\Models\Contracts\FilamentUser;
|
use Filament\Models\Contracts\FilamentUser;
|
||||||
use Filament\Panel;
|
use Filament\Panel;
|
||||||
|
use Illuminate\Auth\Notifications\ResetPassword;
|
||||||
use Illuminate\Contracts\Auth\MustVerifyEmail;
|
use Illuminate\Contracts\Auth\MustVerifyEmail;
|
||||||
use Illuminate\Database\Eloquent\Builder;
|
use Illuminate\Database\Eloquent\Builder;
|
||||||
use Illuminate\Database\Eloquent\Casts\Attribute;
|
use Illuminate\Database\Eloquent\Casts\Attribute;
|
||||||
@@ -24,6 +26,7 @@ use Illuminate\Foundation\Auth\User as Authenticatable;
|
|||||||
use Illuminate\Notifications\Notifiable;
|
use Illuminate\Notifications\Notifiable;
|
||||||
use Illuminate\Support\Carbon;
|
use Illuminate\Support\Carbon;
|
||||||
use Illuminate\Support\Facades\Storage;
|
use Illuminate\Support\Facades\Storage;
|
||||||
|
use Illuminate\Support\Str;
|
||||||
use Laravel\Fortify\TwoFactorAuthenticatable;
|
use Laravel\Fortify\TwoFactorAuthenticatable;
|
||||||
use Laravel\Passport\AuthCode;
|
use Laravel\Passport\AuthCode;
|
||||||
use Laravel\Passport\Contracts\OAuthenticatable;
|
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';
|
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
|
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();
|
&& $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
|
public function isMemberOfOrganization(Organization $organization): bool
|
||||||
{
|
{
|
||||||
if ($this->relationLoaded('organizations')) {
|
if ($this->relationLoaded('organizations')) {
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ use App\Models\Tag;
|
|||||||
use App\Models\Task;
|
use App\Models\Task;
|
||||||
use App\Models\TimeEntry;
|
use App\Models\TimeEntry;
|
||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
|
use App\Service\AuthenticationContract;
|
||||||
use App\Service\BillingContract;
|
use App\Service\BillingContract;
|
||||||
use App\Service\GoalsContract;
|
use App\Service\GoalsContract;
|
||||||
use App\Service\IpLookup\IpLookupServiceContract;
|
use App\Service\IpLookup\IpLookupServiceContract;
|
||||||
@@ -109,6 +110,7 @@ class AppServiceProvider extends ServiceProvider
|
|||||||
$this->app->bind(IpLookupServiceContract::class, NoIpLookupService::class);
|
$this->app->bind(IpLookupServiceContract::class, NoIpLookupService::class);
|
||||||
$this->app->bind(BillingContract::class);
|
$this->app->bind(BillingContract::class);
|
||||||
$this->app->bind(GoalsContract::class);
|
$this->app->bind(GoalsContract::class);
|
||||||
|
$this->app->bind(AuthenticationContract::class);
|
||||||
|
|
||||||
// Storage
|
// Storage
|
||||||
// The local driver ignores the ResponseContentDisposition option of temporaryUrl,
|
// 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\CustomLoginResponse;
|
||||||
use App\Extensions\Fortify\CustomTwoFactorLoginResponse;
|
use App\Extensions\Fortify\CustomTwoFactorLoginResponse;
|
||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
|
use App\Service\AuthenticationContract;
|
||||||
|
use App\Service\IdentityConfirmationService;
|
||||||
use Illuminate\Cache\RateLimiting\Limit;
|
use Illuminate\Cache\RateLimiting\Limit;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Illuminate\Support\Facades\Hash;
|
use Illuminate\Support\Facades\Hash;
|
||||||
@@ -25,6 +27,12 @@ use Laravel\Fortify\Fortify;
|
|||||||
|
|
||||||
class FortifyServiceProvider extends ServiceProvider
|
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.
|
* Register any application services.
|
||||||
*/
|
*/
|
||||||
@@ -44,6 +52,13 @@ class FortifyServiceProvider extends ServiceProvider
|
|||||||
Fortify::resetUserPasswordsUsing(ResetUserPassword::class);
|
Fortify::resetUserPasswordsUsing(ResetUserPassword::class);
|
||||||
|
|
||||||
Fortify::registerView(function () {
|
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', [
|
return Inertia::render('Auth/Register', [
|
||||||
'email' => session('registration_email', ''),
|
'email' => session('registration_email', ''),
|
||||||
'terms_url' => config('auth.terms_url'),
|
'terms_url' => config('auth.terms_url'),
|
||||||
@@ -93,13 +108,24 @@ class FortifyServiceProvider extends ServiceProvider
|
|||||||
->where('is_placeholder', '=', false)
|
->where('is_placeholder', '=', false)
|
||||||
->first();
|
->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 $user;
|
||||||
}
|
}
|
||||||
|
|
||||||
return null;
|
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) {
|
RateLimiter::for('login', function (Request $request) {
|
||||||
$throttleKey = Str::transliterate(Str::lower($request->input(Fortify::username())).'|'.$request->ip());
|
$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\Enums\Role;
|
||||||
use App\Events\BeforeOrganizationDeletion;
|
use App\Events\BeforeOrganizationDeletion;
|
||||||
|
use App\Events\BeforeUserDeletion;
|
||||||
use App\Exceptions\Api\CanNotDeleteUserWhoIsOwnerOfOrganizationWithMultipleMembers;
|
use App\Exceptions\Api\CanNotDeleteUserWhoIsOwnerOfOrganizationWithMultipleMembers;
|
||||||
use App\Models\Client;
|
use App\Models\Client;
|
||||||
use App\Models\Goal;
|
use App\Models\Goal;
|
||||||
@@ -164,6 +165,8 @@ class DeletionService
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
BeforeUserDeletion::dispatch($user);
|
||||||
|
|
||||||
/** @var Member $member */
|
/** @var Member $member */
|
||||||
foreach ($members as $member) {
|
foreach ($members as $member) {
|
||||||
if ($member->role === Role::Owner->value) {
|
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()
|
$invitations = OrganizationInvitation::query()
|
||||||
->whereRaw('lower(email) = ?', [strtolower($user->email)])
|
->whereRaw('lower(email) = ?', [strtolower($user->email)])
|
||||||
->whereNotNull('accepted_at')
|
->whereNotNull('accepted_at')
|
||||||
|
->with('organization')
|
||||||
->get();
|
->get();
|
||||||
|
|
||||||
foreach ($invitations as $invitation) {
|
foreach ($invitations as $invitation) {
|
||||||
|
|||||||
@@ -26,10 +26,15 @@ use InvalidArgumentException;
|
|||||||
|
|
||||||
class UserService
|
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(
|
public function createUser(
|
||||||
string $name,
|
string $name,
|
||||||
string $email,
|
string $email,
|
||||||
string $password,
|
?string $password,
|
||||||
string $timezone,
|
string $timezone,
|
||||||
Weekday $weekStart,
|
Weekday $weekStart,
|
||||||
?string $currency,
|
?string $currency,
|
||||||
@@ -38,12 +43,14 @@ class UserService
|
|||||||
?DateFormat $dateFormat = null,
|
?DateFormat $dateFormat = null,
|
||||||
?IntervalFormat $intervalFormat = null,
|
?IntervalFormat $intervalFormat = null,
|
||||||
?TimeFormat $timeFormat = null,
|
?TimeFormat $timeFormat = null,
|
||||||
bool $verifyEmail = false
|
bool $verifyEmail = false,
|
||||||
|
?Organization $organization = null,
|
||||||
|
Role $role = Role::Employee,
|
||||||
): User {
|
): User {
|
||||||
$user = new User;
|
$user = new User;
|
||||||
$user->name = $name;
|
$user->name = $name;
|
||||||
$user->email = strtolower($email);
|
$user->email = strtolower($email);
|
||||||
$user->password = Hash::make($password);
|
$user->password = $password !== null ? Hash::make($password) : null;
|
||||||
$user->timezone = $timezone;
|
$user->timezone = $timezone;
|
||||||
$user->week_start = $weekStart;
|
$user->week_start = $weekStart;
|
||||||
if ($verifyEmail) {
|
if ($verifyEmail) {
|
||||||
@@ -51,9 +58,16 @@ class UserService
|
|||||||
}
|
}
|
||||||
$user->save();
|
$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(
|
$organization = app(OrganizationService::class)->createOrganization(
|
||||||
$this->getOrganizationNameForUserName($user->name),
|
$this->getOrganizationNameForUserName($user->name),
|
||||||
$user,
|
$user,
|
||||||
|
|||||||
@@ -116,7 +116,11 @@ return [
|
|||||||
|
|
||||||
'password_timeout' => env('AUTH_PASSWORD_TIMEOUT', 10800),
|
'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', ''),
|
'terms_url' => env('TERMS_URL', ''),
|
||||||
|
|
||||||
|
|||||||
@@ -511,6 +511,29 @@ test.describe('Organization Create, Delete & Switch', () => {
|
|||||||
await expect(dialog).toBeVisible();
|
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 }) => {
|
test('can switch the current organization via the organization switcher', async ({ page }) => {
|
||||||
await page.goto(PLAYWRIGHT_BASE_URL + '/dashboard');
|
await page.goto(PLAYWRIGHT_BASE_URL + '/dashboard');
|
||||||
const orgSwitcher = page.locator('[data-testid="organization_switcher"]:visible');
|
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();
|
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 ({
|
test('delete account succeeds with the correct password and logs the user out', async ({
|
||||||
page,
|
page,
|
||||||
}) => {
|
}) => {
|
||||||
@@ -764,6 +781,27 @@ test('test that 2FA can be enabled with correct password', async ({ page }) => {
|
|||||||
// Logout Other Browser Sessions Tests
|
// 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 }) => {
|
test('test that logout other browser sessions works with correct password', async ({ page }) => {
|
||||||
await goToProfilePage(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 PrimaryButton from '@/packages/ui/src/Buttons/PrimaryButton.vue';
|
||||||
import TextInput from '@/packages/ui/src/Input/TextInput.vue';
|
import TextInput from '@/packages/ui/src/Input/TextInput.vue';
|
||||||
|
|
||||||
defineProps({
|
withDefaults(
|
||||||
canResetPassword: Boolean,
|
defineProps<{
|
||||||
status: String,
|
canResetPassword?: boolean;
|
||||||
});
|
status?: string;
|
||||||
|
}>(),
|
||||||
|
{
|
||||||
|
canResetPassword: false,
|
||||||
|
status: '',
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
const form = useForm({
|
const form = useForm({
|
||||||
email: '',
|
email: '',
|
||||||
@@ -28,8 +34,8 @@ const submit = () => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const page = usePage<{
|
const page = usePage<{
|
||||||
flash: {
|
flash?: {
|
||||||
message: string;
|
message?: string;
|
||||||
};
|
};
|
||||||
}>();
|
}>();
|
||||||
</script>
|
</script>
|
||||||
@@ -61,6 +67,9 @@ const page = usePage<{
|
|||||||
{{ page.props.flash?.message }}
|
{{ page.props.flash?.message }}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- Extension seam: alternative-auth errors (e.g. SSO callback failures) -->
|
||||||
|
<slot name="error" />
|
||||||
|
|
||||||
<form @submit.prevent="submit">
|
<form @submit.prevent="submit">
|
||||||
<Field>
|
<Field>
|
||||||
<FieldLabel for="email">Email</FieldLabel>
|
<FieldLabel for="email">Email</FieldLabel>
|
||||||
@@ -103,5 +112,8 @@ const page = usePage<{
|
|||||||
</PrimaryButton>
|
</PrimaryButton>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
|
|
||||||
|
<!-- Extension seam: alternative auth methods (e.g. SSO providers) -->
|
||||||
|
<slot name="alternatives" />
|
||||||
</AuthenticationCard>
|
</AuthenticationCard>
|
||||||
</template>
|
</template>
|
||||||
|
|||||||
@@ -1,29 +1,32 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { ref } from 'vue';
|
import { ref } from 'vue';
|
||||||
import ActionSection from '@/Components/ActionSection.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 DangerButton from '@/packages/ui/src/Buttons/DangerButton.vue';
|
||||||
import DialogModal from '@/packages/ui/src/DialogModal.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 SecondaryButton from '@/packages/ui/src/Buttons/SecondaryButton.vue';
|
||||||
import TextInput from '@/packages/ui/src/Input/TextInput.vue';
|
|
||||||
import { useDeleteUserMutation } from '@/utils/useUserQuery';
|
import { useDeleteUserMutation } from '@/utils/useUserQuery';
|
||||||
import { getCurrentUserId } from '@/utils/useUser';
|
import { getCurrentUserId } from '@/utils/useUser';
|
||||||
|
|
||||||
|
const props = defineProps<{
|
||||||
|
confirmsWithPassword: boolean;
|
||||||
|
}>();
|
||||||
|
|
||||||
const deleteUserMutation = useDeleteUserMutation();
|
const deleteUserMutation = useDeleteUserMutation();
|
||||||
|
|
||||||
const confirmingUserDeletion = ref(false);
|
const confirmingUserDeletion = ref(false);
|
||||||
const passwordInput = ref<HTMLInputElement | null>(null);
|
const confirmationInput = ref<InstanceType<typeof IdentityConfirmationInput> | null>(null);
|
||||||
const password = ref('');
|
const password = ref('');
|
||||||
const passwordError = ref('');
|
const passwordError = ref('');
|
||||||
const processing = ref(false);
|
const processing = ref(false);
|
||||||
|
|
||||||
function confirmUserDeletion() {
|
function confirmUserDeletion() {
|
||||||
confirmingUserDeletion.value = true;
|
confirmingUserDeletion.value = true;
|
||||||
setTimeout(() => passwordInput.value?.focus(), 250);
|
setTimeout(() => confirmationInput.value?.focus(), 250);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function deleteUser() {
|
async function deleteUser() {
|
||||||
if (processing.value) return;
|
if (processing.value || !props.confirmsWithPassword) return;
|
||||||
processing.value = true;
|
processing.value = true;
|
||||||
passwordError.value = '';
|
passwordError.value = '';
|
||||||
try {
|
try {
|
||||||
@@ -41,7 +44,7 @@ async function deleteUser() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
processing.value = false;
|
processing.value = false;
|
||||||
passwordInput.value?.focus();
|
confirmationInput.value?.focus();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -75,21 +78,18 @@ function closeModal() {
|
|||||||
|
|
||||||
<template #content>
|
<template #content>
|
||||||
Are you sure you want to delete your account? Once your account is deleted, all
|
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
|
of its resources and data will be permanently deleted.
|
||||||
password to confirm you would like to permanently delete your account.
|
<template v-if="confirmsWithPassword">
|
||||||
|
Please enter your password to confirm you would like to permanently delete
|
||||||
|
your account.
|
||||||
|
</template>
|
||||||
|
|
||||||
<Field class="mt-4">
|
<IdentityConfirmationInput
|
||||||
<TextInput
|
ref="confirmationInput"
|
||||||
ref="passwordInput"
|
v-model:password="password"
|
||||||
v-model="password"
|
:confirms-with-password="confirmsWithPassword"
|
||||||
type="password"
|
:error="passwordError"
|
||||||
class="block w-3/4"
|
@submit="deleteUser" />
|
||||||
placeholder="Password"
|
|
||||||
autocomplete="current-password"
|
|
||||||
@keyup.enter="deleteUser" />
|
|
||||||
|
|
||||||
<FieldError v-if="passwordError">{{ passwordError }}</FieldError>
|
|
||||||
</Field>
|
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<template #footer>
|
<template #footer>
|
||||||
@@ -97,8 +97,8 @@ function closeModal() {
|
|||||||
|
|
||||||
<DangerButton
|
<DangerButton
|
||||||
class="ms-3"
|
class="ms-3"
|
||||||
:class="{ 'opacity-25': processing }"
|
:class="{ 'opacity-25': processing || !confirmsWithPassword }"
|
||||||
:disabled="processing"
|
:disabled="processing || !confirmsWithPassword"
|
||||||
@click="deleteUser">
|
@click="deleteUser">
|
||||||
Delete Account
|
Delete Account
|
||||||
</DangerButton>
|
</DangerButton>
|
||||||
|
|||||||
@@ -4,18 +4,19 @@ import { useForm } from '@inertiajs/vue3';
|
|||||||
import ActionMessage from '@/Components/ActionMessage.vue';
|
import ActionMessage from '@/Components/ActionMessage.vue';
|
||||||
import ActionSection from '@/Components/ActionSection.vue';
|
import ActionSection from '@/Components/ActionSection.vue';
|
||||||
import DialogModal from '@/packages/ui/src/DialogModal.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 PrimaryButton from '@/packages/ui/src/Buttons/PrimaryButton.vue';
|
||||||
import SecondaryButton from '@/packages/ui/src/Buttons/SecondaryButton.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';
|
import type { Session } from '@/types/jetstream';
|
||||||
|
|
||||||
defineProps<{
|
const props = defineProps<{
|
||||||
sessions: Session[];
|
sessions: Session[];
|
||||||
|
confirmsWithPassword: boolean;
|
||||||
}>();
|
}>();
|
||||||
|
|
||||||
const confirmingLogout = ref(false);
|
const confirmingLogout = ref(false);
|
||||||
const passwordInput = ref<HTMLElement | null>(null);
|
const confirmationInput = ref<InstanceType<typeof IdentityConfirmationInput> | null>(null);
|
||||||
|
|
||||||
const form = useForm({
|
const form = useForm({
|
||||||
password: '',
|
password: '',
|
||||||
@@ -23,23 +24,27 @@ const form = useForm({
|
|||||||
|
|
||||||
const confirmLogout = () => {
|
const confirmLogout = () => {
|
||||||
confirmingLogout.value = true;
|
confirmingLogout.value = true;
|
||||||
|
setTimeout(() => confirmationInput.value?.focus(), 250);
|
||||||
setTimeout(() => passwordInput.value?.focus(), 250);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const logoutOtherBrowserSessions = () => {
|
const logoutOtherBrowserSessions = () => {
|
||||||
form.delete(route('other-browser-sessions.destroy'), {
|
if (form.processing) return;
|
||||||
preserveScroll: true,
|
// Users without a password log out other sessions without confirming, see OtherBrowserSessionsController.
|
||||||
onSuccess: () => closeModal(),
|
form.transform(() => (props.confirmsWithPassword ? { password: form.password } : {})).delete(
|
||||||
onError: () => passwordInput.value?.focus(),
|
route('other-browser-sessions.destroy'),
|
||||||
onFinish: () => form.reset(),
|
{
|
||||||
});
|
preserveScroll: true,
|
||||||
|
onSuccess: () => closeModal(),
|
||||||
|
onError: () => confirmationInput.value?.focus(),
|
||||||
|
onFinish: () => form.reset(),
|
||||||
|
}
|
||||||
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
const closeModal = () => {
|
const closeModal = () => {
|
||||||
confirmingLogout.value = false;
|
confirmingLogout.value = false;
|
||||||
|
|
||||||
form.reset();
|
form.reset();
|
||||||
|
form.clearErrors();
|
||||||
};
|
};
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
@@ -55,8 +60,11 @@ const closeModal = () => {
|
|||||||
<div class="max-w-xl text-sm text-text-secondary">
|
<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
|
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
|
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
|
not be exhaustive.
|
||||||
update your password.
|
<template v-if="confirmsWithPassword">
|
||||||
|
If you feel your account has been compromised, you should also update your
|
||||||
|
password.
|
||||||
|
</template>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Other Browser Sessions -->
|
<!-- Other Browser Sessions -->
|
||||||
@@ -128,23 +136,21 @@ const closeModal = () => {
|
|||||||
<template #title> Log Out Other Browser Sessions </template>
|
<template #title> Log Out Other Browser Sessions </template>
|
||||||
|
|
||||||
<template #content>
|
<template #content>
|
||||||
Please enter your password to confirm you would like to log out of your other
|
Log out of your other browser sessions across all of your devices.
|
||||||
browser sessions across all of your devices.
|
<template v-if="confirmsWithPassword"
|
||||||
|
>Please enter your password to confirm.</template
|
||||||
|
>
|
||||||
|
|
||||||
<Field class="mt-4">
|
<IdentityConfirmationInput
|
||||||
<TextInput
|
v-if="confirmsWithPassword"
|
||||||
ref="passwordInput"
|
ref="confirmationInput"
|
||||||
v-model="form.password"
|
v-model:password="form.password"
|
||||||
type="password"
|
:confirms-with-password="confirmsWithPassword"
|
||||||
class="block w-3/4"
|
:error="form.errors.password ?? ''"
|
||||||
placeholder="Password"
|
@submit="logoutOtherBrowserSessions" />
|
||||||
autocomplete="current-password"
|
<FieldError v-else-if="form.errors.password" class="mt-4">{{
|
||||||
@keyup.enter="logoutOtherBrowserSessions" />
|
form.errors.password
|
||||||
|
}}</FieldError>
|
||||||
<FieldError v-if="form.errors.password">{{
|
|
||||||
form.errors.password
|
|
||||||
}}</FieldError>
|
|
||||||
</Field>
|
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<template #footer>
|
<template #footer>
|
||||||
|
|||||||
@@ -250,11 +250,19 @@ onBeforeUnmount(() => {
|
|||||||
type="email"
|
type="email"
|
||||||
class="block w-full"
|
class="block w-full"
|
||||||
required
|
required
|
||||||
:disabled="!isUserLoaded"
|
:disabled="!user?.can_change_email"
|
||||||
autocomplete="username" />
|
autocomplete="username" />
|
||||||
<FieldError v-if="fieldErrors.email">{{ fieldErrors.email }}</FieldError>
|
<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">
|
<p class="text-text-primary">
|
||||||
A verification link was sent to
|
A verification link was sent to
|
||||||
<span class="font-medium">{{ pendingEmail }}</span
|
<span class="font-medium">{{ pendingEmail }}</span
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
|
import ActionSection from '@/Components/ActionSection.vue';
|
||||||
import AppLayout from '@/Layouts/AppLayout.vue';
|
import AppLayout from '@/Layouts/AppLayout.vue';
|
||||||
import DeleteUserForm from '@/Pages/Profile/Partials/DeleteUserForm.vue';
|
import DeleteUserForm from '@/Pages/Profile/Partials/DeleteUserForm.vue';
|
||||||
import LogoutOtherBrowserSessionsForm from '@/Pages/Profile/Partials/LogoutOtherBrowserSessionsForm.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 ApiTokensForm from '@/Pages/Profile/Partials/ApiTokensForm.vue';
|
||||||
import ThemeForm from '@/Pages/Profile/Partials/ThemeForm.vue';
|
import ThemeForm from '@/Pages/Profile/Partials/ThemeForm.vue';
|
||||||
import NotificationSettingsForm from '@/Pages/Profile/Partials/NotificationSettingsForm.vue';
|
import NotificationSettingsForm from '@/Pages/Profile/Partials/NotificationSettingsForm.vue';
|
||||||
|
import { useUserQuery } from '@/utils/useUserQuery';
|
||||||
|
import { computed } from 'vue';
|
||||||
|
|
||||||
defineProps<{
|
defineProps<{
|
||||||
confirmsTwoFactorAuthentication: boolean;
|
confirmsTwoFactorAuthentication: boolean;
|
||||||
sessions: Session[];
|
sessions: Session[];
|
||||||
}>();
|
}>();
|
||||||
|
|
||||||
|
const { user } = useUserQuery();
|
||||||
|
const confirmsWithPassword = computed(() => user.value?.confirms_with_password ?? false);
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
@@ -43,28 +49,52 @@ defineProps<{
|
|||||||
<SectionBorder />
|
<SectionBorder />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div>
|
<template v-if="confirmsWithPassword">
|
||||||
<UpdatePasswordForm class="mt-10 sm:mt-0" />
|
<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 />
|
<SectionBorder />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div>
|
<LogoutOtherBrowserSessionsForm
|
||||||
<TwoFactorAuthenticationForm
|
:sessions="sessions"
|
||||||
:requires-confirmation="confirmsTwoFactorAuthentication"
|
:confirms-with-password="confirmsWithPassword"
|
||||||
class="mt-10 sm:mt-0" />
|
class="mt-10 sm:mt-0" />
|
||||||
|
|
||||||
<SectionBorder />
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<LogoutOtherBrowserSessionsForm :sessions="sessions" class="mt-10 sm:mt-0" />
|
|
||||||
<SectionBorder />
|
<SectionBorder />
|
||||||
|
|
||||||
<ApiTokensForm></ApiTokensForm>
|
<ApiTokensForm></ApiTokensForm>
|
||||||
|
|
||||||
<SectionBorder />
|
<SectionBorder />
|
||||||
|
|
||||||
<DeleteUserForm class="mt-10 sm:mt-0" />
|
<DeleteUserForm
|
||||||
|
class="mt-10 sm:mt-0"
|
||||||
|
:confirms-with-password="confirmsWithPassword" />
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</AppLayout>
|
</AppLayout>
|
||||||
|
|||||||
@@ -2,19 +2,19 @@
|
|||||||
import { ref } from 'vue';
|
import { ref } from 'vue';
|
||||||
import { router } from '@inertiajs/vue3';
|
import { router } from '@inertiajs/vue3';
|
||||||
import ActionSection from '@/Components/ActionSection.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 DangerButton from '@/packages/ui/src/Buttons/DangerButton.vue';
|
||||||
import DialogModal from '@/packages/ui/src/DialogModal.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 SecondaryButton from '@/packages/ui/src/Buttons/SecondaryButton.vue';
|
||||||
import TextInput from '@/packages/ui/src/Input/TextInput.vue';
|
|
||||||
import { useOrganizationStore } from '@/utils/useOrganization';
|
import { useOrganizationStore } from '@/utils/useOrganization';
|
||||||
|
|
||||||
const props = defineProps<{
|
const props = defineProps<{
|
||||||
team: { id: string };
|
team: { id: string };
|
||||||
|
confirmsWithPassword: boolean;
|
||||||
}>();
|
}>();
|
||||||
|
|
||||||
const confirmingTeamDeletion = ref(false);
|
const confirmingTeamDeletion = ref(false);
|
||||||
const passwordInput = ref<HTMLInputElement | null>(null);
|
const confirmationInput = ref<InstanceType<typeof IdentityConfirmationInput> | null>(null);
|
||||||
const password = ref('');
|
const password = ref('');
|
||||||
const passwordError = ref('');
|
const passwordError = ref('');
|
||||||
const processing = ref(false);
|
const processing = ref(false);
|
||||||
@@ -22,11 +22,11 @@ const organizationStore = useOrganizationStore();
|
|||||||
|
|
||||||
const confirmTeamDeletion = () => {
|
const confirmTeamDeletion = () => {
|
||||||
confirmingTeamDeletion.value = true;
|
confirmingTeamDeletion.value = true;
|
||||||
setTimeout(() => passwordInput.value?.focus(), 250);
|
setTimeout(() => confirmationInput.value?.focus(), 250);
|
||||||
};
|
};
|
||||||
|
|
||||||
const deleteTeam = async () => {
|
const deleteTeam = async () => {
|
||||||
if (processing.value) return;
|
if (processing.value || !props.confirmsWithPassword) return;
|
||||||
processing.value = true;
|
processing.value = true;
|
||||||
passwordError.value = '';
|
passwordError.value = '';
|
||||||
try {
|
try {
|
||||||
@@ -44,7 +44,7 @@ const deleteTeam = async () => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
processing.value = false;
|
processing.value = false;
|
||||||
passwordInput.value?.focus();
|
confirmationInput.value?.focus();
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -78,21 +78,18 @@ const closeModal = () => {
|
|||||||
|
|
||||||
<template #content>
|
<template #content>
|
||||||
Are you sure you want to delete this organization? Once a organization is
|
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
|
deleted, all of its resources and data will be permanently deleted.
|
||||||
your password to confirm you would like to permanently delete this organization.
|
<template v-if="confirmsWithPassword">
|
||||||
|
Please enter your password to confirm you would like to permanently delete
|
||||||
|
this organization.
|
||||||
|
</template>
|
||||||
|
|
||||||
<Field class="mt-4">
|
<IdentityConfirmationInput
|
||||||
<TextInput
|
ref="confirmationInput"
|
||||||
ref="passwordInput"
|
v-model:password="password"
|
||||||
v-model="password"
|
:confirms-with-password="confirmsWithPassword"
|
||||||
type="password"
|
:error="passwordError"
|
||||||
class="block w-3/4"
|
@submit="deleteTeam" />
|
||||||
placeholder="Password"
|
|
||||||
autocomplete="current-password"
|
|
||||||
@keyup.enter="deleteTeam" />
|
|
||||||
|
|
||||||
<FieldError v-if="passwordError">{{ passwordError }}</FieldError>
|
|
||||||
</Field>
|
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<template #footer>
|
<template #footer>
|
||||||
@@ -100,8 +97,8 @@ const closeModal = () => {
|
|||||||
|
|
||||||
<DangerButton
|
<DangerButton
|
||||||
class="ms-3"
|
class="ms-3"
|
||||||
:class="{ 'opacity-25': processing }"
|
:class="{ 'opacity-25': processing || !confirmsWithPassword }"
|
||||||
:disabled="processing"
|
:disabled="processing || !confirmsWithPassword"
|
||||||
@click="deleteTeam">
|
@click="deleteTeam">
|
||||||
Delete Organization
|
Delete Organization
|
||||||
</DangerButton>
|
</DangerButton>
|
||||||
|
|||||||
@@ -11,15 +11,19 @@ import OrganizationTimeEntrySettings from '@/Pages/Teams/Partials/OrganizationTi
|
|||||||
import OrganizationTrial from '@/Pages/Teams/Partials/OrganizationTrial.vue';
|
import OrganizationTrial from '@/Pages/Teams/Partials/OrganizationTrial.vue';
|
||||||
import { isBillingActivated, isInTrial } from '@/utils/billing';
|
import { isBillingActivated, isInTrial } from '@/utils/billing';
|
||||||
import { canManageBilling } from '@/utils/permissions';
|
import { canManageBilling } from '@/utils/permissions';
|
||||||
import { onMounted, ref } from 'vue';
|
import { computed, onMounted, ref } from 'vue';
|
||||||
import { useOrganizationStore } from '@/utils/useOrganization';
|
import { useOrganizationStore } from '@/utils/useOrganization';
|
||||||
import { storeToRefs } from 'pinia';
|
import { storeToRefs } from 'pinia';
|
||||||
|
import { useUserQuery } from '@/utils/useUserQuery';
|
||||||
|
|
||||||
defineProps<{
|
defineProps<{
|
||||||
team: Organization;
|
team: Organization;
|
||||||
permissions: Permissions;
|
permissions: Permissions;
|
||||||
}>();
|
}>();
|
||||||
|
|
||||||
|
const { user } = useUserQuery();
|
||||||
|
const confirmsWithPassword = computed(() => user.value?.confirms_with_password ?? false);
|
||||||
|
|
||||||
const loading = ref(true);
|
const loading = ref(true);
|
||||||
const orgStore = useOrganizationStore();
|
const orgStore = useOrganizationStore();
|
||||||
const { organization } = storeToRefs(orgStore);
|
const { organization } = storeToRefs(orgStore);
|
||||||
@@ -62,7 +66,10 @@ onMounted(async () => {
|
|||||||
|
|
||||||
<template v-if="permissions.canDeleteTeam">
|
<template v-if="permissions.canDeleteTeam">
|
||||||
<SectionBorder />
|
<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>
|
||||||
</template>
|
</template>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -10,35 +10,73 @@ import { QueryClient, VueQueryPlugin } from '@tanstack/vue-query';
|
|||||||
import { type DefineComponent } from 'vue';
|
import { type DefineComponent } from 'vue';
|
||||||
import { setupPrefetching } from '@/utils/prefetch';
|
import { setupPrefetching } from '@/utils/prefetch';
|
||||||
|
|
||||||
|
interface ExtensionManifest {
|
||||||
|
name?: string;
|
||||||
|
alias?: string;
|
||||||
|
}
|
||||||
|
|
||||||
const appName = import.meta.env.VITE_APP_NAME || 'Laravel';
|
const appName = import.meta.env.VITE_APP_NAME || 'Laravel';
|
||||||
const pinia = createPinia();
|
const pinia = createPinia();
|
||||||
const queryClient = new QueryClient();
|
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({
|
createInertiaApp({
|
||||||
title: (title) => `${title} - ${appName}`,
|
title: (title) => `${title} - ${appName}`,
|
||||||
resolve: (name) => {
|
resolve: (name) => {
|
||||||
if (name.includes('Invoicing::')) {
|
// "Module::Page" (both halves present) resolves to that extension's page
|
||||||
const [module, page] = name.split('::');
|
// directory; everything else is a host page under resources/js/Pages.
|
||||||
|
const [module, ...pageSegments] = name.split('::');
|
||||||
|
const page = pageSegments.join('::');
|
||||||
|
|
||||||
const pagePath = module
|
if (module && page) {
|
||||||
? `../../extensions/${module}/resources/js/Pages/${page}.vue`
|
const extensionDirectory = resolveExtensionDirectory(module);
|
||||||
: `./Pages/${page}.vue`;
|
const pagePath = `../../extensions/${extensionDirectory}/resources/js/Pages/${page}.vue`;
|
||||||
|
|
||||||
// BillingPortal is a Vue 2 Component and therefore should not be imported
|
return resolvePageComponent(pagePath, extensionPages);
|
||||||
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(
|
||||||
|
`./Pages/${name}.vue`,
|
||||||
|
import.meta.glob<DefineComponent>('./Pages/**/*.vue')
|
||||||
|
);
|
||||||
},
|
},
|
||||||
setup({ el, App, props, plugin }) {
|
setup({ el, App, props, plugin }) {
|
||||||
const app = createApp({ render: () => h(App, props) });
|
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
|
const ClientUpdateRequest = z
|
||||||
.object({ name: z.string().min(1).max(255), is_archived: z.boolean().optional() })
|
.object({ name: z.string().min(1).max(255), is_archived: z.boolean().optional() })
|
||||||
.passthrough();
|
.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 ImportRequest = z.object({ type: z.string(), data: z.string() }).passthrough();
|
||||||
const InvitationResource = z
|
const InvitationResource = z
|
||||||
.object({ id: z.string(), email: z.string(), role: z.string() })
|
.object({ id: z.string(), email: z.string(), role: z.string() })
|
||||||
@@ -800,6 +804,8 @@ const UserResource = z
|
|||||||
timezone: z.string(),
|
timezone: z.string(),
|
||||||
week_start: Weekday,
|
week_start: Weekday,
|
||||||
send_time_entry_still_running_email: z.boolean(),
|
send_time_entry_still_running_email: z.boolean(),
|
||||||
|
confirms_with_password: z.boolean(),
|
||||||
|
can_change_email: z.boolean(),
|
||||||
})
|
})
|
||||||
.passthrough();
|
.passthrough();
|
||||||
const UserUpdateRequest = z
|
const UserUpdateRequest = z
|
||||||
|
|||||||
@@ -6,7 +6,9 @@ namespace Tests\Feature;
|
|||||||
|
|
||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
use App\Providers\RouteServiceProvider;
|
use App\Providers\RouteServiceProvider;
|
||||||
|
use App\Service\AuthenticationContract;
|
||||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||||
|
use Mockery\MockInterface;
|
||||||
use Tests\TestCase;
|
use Tests\TestCase;
|
||||||
|
|
||||||
class AuthenticationTest extends TestCase
|
class AuthenticationTest extends TestCase
|
||||||
@@ -44,4 +46,67 @@ class AuthenticationTest extends TestCase
|
|||||||
|
|
||||||
$this->assertGuest();
|
$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;
|
namespace Tests\Feature;
|
||||||
|
|
||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
|
use App\Service\AuthenticationContract;
|
||||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||||
use Illuminate\Support\Facades\Hash;
|
use Illuminate\Support\Facades\Hash;
|
||||||
|
use Mockery\MockInterface;
|
||||||
use Tests\TestCase;
|
use Tests\TestCase;
|
||||||
|
|
||||||
class PasswordConfirmationTest extends TestCase
|
class PasswordConfirmationTest extends TestCase
|
||||||
@@ -83,4 +85,37 @@ class PasswordConfirmationTest extends TestCase
|
|||||||
$response->assertSessionHasErrors();
|
$response->assertSessionHasErrors();
|
||||||
$this->assertFalse($this->app['session']->has('auth.password_confirmed_at'));
|
$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;
|
namespace Tests\Feature;
|
||||||
|
|
||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
|
use App\Service\AuthenticationContract;
|
||||||
use Illuminate\Auth\Notifications\ResetPassword;
|
use Illuminate\Auth\Notifications\ResetPassword;
|
||||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||||
use Illuminate\Support\Facades\Hash;
|
use Illuminate\Support\Facades\Hash;
|
||||||
use Illuminate\Support\Facades\Notification;
|
use Illuminate\Support\Facades\Notification;
|
||||||
use Laravel\Fortify\Features;
|
use Laravel\Fortify\Features;
|
||||||
|
use Mockery\MockInterface;
|
||||||
use Tests\TestCase;
|
use Tests\TestCase;
|
||||||
|
|
||||||
class PasswordResetTest extends TestCase
|
class PasswordResetTest extends TestCase
|
||||||
@@ -152,4 +154,36 @@ class PasswordResetTest extends TestCase
|
|||||||
$response->assertSessionHasErrors('email');
|
$response->assertSessionHasErrors('email');
|
||||||
Notification::assertNothingSent();
|
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;
|
namespace Tests\Feature;
|
||||||
|
|
||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
|
use App\Service\AuthenticationContract;
|
||||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||||
use Illuminate\Support\Facades\Hash;
|
use Illuminate\Support\Facades\Hash;
|
||||||
|
use Mockery\MockInterface;
|
||||||
use Tests\TestCase;
|
use Tests\TestCase;
|
||||||
|
|
||||||
class UpdatePasswordTest extends TestCase
|
class UpdatePasswordTest extends TestCase
|
||||||
@@ -55,4 +57,41 @@ class UpdatePasswordTest extends TestCase
|
|||||||
|
|
||||||
$this->assertTrue(Hash::check('password', $user->fresh()->password));
|
$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;
|
namespace Tests;
|
||||||
|
|
||||||
|
use App\Service\AuthenticationContract;
|
||||||
use App\Service\BillableRateService;
|
use App\Service\BillableRateService;
|
||||||
use App\Service\BillingContract;
|
use App\Service\BillingContract;
|
||||||
use App\Service\PermissionStore;
|
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));
|
// $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
|
protected function mockPrivateStorage(): void
|
||||||
{
|
{
|
||||||
Storage::fake(config('filesystems.private'));
|
Storage::fake(config('filesystems.private'));
|
||||||
|
|||||||
@@ -649,4 +649,24 @@ class OrganizationEndpointTest extends ApiEndpointTestAbstract
|
|||||||
$response->assertOk();
|
$response->assertOk();
|
||||||
$response->assertJsonPath('data.can_use_billable_rates', false);
|
$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\Member;
|
||||||
use App\Models\Organization;
|
use App\Models\Organization;
|
||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
|
use App\Service\AuthenticationContract;
|
||||||
use Illuminate\Support\Facades\Mail;
|
use Illuminate\Support\Facades\Mail;
|
||||||
use Illuminate\Support\Facades\Storage;
|
use Illuminate\Support\Facades\Storage;
|
||||||
use Laravel\Passport\Passport;
|
use Laravel\Passport\Passport;
|
||||||
@@ -46,10 +47,42 @@ class UserEndpointTest extends ApiEndpointTestAbstract
|
|||||||
'timezone' => $data->user->timezone,
|
'timezone' => $data->user->timezone,
|
||||||
'week_start' => $data->user->week_start->value,
|
'week_start' => $data->user->week_start->value,
|
||||||
'send_time_entry_still_running_email' => true,
|
'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
|
public function test_update_current_organization_fails_when_not_authenticated(): void
|
||||||
{
|
{
|
||||||
// Arrange
|
// Arrange
|
||||||
@@ -245,6 +278,52 @@ class UserEndpointTest extends ApiEndpointTestAbstract
|
|||||||
Mail::assertNothingSent();
|
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
|
public function test_update_fails_if_email_is_already_used_by_another_user(): void
|
||||||
{
|
{
|
||||||
// Arrange
|
// 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
|
public function test_resend_email_verification_fails_if_given_id_is_not_the_authenticated_user(): void
|
||||||
{
|
{
|
||||||
// Arrange
|
// Arrange
|
||||||
@@ -789,4 +888,20 @@ class UserEndpointTest extends ApiEndpointTestAbstract
|
|||||||
$response->assertNoContent();
|
$response->assertNoContent();
|
||||||
$this->assertDatabaseMissing(User::class, ['id' => $data->user->getKey()]);
|
$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\Http\Controllers\Web\OtherBrowserSessionsController;
|
||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
|
use App\Service\AuthenticationContract;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
use Illuminate\Support\Facades\Hash;
|
use Illuminate\Support\Facades\Hash;
|
||||||
|
use Mockery\MockInterface;
|
||||||
use PHPUnit\Framework\Attributes\CoversClass;
|
use PHPUnit\Framework\Attributes\CoversClass;
|
||||||
|
|
||||||
#[CoversClass(OtherBrowserSessionsController::class)]
|
#[CoversClass(OtherBrowserSessionsController::class)]
|
||||||
@@ -100,4 +102,65 @@ class OtherBrowserSessionsEndpointTest extends EndpointTestAbstract
|
|||||||
$this->assertDatabaseMissing('sessions', ['id' => 'other-session-of-current-user']);
|
$this->assertDatabaseMissing('sessions', ['id' => 'other-session-of-current-user']);
|
||||||
$this->assertDatabaseHas('sessions', ['id' => 'session-of-another-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\Http\Controllers\Web\UserController;
|
||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
|
use App\Service\AuthenticationContract;
|
||||||
use Illuminate\Support\Carbon;
|
use Illuminate\Support\Carbon;
|
||||||
use Illuminate\Support\Facades\URL;
|
use Illuminate\Support\Facades\URL;
|
||||||
use PHPUnit\Framework\Attributes\CoversClass;
|
use PHPUnit\Framework\Attributes\CoversClass;
|
||||||
@@ -46,6 +47,37 @@ class UserEndpointTest extends EndpointTestAbstract
|
|||||||
$this->assertTrue(now()->equalTo($user->email_verified_at));
|
$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
|
public function test_pending_email_verification_is_rejected_for_another_authenticated_user(): void
|
||||||
{
|
{
|
||||||
// Arrange
|
// 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\Enums\Role;
|
||||||
use App\Events\BeforeOrganizationDeletion;
|
use App\Events\BeforeOrganizationDeletion;
|
||||||
|
use App\Events\BeforeUserDeletion;
|
||||||
use App\Exceptions\Api\CanNotDeleteUserWhoIsOwnerOfOrganizationWithMultipleMembers;
|
use App\Exceptions\Api\CanNotDeleteUserWhoIsOwnerOfOrganizationWithMultipleMembers;
|
||||||
use App\Models\Audit;
|
use App\Models\Audit;
|
||||||
use App\Models\Client;
|
use App\Models\Client;
|
||||||
@@ -43,6 +44,7 @@ class DeletionServiceTest extends TestCaseWithDatabase
|
|||||||
parent::setUp();
|
parent::setUp();
|
||||||
Event::fake([
|
Event::fake([
|
||||||
BeforeOrganizationDeletion::class,
|
BeforeOrganizationDeletion::class,
|
||||||
|
BeforeUserDeletion::class,
|
||||||
]);
|
]);
|
||||||
$this->deletionService = app(DeletionService::class);
|
$this->deletionService = app(DeletionService::class);
|
||||||
}
|
}
|
||||||
@@ -255,6 +257,7 @@ class DeletionServiceTest extends TestCaseWithDatabase
|
|||||||
// Assert
|
// Assert
|
||||||
$this->assertTrue(true);
|
$this->assertTrue(true);
|
||||||
}
|
}
|
||||||
|
Event::assertNotDispatched(BeforeUserDeletion::class);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function test_delete_user_rolls_back_on_error_if_transaction_is_active(): void
|
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);
|
$this->deletionService->deleteUser($user);
|
||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
|
Event::assertDispatched(fn (BeforeUserDeletion $event): bool => $event->user->is($user), 1);
|
||||||
$this->assertDatabaseMissing(User::class, [
|
$this->assertDatabaseMissing(User::class, [
|
||||||
'id' => $user->getKey(),
|
'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\Enums\Weekday;
|
||||||
use App\Models\Member;
|
use App\Models\Member;
|
||||||
use App\Models\Organization;
|
use App\Models\Organization;
|
||||||
|
use App\Models\OrganizationInvitation;
|
||||||
use App\Models\Project;
|
use App\Models\Project;
|
||||||
use App\Models\ProjectMember;
|
use App\Models\ProjectMember;
|
||||||
use App\Models\TimeEntry;
|
use App\Models\TimeEntry;
|
||||||
@@ -16,6 +17,7 @@ use App\Service\UserService;
|
|||||||
use Illuminate\Auth\Events\Verified;
|
use Illuminate\Auth\Events\Verified;
|
||||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||||
use Illuminate\Support\Facades\Event;
|
use Illuminate\Support\Facades\Event;
|
||||||
|
use Illuminate\Support\Facades\Hash;
|
||||||
use PHPUnit\Framework\Attributes\CoversClass;
|
use PHPUnit\Framework\Attributes\CoversClass;
|
||||||
use Tests\TestCase;
|
use Tests\TestCase;
|
||||||
|
|
||||||
@@ -165,4 +167,139 @@ class UserServiceTest extends TestCase
|
|||||||
$this->assertSame(Role::Owner->value, $newMember->role);
|
$this->assertSame(Role::Owner->value, $newMember->role);
|
||||||
$this->assertSame($newOrganization->getKey(), $user->currentOrganization->getKey());
|
$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/**/*.ts",
|
||||||
"extensions/Invoicing/resources/js/**/*.d.ts",
|
"extensions/Invoicing/resources/js/**/*.d.ts",
|
||||||
"extensions/Invoicing/resources/js/**/*.vue",
|
"extensions/Invoicing/resources/js/**/*.vue",
|
||||||
|
"extensions/SSO/resources/js/**/*.ts",
|
||||||
|
"extensions/SSO/resources/js/**/*.vue",
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user