You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

80 lines
1.9 KiB
PHP

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

<?php
namespace App\Services;
use Illuminate\Support\Facades\DB;
class UserService
{
/**
* 从 JWT payload 获取用户完整信息
* @param array|null $payload
* @return object|null
*/
public function getUserInfoFromPayload($payload)
{
if (!$payload || !isset($payload['user_id'])) {
return null;
}
return DB::table('sys_user')
->where('id', $payload['user_id'])
->where('deleted', 0)
->first();
}
/**
* 从 Request 获取用户信息
* @param \Illuminate\Http\Request $request
* @return object|null
*/
public function getUserInfoFromRequest($request)
{
$payload = $request->attributes->get('payload');
return $this->getUserInfoFromPayload($payload);
}
/**
* 判断用户是否为管理员
* @param array|null $payload
* @return bool
*/
public function isAdmin($payload)
{
if (!$payload || !isset($payload['roles'])) {
return false;
}
// JWT payload 中已包含 roles直接判断即可
$roles = $payload['roles'];
// 检查是否包含 admin 或 ADMIN
return in_array('admin', $roles) || in_array('ADMIN', $roles);
}
/**
* 从 Request 判断用户是否为管理员
* @param \Illuminate\Http\Request $request
* @return bool
*/
public function isAdminFromRequest($request)
{
$payload = $request->attributes->get('payload');
return $this->isAdmin($payload);
}
/**
* 获取用户角色列表
* @param int $userId
* @return array
*/
public function getUserRoles($userId)
{
return DB::table('sys_user_role')
->join('sys_role', 'sys_user_role.role_id', '=', 'sys_role.id')
->where('sys_user_role.user_id', $userId)
->pluck('sys_role.role_code')
->toArray();
}
}