3 namespace Tests\Helpers;
5 use BookStack\Permissions\PermissionsRepo;
6 use BookStack\Users\Models\Role;
7 use BookStack\Users\Models\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 * Get the system "guest" user.
56 public function guest(): User
58 return User::getGuest();
62 * Create a new fresh user without any relations.
64 public function newUser(array $attrs = []): User
66 return User::factory()->create($attrs);
70 * Create a new fresh user, with the given attrs, that has assigned a fresh role
71 * that has the given role permissions.
72 * Intended as a helper to create a blank slate baseline user and role.
73 * @return array{0: User, 1: Role}
75 public function newUserWithRole(array $userAttrs = [], array $rolePermissions = []): array
77 $user = $this->newUser($userAttrs);
78 $role = $this->attachNewRole($user, $rolePermissions);
80 return [$user, $role];
84 * Attach a new role, with the given role permissions, to the given user
85 * and return that role.
87 public function attachNewRole(User $user, array $rolePermissions = []): Role
89 $role = $this->createRole($rolePermissions);
90 $user->attachRole($role);
95 * Create a new basic role with the given role permissions.
97 public function createRole(array $rolePermissions = []): Role
99 $permissionRepo = app(PermissionsRepo::class);
100 $roleData = Role::factory()->make()->toArray();
101 $roleData['permissions'] = $rolePermissions;
103 return $permissionRepo->saveNewRole($roleData);