Add admin user creation flow #76

Merged
Twyco merged 3 commits from koda/137-user-create-force-password-change into main 2026-05-22 23:04:06 +00:00
20 changed files with 701 additions and 10 deletions
@@ -4,6 +4,7 @@ namespace App\Http\Controllers\Admin;
use App\Actions\Permissions\PermissionService;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\StoreManagedUserRequest;
use App\Http\Requests\Admin\SyncUserGlobalPermissionsRequest;
use App\Http\Resources\PermissionOptionResource;
use App\Http\Resources\UserResource;
@@ -35,6 +36,26 @@ class UserManagementController extends Controller
]);
}
public function create(): Response
{
return Inertia::render('admin/users/Create');
}
public function store(StoreManagedUserRequest $request): RedirectResponse
{
$validated = $request->validated();
User::query()->create([
'name' => Arr::get($validated, 'name'),
'email' => Arr::get($validated, 'email'),
'password' => Arr::get($validated, 'password'),
'must_change_password_on_next_login' => (bool) Arr::get($validated, 'must_change_password_on_next_login', true),
]);
return to_route('admin.users.index')
->with('status', 'User was created.');
}
public function update(SyncUserGlobalPermissionsRequest $request, User $user): RedirectResponse
{
$validated = $request->validated();
@@ -6,6 +6,7 @@ use App\Http\Controllers\Controller;
use App\Http\Requests\Settings\PasswordUpdateRequest;
use App\Http\Requests\Settings\TwoFactorAuthenticationRequest;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Controllers\HasMiddleware;
use Illuminate\Routing\Controllers\Middleware;
use Inertia\Inertia;
@@ -28,11 +29,18 @@ class SecurityController extends Controller implements HasMiddleware
/**
* Show the user's security settings page.
*/
public function edit(TwoFactorAuthenticationRequest $request): Response
public function edit(TwoFactorAuthenticationRequest $request): Response|RedirectResponse
{
$user = $request->user();
if ($user->must_change_password_on_next_login) {
return to_route('password.force-change.edit');
}
$props = [
'canManageTwoFactor' => Features::canManageTwoFactorAuthentication(),
'mustChangePassword' => (bool) $user->must_change_password_on_next_login,
'status' => session('status'),
];
if (Features::canManageTwoFactorAuthentication()) {
@@ -45,17 +53,37 @@ class SecurityController extends Controller implements HasMiddleware
return Inertia::render('settings/Security', $props);
}
/**
* Show the dedicated forced password change page.
*/
public function editForcedPassword(Request $request): Response|RedirectResponse
{
if (! $request->user()->must_change_password_on_next_login) {
return to_route('dashboard');
}
return Inertia::render('auth/ForcePasswordChange', [
'status' => session('status'),
]);
}
/**
* Update the user's password.
*/
public function update(PasswordUpdateRequest $request): RedirectResponse
{
$user = $request->user();
$mustChangePassword = (bool) $user->must_change_password_on_next_login;
$user->update([
'must_change_password_on_next_login' => false,
'password' => $request->password,
]);
if ($mustChangePassword) {
return redirect()->intended(route('dashboard'));
}
return back();
}
}
@@ -0,0 +1,43 @@
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class RequirePasswordChange
{
/**
* Handle an incoming request.
*
* @param Closure(Request): Response $next
*/
public function handle(Request $request, Closure $next): Response
{
$user = $request->user();
if ($user === null || ! $user->must_change_password_on_next_login) {
return $next($request);
}
if ($request->routeIs([
'logout',
'password.confirm',
'password.confirm.*',
'password.force-change.edit',
'security.edit',
'user-password.update',
])) {
return $next($request);
}
if ($request->isMethod('get') && ! $request->expectsJson()) {
$request->session()->put('url.intended', $request->fullUrl());
}
return redirect()
->route('password.force-change.edit')
->with('status', 'You must change your password before continuing.');
}
}
@@ -0,0 +1,36 @@
<?php
namespace App\Http\Requests\Admin;
use App\Concerns\PasswordValidationRules;
use App\Concerns\ProfileValidationRules;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Foundation\Http\FormRequest;
class StoreManagedUserRequest extends FormRequest
{
use PasswordValidationRules;
use ProfileValidationRules;
/**
* Determine if the user is authorized to make this request.
*/
public function authorize(): bool
{
return $this->user()?->can('access-admin') ?? false;
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
return [
...$this->profileRules(),
'must_change_password_on_next_login' => ['required', 'boolean'],
'password' => $this->passwordRules(),
];
}
}
@@ -19,7 +19,19 @@ class PasswordUpdateRequest extends FormRequest
{
return [
'current_password' => $this->currentPasswordRules(),
'password' => $this->passwordRules(),
'password' => [...$this->passwordRules(), 'different:current_password'],
];
}
/**
* Get the custom validation messages for the request.
*
* @return array<string, string>
*/
public function messages(): array
{
return [
'password.different' => 'The new password must be different from your current password.',
];
}
}
+1
View File
@@ -19,6 +19,7 @@ class UserResource extends JsonResource
'name' => $this->name,
'email' => $this->email,
'email_verified_at' => $this->email_verified_at?->toISOString(),
'must_change_password_on_next_login' => (bool) $this->must_change_password_on_next_login,
'created_at' => $this->created_at?->toISOString(),
'updated_at' => $this->updated_at?->toISOString(),
];
+2 -1
View File
@@ -17,7 +17,7 @@ use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Fortify\TwoFactorAuthenticatable;
#[Fillable(['name', 'email', 'password'])]
#[Fillable(['name', 'email', 'password', 'must_change_password_on_next_login'])]
#[Hidden(['password', 'two_factor_secret', 'two_factor_recovery_codes', 'remember_token'])]
class User extends Authenticatable
{
@@ -40,6 +40,7 @@ class User extends Authenticatable
{
return [
'email_verified_at' => 'datetime',
'must_change_password_on_next_login' => 'bool',
'password' => 'hashed',
'two_factor_confirmed_at' => 'datetime',
];
+2
View File
@@ -3,6 +3,7 @@
use App\Http\Middleware\AuthenticateApiApplicationKey;
use App\Http\Middleware\HandleAppearance;
use App\Http\Middleware\HandleInertiaRequests;
use App\Http\Middleware\RequirePasswordChange;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
@@ -21,6 +22,7 @@ return Application::configure(basePath: dirname(__DIR__))
$middleware->web(append: [
HandleAppearance::class,
HandleInertiaRequests::class,
RequirePasswordChange::class,
AddLinkHeadersForPreloadedAssets::class,
]);
+1
View File
@@ -29,6 +29,7 @@ class UserFactory extends Factory
'name' => fake()->name(),
'email' => fake()->unique()->safeEmail(),
'email_verified_at' => now(),
'must_change_password_on_next_login' => false,
'password' => static::$password ??= Hash::make('password'),
'remember_token' => Str::random(10),
'two_factor_secret' => null,
@@ -0,0 +1,30 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::table('users', function (Blueprint $table): void {
$table->boolean('must_change_password_on_next_login')
->default(false)
->after('password');
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('users', function (Blueprint $table): void {
$table->dropColumn('must_change_password_on_next_login');
});
}
};
+155
View File
@@ -0,0 +1,155 @@
<script setup lang="ts">
import { Form, Head, Link } from '@inertiajs/vue3';
import UserManagementController from '@/actions/App/Http/Controllers/Admin/UserManagementController';
import Heading from '@/components/Heading.vue';
import InputError from '@/components/InputError.vue';
import PasswordInput from '@/components/PasswordInput.vue';
import { Button } from '@/components/ui/button';
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import AppLayout from '@/layouts/AppLayout.vue';
import { create, index } from '@/routes/admin/users';
import type { BreadcrumbItem } from '@/types';
const breadcrumbs: BreadcrumbItem[] = [
{
title: 'User management',
href: index(),
},
{
title: 'Create user',
href: create(),
},
];
</script>
<template>
<AppLayout :breadcrumbs="breadcrumbs">
<Head title="Create user" />
<div class="mx-auto flex w-full max-w-3xl flex-1 flex-col gap-6 p-4">
<Heading
title="Create user"
description="Create a user account and optionally force a password change on the next login."
/>
<Card>
<CardHeader>
<CardTitle>User details</CardTitle>
<CardDescription>
Set an initial password that the user can replace after
their first sign-in.
</CardDescription>
</CardHeader>
<CardContent>
<Form
v-bind="UserManagementController.store.form()"
:transform="(data) => ({
...data,
must_change_password_on_next_login:
data.must_change_password_on_next_login === true ||
data.must_change_password_on_next_login === 'on',
})"
class="space-y-6"
v-slot="{ errors, processing }"
>
<div class="grid gap-2">
<Label for="name">Name</Label>
<Input
id="name"
name="name"
required
autofocus
autocomplete="name"
placeholder="Jane Admin"
/>
<InputError :message="errors.name" />
</div>
<div class="grid gap-2">
<Label for="email">Email</Label>
<Input
id="email"
name="email"
type="email"
required
autocomplete="email"
placeholder="jane@example.com"
/>
<InputError :message="errors.email" />
</div>
<div class="grid gap-2">
<Label for="password">Password</Label>
<PasswordInput
id="password"
name="password"
required
autocomplete="new-password"
placeholder="Temporary password"
/>
<InputError :message="errors.password" />
</div>
<div class="grid gap-2">
<Label for="password_confirmation"
>Confirm password</Label
>
<PasswordInput
id="password_confirmation"
name="password_confirmation"
required
autocomplete="new-password"
placeholder="Confirm password"
/>
</div>
<div class="grid gap-2">
<Label
for="must_change_password_on_next_login"
class="flex items-start gap-3 rounded-lg border px-4 py-3"
>
<input
id="must_change_password_on_next_login"
name="must_change_password_on_next_login"
type="checkbox"
checked
class="border-input text-primary focus:ring-ring mt-0.5 size-4 rounded"
/>
<span class="space-y-1">
<span class="block font-medium">
Must change password on next login
</span>
<span class="text-muted-foreground block text-sm">
Redirect the user to the security settings page until they save a new password.
</span>
</span>
</Label>
<InputError
:message="errors.must_change_password_on_next_login"
/>
</div>
<div class="flex items-center gap-3">
<Button type="submit" :disabled="processing">
Create user
</Button>
<Button as-child variant="outline">
<Link :href="index()">Cancel</Link>
</Button>
</div>
</Form>
</CardContent>
</Card>
</div>
</AppLayout>
</template>
+24 -7
View File
@@ -1,6 +1,6 @@
<script setup lang="ts">
import { Form, Head } from '@inertiajs/vue3';
import { FolderPlus, Shield, Users } from 'lucide-vue-next';
import { Form, Head, Link } from '@inertiajs/vue3';
import { FolderPlus, KeyRound, Shield, UserPlus, Users } from 'lucide-vue-next';
import UserManagementController from '@/actions/App/Http/Controllers/Admin/UserManagementController';
import Heading from '@/components/Heading.vue';
import { Badge } from '@/components/ui/badge';
@@ -13,7 +13,7 @@ import {
CardTitle,
} from '@/components/ui/card';
import AppLayout from '@/layouts/AppLayout.vue';
import { index as adminUsers } from '@/routes/admin/users';
import { create as createAdminUser, index as adminUsers } from '@/routes/admin/users';
import type { AdminUsersPageProps, BreadcrumbItem } from '@/types';
const props = defineProps<AdminUsersPageProps>();
@@ -40,10 +40,19 @@ const hasPermission = (actorId: number, permission: string) =>
description="Assign the global permissions that unlock platform-wide administration and project creation."
/>
<Badge variant="outline" class="gap-1.5 px-3 py-1">
<Users class="size-3.5" />
Admin-only area
</Badge>
<div class="flex items-center gap-3">
<Button as-child>
<Link :href="createAdminUser()">
<UserPlus class="size-4" />
User create
</Link>
</Button>
<Badge variant="outline" class="gap-1.5 px-3 py-1">
<Users class="size-3.5" />
Admin-only area
</Badge>
</div>
</div>
<div
@@ -108,6 +117,14 @@ const hasPermission = (actorId: number, permission: string) =>
</td>
<td class="px-4 py-4">
<div class="flex flex-wrap gap-2">
<Badge
v-if="user.must_change_password_on_next_login"
variant="outline"
class="gap-1.5"
>
<KeyRound class="size-3.5" />
Must change password
</Badge>
<Badge
v-if="
hasPermission(
@@ -0,0 +1,115 @@
<script setup lang="ts">
import { Form, Head, Link } from '@inertiajs/vue3';
import { LogOut } from 'lucide-vue-next';
import SecurityController from '@/actions/App/Http/Controllers/Settings/SecurityController';
import InputError from '@/components/InputError.vue';
import PasswordInput from '@/components/PasswordInput.vue';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { Spinner } from '@/components/ui/spinner';
import AuthLayout from '@/layouts/AuthLayout.vue';
import { logout } from '@/routes';
withDefaults(
defineProps<{
status?: string | null;
}>(),
{
status: null,
},
);
</script>
<template>
<AuthLayout
title="Change your password"
description="You must update your password before you can continue using the application."
>
<Head title="Change your password" />
<div class="mb-6 flex justify-end">
<Button as-child variant="ghost" size="sm">
<Link :href="logout()" as="button">
<LogOut class="size-4" />
Log out
</Link>
</Button>
</div>
<div
v-if="status"
class="mb-6 rounded-xl border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-900"
>
{{ status }}
</div>
<Form
v-bind="SecurityController.update.form()"
reset-on-success
:reset-on-error="[
'password',
'password_confirmation',
'current_password',
]"
v-slot="{ errors, processing }"
>
<div class="space-y-6">
<div class="grid gap-2">
<Label htmlFor="current_password">Current password</Label>
<PasswordInput
id="current_password"
name="current_password"
class="mt-1 block w-full"
required
autocomplete="current-password"
autofocus
placeholder="Current password"
/>
<InputError :message="errors.current_password" />
</div>
<div class="grid gap-2">
<Label htmlFor="password">New password</Label>
<PasswordInput
id="password"
name="password"
class="mt-1 block w-full"
required
autocomplete="new-password"
placeholder="New password"
/>
<InputError :message="errors.password" />
</div>
<div class="grid gap-2">
<Label htmlFor="password_confirmation">
Confirm new password
</Label>
<PasswordInput
id="password_confirmation"
name="password_confirmation"
class="mt-1 block w-full"
required
autocomplete="new-password"
placeholder="Confirm new password"
/>
<InputError :message="errors.password_confirmation" />
</div>
<div class="flex items-center">
<Button
class="w-full"
:disabled="processing"
data-test="force-password-change-button"
>
<Spinner v-if="processing" />
Save new password
</Button>
</div>
</div>
</Form>
</AuthLayout>
</template>
+15
View File
@@ -19,13 +19,17 @@ import type { BreadcrumbItem } from '@/types';
type Props = {
canManageTwoFactor?: boolean;
mustChangePassword?: boolean;
requiresConfirmation?: boolean;
status?: string | null;
twoFactorEnabled?: boolean;
};
withDefaults(defineProps<Props>(), {
canManageTwoFactor: false,
mustChangePassword: false,
requiresConfirmation: false,
status: null,
twoFactorEnabled: false,
});
@@ -49,6 +53,17 @@ onUnmounted(() => clearTwoFactorAuthData());
<h1 class="sr-only">Security settings</h1>
<SettingsLayout>
<div
v-if="mustChangePassword || status"
class="rounded-xl border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-900 dark:border-amber-900/70 dark:bg-amber-950/40 dark:text-amber-100"
>
{{
mustChangePassword
? 'You must change your password before continuing anywhere else in the app.'
: status
}}
</div>
<div class="space-y-6">
<Heading
variant="small"
+1
View File
@@ -4,6 +4,7 @@ export type UserModel = {
email: string;
avatar?: string;
email_verified_at: string | null;
must_change_password_on_next_login: boolean;
created_at: string;
updated_at: string;
};
+2
View File
@@ -12,6 +12,8 @@ Route::middleware('can:access-admin')
->controller(UserManagementController::class)
->group(function (): void {
Route::get('/', 'index')->name('index');
Route::get('create', 'create')->name('create');
Route::post('/', 'store')->name('store');
Route::patch('{user}/permissions', 'update')->name('update');
});
});
+7
View File
@@ -19,6 +19,13 @@ Route::middleware('auth')
});
});
Route::middleware(['auth', 'verified'])
->controller(SecurityController::class)
->group(function (): void {
Route::get('user/force-password-change', 'editForcedPassword')
->name('password.force-change.edit');
});
Route::middleware(['auth', 'verified'])
->prefix('settings')
->group(function (): void {
@@ -46,6 +46,46 @@ class UserManagementControllerTest extends TestCase
->assertForbidden();
}
/**
* Ensure admins can view the create user page.
*/
public function test_admin_can_view_the_create_user_page(): void
{
$admin = User::factory()->admin()->create();
$this->actingAs($admin)
->get(route('admin.users.create'))
->assertOk()
->assertInertia(fn (Assert $page) => $page
->component('admin/users/Create'),
);
}
/**
* Ensure admins can create managed users.
*/
public function test_admin_can_create_a_user_that_must_change_password_on_next_login(): void
{
$admin = User::factory()->admin()->create();
$this->actingAs($admin)
->post(route('admin.users.store'), [
'name' => 'New Member',
'email' => 'new-member@example.com',
'password' => 'temporary-password',
'password_confirmation' => 'temporary-password',
'must_change_password_on_next_login' => true,
])
->assertRedirect(route('admin.users.index'))
->assertSessionHas('status', 'User was created.');
$this->assertDatabaseHas('users', [
'name' => 'New Member',
'email' => 'new-member@example.com',
'must_change_password_on_next_login' => true,
]);
}
/**
* Ensure admins can update another user's global permissions.
*/
@@ -126,4 +166,26 @@ class UserManagementControllerTest extends TestCase
'scope_type' => null,
]);
}
/**
* Ensure non-admin users cannot create managed users.
*/
public function test_non_admin_cannot_create_a_user(): void
{
$member = User::factory()->create();
$this->actingAs($member)
->post(route('admin.users.store'), [
'name' => 'Blocked User',
'email' => 'blocked-user@example.com',
'password' => 'temporary-password',
'password_confirmation' => 'temporary-password',
'must_change_password_on_next_login' => true,
])
->assertForbidden();
$this->assertDatabaseMissing('users', [
'email' => 'blocked-user@example.com',
]);
}
}
+19
View File
@@ -5,6 +5,7 @@ namespace Tests\Feature\Auth;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\RateLimiter;
use Inertia\Testing\AssertableInertia as Assert;
use Laravel\Fortify\Features;
use Tests\TestCase;
@@ -32,6 +33,24 @@ class AuthenticationTest extends TestCase
$response->assertRedirect(route('dashboard', absolute: false));
}
public function test_users_who_must_change_their_password_are_redirected_to_the_dedicated_force_change_page_after_login()
{
$user = User::factory()->create([
'must_change_password_on_next_login' => true,
]);
$response = $this->followingRedirects()->post(route('login.store'), [
'email' => $user->email,
'password' => 'password',
]);
$this->assertAuthenticated();
$response->assertInertia(fn (Assert $page) => $page
->component('auth/ForcePasswordChange')
->where('status', 'You must change your password before continuing.'),
);
}
public function test_users_with_two_factor_enabled_are_redirected_to_two_factor_challenge()
{
$this->skipUnlessFortifyFeature(Features::twoFactorAuthentication());
+123
View File
@@ -89,6 +89,64 @@ class SecurityTest extends TestCase
);
}
public function test_users_who_must_change_their_password_are_redirected_to_security_when_visiting_other_pages()
{
$user = User::factory()->create([
'must_change_password_on_next_login' => true,
]);
$this->actingAs($user)
->get(route('dashboard'))
->assertRedirect(route('password.force-change.edit'));
}
public function test_users_who_must_change_their_password_can_view_the_dedicated_force_change_page()
{
$user = User::factory()->create([
'must_change_password_on_next_login' => true,
]);
$this->actingAs($user)
->get(route('password.force-change.edit'))
->assertOk()
->assertInertia(fn (Assert $page) => $page
->component('auth/ForcePasswordChange')
->where('status', null),
);
}
public function test_forced_password_change_page_exposes_a_logout_action()
{
$user = User::factory()->create([
'must_change_password_on_next_login' => true,
]);
$this->actingAs($user)
->get(route('password.force-change.edit'))
->assertInertia(fn (Assert $page) => $page
->component('auth/ForcePasswordChange'),
);
}
public function test_users_who_must_change_their_password_are_not_sent_to_the_normal_security_page()
{
$this->skipUnlessFortifyFeature(Features::twoFactorAuthentication());
Features::twoFactorAuthentication([
'confirm' => true,
'confirmPassword' => true,
]);
$user = User::factory()->create([
'must_change_password_on_next_login' => true,
]);
$this->actingAs($user)
->withSession(['auth.password_confirmed_at' => time()])
->get(route('security.edit'))
->assertRedirect(route('password.force-change.edit'));
}
public function test_password_can_be_updated()
{
$user = User::factory()->create();
@@ -109,6 +167,49 @@ class SecurityTest extends TestCase
$this->assertTrue(Hash::check('new-password', $user->refresh()->password));
}
public function test_password_update_clears_the_forced_password_change_flag()
{
$user = User::factory()->create([
'must_change_password_on_next_login' => true,
]);
$this
->actingAs($user)
->from(route('security.edit'))
->put(route('user-password.update'), [
'current_password' => 'password',
'password' => 'new-password',
'password_confirmation' => 'new-password',
])
->assertSessionHasNoErrors()
->assertRedirect(route('dashboard'));
$this->assertFalse((bool) $user->refresh()->must_change_password_on_next_login);
}
public function test_forced_password_change_returns_the_user_to_their_intended_page_after_updating()
{
$user = User::factory()->create([
'must_change_password_on_next_login' => true,
]);
$this->actingAs($user)
->get(route('dashboard'));
$this->actingAs($user)
->from(route('password.force-change.edit'))
->put(route('user-password.update'), [
'current_password' => 'password',
'password' => 'new-password',
'password_confirmation' => 'new-password',
])
->assertSessionHasNoErrors()
->assertRedirect(route('dashboard'));
$this->assertFalse((bool) $user->refresh()->must_change_password_on_next_login);
$this->assertTrue(Hash::check('new-password', $user->password));
}
public function test_correct_password_must_be_provided_to_update_password()
{
$user = User::factory()->create();
@@ -126,4 +227,26 @@ class SecurityTest extends TestCase
->assertSessionHasErrors('current_password')
->assertRedirect(route('security.edit'));
}
public function test_new_password_must_be_different_from_the_current_password()
{
$user = User::factory()->create();
$response = $this
->actingAs($user)
->from(route('security.edit'))
->put(route('user-password.update'), [
'current_password' => 'password',
'password' => 'password',
'password_confirmation' => 'password',
]);
$response
->assertSessionHasErrors([
'password' => 'The new password must be different from your current password.',
])
->assertRedirect(route('security.edit'));
$this->assertTrue(Hash::check('password', $user->fresh()->password));
}
}