12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879 |
- <?php
- namespace Modules\User\Http\Controllers;
- use Illuminate\Support\Collection;
- use Illuminate\Support\Facades\DB;
- use Modules\Common\Errors\Errors;
- use Modules\Common\Exceptions\CommonBusinessException;
- use Modules\User\Models\User;
- trait UserTrait
- {
-
- protected $currentUser;
-
- protected function getCurrentUser(): User {
- if(!$this->currentUser) {
- $this->currentUser = $this->getLoginUser();
- }
- return $this->currentUser;
- }
-
- protected function listUserRoles():Collection {
- return $this->getCurrentUser()->roles->pluck('identify');
- }
-
- public function userIsCp():bool {
- return $this->listUserRoles()->contains('cp');
- }
-
- public function getUserCpName():string|null {
- if($this->userIsCp()) {
- return DB::table('user_belong_to_cp')
- ->where([
- 'is_enabled' => 1,
- 'user_id' => $this->getCurrentUser()->id,
- ])->value('cp_name');
- } else {
- return null;
- }
- }
- protected function getUserContext($operateUserId) {
- $loginUser = $this->getLoginUser();
- $loginUserRoles = $this->listUserRoles();
- if($operateUserId) {
- $operateUser = User::find($operateUserId);
- $operateUserRoles = $operateUser->roles->pluck('identify');
- if($loginUser->id != $operateUser->pid) {
- CommonBusinessException::throwError(Errors::NO_OPERATE_PERMISSION);
- }
- if(!$operateUserRoles->contains('optimizer')) {
- CommonBusinessException::throwError(Errors::NO_OPERATE_PERMISSION);
- }
- } else {
- $operateUser = $loginUser;
- $operateUserRoles = $loginUserRoles;
- }
- return compact('loginUser', 'loginUserRoles', 'operateUserRoles', 'operateUser');
- }
- }
|