Skip to content

Commit

Permalink
reactor(batch user roles): 批量设置用户所属角色、获取用户所属角色列表
Browse files Browse the repository at this point in the history
  • Loading branch information
zds-s committed Oct 8, 2024
1 parent 38b37bf commit 620c37a
Show file tree
Hide file tree
Showing 8 changed files with 44 additions and 26 deletions.
15 changes: 10 additions & 5 deletions app/Http/Admin/Controller/Permission/UserController.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
use App\Http\Common\Middleware\OperationMiddleware;
use App\Http\Common\Result;
use App\Http\CurrentUser;
use App\Model\Permission\Role;
use App\Schema\UserSchema;
use App\Service\Permission\UserService;
use Hyperf\Collection\Arr;
Expand Down Expand Up @@ -148,27 +149,31 @@ public function save(int $userId, UserRequest $request): Result
}

#[Get(
path: '/admin/user/getUserRole/{userId}',
path: '/admin/user/{userId}/roles',
operationId: 'getUserRole',
summary: '获取用户角色列表',
security: [['Bearer' => [], 'ApiKey' => []]],
tags: ['用户管理']
)]
#[Permission(code: 'user:getRole')]
#[Permission(code: 'user:get:roles')]
#[ResultResponse(new Result())]
public function getUserRole(int $userId): Result
{
return $this->success($this->userService->getUserRole($userId));
return $this->success($this->userService->getUserRole($userId)->map(static fn (Role $role) => $role->only([
'id',
'code',
'name',
])));
}

#[Put(
path: '/admin/user/setUserRole/{userId}',
path: '/admin/user/{userId}/roles',
operationId: 'batchGrantRolesForUser',
summary: '批量授权用户角色',
security: [['Bearer' => [], 'ApiKey' => []]],
tags: ['用户管理']
)]
#[Permission(code: 'user:setRole')]
#[Permission(code: 'user:set:roles')]
#[RequestBody(content: new JsonContent(ref: BatchGrantRolesForUserRequest::class, title: '批量授权用户角色'))]
#[ResultResponse(new Result())]
public function batchGrantRolesForUser(int $userId, BatchGrantRolesForUserRequest $request): Result
Expand Down
2 changes: 1 addition & 1 deletion app/Http/CurrentUser.php
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ public function menus(): Collection
*/
public function roles(): Collection
{
return $this->user()->getRoles();
return $this->user()->getRoles()->map(static fn (Role $role) => $role->only(['name', 'code', 'remark']));
}

public function isSystem(): bool
Expand Down
1 change: 0 additions & 1 deletion app/Model/Permission/User.php
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,6 @@ public function getRoles(): Collection
{
return $this->roles()
->where('status', Status::ENABLE)
->select(['name', 'code', 'remark'])
->get();
}

Expand Down
3 changes: 1 addition & 2 deletions app/Service/Permission/UserService.php
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,7 @@ public function resetPassword(?int $id): bool

public function getUserRole(int $id): Collection
{
$entity = $this->repository->findById($id);
return $entity->getRoles();
return $this->repository->findById($id)->roles()->get();
}

public function batchGrantRoleForUser(int $id, array $roleCodes): void
Expand Down
4 changes: 2 additions & 2 deletions databases/seeders/menu_seeder_20240926.php
Original file line number Diff line number Diff line change
Expand Up @@ -138,15 +138,15 @@ public function data(): array
]),
],
[
'name' => 'permission:user:getRole',
'name' => 'user:get:roles',
'meta' => new Meta([
'title' => '获取用户角色',
'type' => 'B',
'i18n' => 'baseMenu.permission.getUserRole',
]),
],
[
'name' => 'permission:user:setRole',
'name' => 'user:set:roles',
'meta' => new Meta([
'title' => '用户角色赋予',
'type' => 'B',
Expand Down
2 changes: 1 addition & 1 deletion storage/swagger/http.json

Large diffs are not rendered by default.

39 changes: 27 additions & 12 deletions tests/Feature/Admin/Permission/UserControllerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -234,41 +234,56 @@ public function testBatchGrantRolesForUser(): void
{
$token = $this->token;
$user = $this->user;
$uri = '/admin/user/' . $user->id . '/roles';
$roles = [
Role::create([
'name' => Str::random(10),
'code' => Str::random(10),
'name' => Str::random(22),
'code' => Str::random(22),
'sort' => rand(1, 100),
'status' => rand(0, 1),
'remark' => Str::random(),
]),
Role::create([
'name' => Str::random(10),
'code' => Str::random(10),
'name' => Str::random(22),
'code' => Str::random(22),
'sort' => rand(1, 100),
'status' => rand(0, 1),
'remark' => Str::random(),
]),
Role::create([
'name' => Str::random(10),
'code' => Str::random(10),
'name' => Str::random(22),
'code' => Str::random(22),
'sort' => rand(1, 100),
'status' => rand(0, 1),
'remark' => Str::random(),
]),
];
$roleIds = array_map(static fn ($role) => $role->id, $roles);
$roleCodes = array_map(static fn ($role) => $role->code, $roles);
$result = $this->put('/admin/user/setUserRole/' . $user->id, ['role_codes' => $roleCodes]);
$result = $this->put($uri, ['role_codes' => $roleCodes]);
self::assertSame(Arr::get($result, 'code'), ResultCode::UNAUTHORIZED->value);
$result = $this->put('/admin/user/setUserRole/' . $user->id, ['role_codes' => $roleCodes], ['Authorization' => 'Bearer ' . $token]);
$result = $this->put($uri, ['role_codes' => $roleCodes], ['Authorization' => 'Bearer ' . $token]);
self::assertSame(Arr::get($result, 'code'), ResultCode::FORBIDDEN->value);
$enforce = $this->getEnforce();
self::assertFalse($enforce->hasPermissionForUser($this->user->username, 'user:setRole'));
self::assertTrue($enforce->addPermissionForUser($this->user->username, 'user:setRole'));
self::assertTrue($enforce->hasPermissionForUser($this->user->username, 'user:setRole'));
$result = $this->put('/admin/user/setUserRole/' . $user->id, ['role_codes' => $roleCodes], ['Authorization' => 'Bearer ' . $token]);

self::assertFalse($enforce->hasPermissionForUser($this->user->username, 'user:set:roles'));
self::assertTrue($enforce->addPermissionForUser($this->user->username, 'user:set:roles'));
self::assertTrue($enforce->hasPermissionForUser($this->user->username, 'user:set:roles'));

self::assertFalse($enforce->hasPermissionForUser($this->user->username, 'user:get:roles'));
self::assertTrue($enforce->addPermissionForUser($this->user->username, 'user:get:roles'));
self::assertTrue($enforce->hasPermissionForUser($this->user->username, 'user:get:roles'));

$result = $this->put($uri, ['role_codes' => $roleCodes], ['Authorization' => 'Bearer ' . $token]);
self::assertSame(Arr::get($result, 'code'), ResultCode::SUCCESS->value);

$result = $this->get($uri, [], ['Authorization' => 'Bearer ' . $token]);
self::assertSame(Arr::get($result, 'code'), ResultCode::SUCCESS->value);
self::assertSame(\count(Arr::get($result, 'data')), \count($roles));
foreach ($roles as $role) {
self::assertContains($role->code, Arr::pluck(Arr::get($result, 'data'), 'code'));
}

$user->refresh();
self::assertSame($user->roles()->pluck('role.id')->toArray(), $roleIds);
}
Expand Down
4 changes: 2 additions & 2 deletions web/src/modules/base/api/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,9 @@ export function updateInfo(data: UserVo): Promise<ResponseStruct<null>> {
}

export function getUserRole(id: number): Promise<ResponseStruct<any[]>> {
return useHttp().get(`/admin/user/getUserRole/${id}`)
return useHttp().get(`/admin/user/${id}/roles`)
}

export function setUserRole(id: number, role_codes: string[]): Promise<ResponseStruct<null>> {
return useHttp().put(`/admin/user/setUserRole/${id}`, { role_codes })
return useHttp().put(`/admin/user/${id}/roles`, { role_codes })
}

0 comments on commit 620c37a

Please sign in to comment.