Add admin-managed user creation
This commit is contained in:
@@ -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();
|
||||
|
||||
@@ -33,6 +33,8 @@ class SecurityController extends Controller implements HasMiddleware
|
||||
$user = $request->user();
|
||||
$props = [
|
||||
'canManageTwoFactor' => Features::canManageTwoFactorAuthentication(),
|
||||
'mustChangePassword' => (bool) $user->must_change_password_on_next_login,
|
||||
'status' => session('status'),
|
||||
];
|
||||
|
||||
if (Features::canManageTwoFactorAuthentication()) {
|
||||
@@ -53,6 +55,7 @@ class SecurityController extends Controller implements HasMiddleware
|
||||
$user = $request->user();
|
||||
|
||||
$user->update([
|
||||
'must_change_password_on_next_login' => false,
|
||||
'password' => $request->password,
|
||||
]);
|
||||
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
<?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.*',
|
||||
'security.edit',
|
||||
'user-password.update',
|
||||
])) {
|
||||
return $next($request);
|
||||
}
|
||||
|
||||
return redirect()
|
||||
->route('security.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,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
@@ -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',
|
||||
];
|
||||
|
||||
@@ -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,
|
||||
]);
|
||||
|
||||
|
||||
@@ -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,
|
||||
|
||||
+30
@@ -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');
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -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>
|
||||
@@ -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,11 +40,20 @@ const hasPermission = (actorId: number, permission: string) =>
|
||||
description="Assign the global permissions that unlock platform-wide administration and project creation."
|
||||
/>
|
||||
|
||||
<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
|
||||
v-if="status"
|
||||
@@ -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(
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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;
|
||||
};
|
||||
|
||||
@@ -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');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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',
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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,23 @@ class AuthenticationTest extends TestCase
|
||||
$response->assertRedirect(route('dashboard', absolute: false));
|
||||
}
|
||||
|
||||
public function test_users_who_must_change_their_password_are_redirected_to_security_settings_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/ConfirmPassword'),
|
||||
);
|
||||
}
|
||||
|
||||
public function test_users_with_two_factor_enabled_are_redirected_to_two_factor_challenge()
|
||||
{
|
||||
$this->skipUnlessFortifyFeature(Features::twoFactorAuthentication());
|
||||
|
||||
@@ -89,6 +89,17 @@ 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('security.edit'));
|
||||
}
|
||||
|
||||
public function test_password_can_be_updated()
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
@@ -109,6 +120,26 @@ 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('security.edit'));
|
||||
|
||||
$this->assertFalse((bool) $user->refresh()->must_change_password_on_next_login);
|
||||
}
|
||||
|
||||
public function test_correct_password_must_be_provided_to_update_password()
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
|
||||
Reference in New Issue
Block a user