3 namespace Tests\Helpers;
5 use BookStack\Auth\Permissions\PermissionsRepo;
6 use BookStack\Auth\Role;
7 use BookStack\Auth\User;
11 protected ?User $admin = null;
12 protected ?User $editor = null;
15 * Get a typical "Admin" user.
17 public function admin(): User
19 if (is_null($this->admin)) {
20 $adminRole = Role::getSystemRole('admin');
21 $this->admin = $adminRole->users->first();
28 * Get a typical "Editor" user.
30 public function editor(): User
32 if ($this->editor === null) {
33 $editorRole = Role::getRole('editor');
34 $this->editor = $editorRole->users->first();
41 * Get a typical "Viewer" user.
43 public function viewer(array $attributes = []): User
45 $user = Role::getRole('viewer')->users()->first();
46 if (!empty($attributes)) {
47 $user->forceFill($attributes)->save();
54 * Create a new fresh user, with the given attrs, that has assigned a fresh role
55 * that has the given role permissions.
56 * Intended as a helper to create a blank slate baseline user and role.
57 * @return array{0: User, 1: Role}
59 public function newUserWithRole(array $userAttrs = [], array $rolePermissions = []): array
61 $user = User::factory()->create($userAttrs);
62 $role = $this->attachRole($user, $rolePermissions);
64 return [$user, $role];
68 * Attach a new role, with the given role permissions, to the given user
69 * and return that role.
71 public function attachRole(User $user, array $rolePermissions = []): Role
73 $role = $this->createRole($rolePermissions);
74 $user->attachRole($role);
79 * Create a new basic role with the given role permissions.
81 public function createRole(array $rolePermissions = []): Role
83 $permissionRepo = app(PermissionsRepo::class);
84 $roleData = Role::factory()->make()->toArray();
85 $roleData['permissions'] = array_flip($rolePermissions);
87 return $permissionRepo->saveNewRole($roleData);