| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227 |
- <?php
- use Firebase\JWT\JWT;
- use Firebase\JWT\Key;
- /// 加密密钥
- $GLOBALS['token_key_secret'] = "z.1i8L?Ld+ovuA4r%4YZrz?w1Y%-NYvlrJ=TqV$[W[5=B#C[=l2gHV8gJ,DhZc";
- /// COOKIE 有效期
- $GLOBALS['cookieExpire'] = 60 * 60 * 24 * 7;
- /**
- * 响应成功json
- */
- if(!function_exists('json_success')){
- function json_success($data = [], $message = ""){
- return json([
- 'state' => 1,
- 'data' => $data,
- 'message' => $message ?? ""
- ]);
- }
- }
- /**
- * 响应失败json
- */
- if(!function_exists('json_error')){
- function json_error($data = [], $message = "", $code = 1){
- return json([
- 'state' => 0,
- 'code' => $code,
- 'data' => $data,
- 'message' => $message ?? ""
- ]);
- }
- }
- /**
- * 获取用户真实请求IP
- * 使用ThinkPHP内置的Request::ip()方法
- *
- * @return string 返回客户端真实IP地址
- */
- if(!function_exists('getClientIp')){
- function getClientIp() {
- return \think\facade\Request::ip();
- }
- }
- /**
- * 生成JWT Token
- *
- * @param array $data 待加密数据
- * @param int $expire 过期时间(秒),0表示使用默认过期时间
- * @return string
- */
- if(!function_exists('generateToken')){
- function generateToken($data = [], $expire = 0){
- $payload = [
- 'exp' => time() + ($expire > 0 ? $expire : $GLOBALS['cookieExpire']), // 有效期
- 'iat' => time(), // 签发时间
- ];
- $payload = array_merge($payload, $data);
- $token = JWT::encode($payload, $GLOBALS['token_key_secret'], 'HS256');
- return $token;
- }
- }
- /**
- * 解析JWT Token
- *
- * @param string $token JWT Token字符串
- * @return array|null 解析成功返回payload数组,失败返回null
- */
- if(!function_exists('parseToken')){
- function parseToken($token) {
- try {
- if (empty($token)) {
- return null;
- }
-
- // 使用JWT库解析token
- $decoded = JWT::decode($token, new Key($GLOBALS['token_key_secret'], 'HS256'));
-
- // 转换为数组
- $payload = (array) $decoded;
-
- // 检查是否过期
- if (isset($payload['exp']) && $payload['exp'] < time()) {
- return null;
- }
-
- return $payload;
-
- } catch (\Firebase\JWT\ExpiredException $e) {
- // Token已过期
- return null;
- } catch (\Firebase\JWT\SignatureInvalidException $e) {
- // 签名无效
- return null;
- } catch (\Firebase\JWT\BeforeValidException $e) {
- // Token尚未生效
- return null;
- } catch (\Exception $e) {
- // 其他异常
- return null;
- }
- }
- }
- /**
- * 验证Token是否有效
- *
- * @param string $token JWT Token字符串
- * @return bool
- */
- if(!function_exists('verifyToken')){
- function verifyToken($token) {
- return parseToken($token) !== null;
- }
- }
- /**
- * 检查用户登录状态
- *
- * @return array|null 登录成功返回用户信息数组,失败返回null
- */
- if(!function_exists('checkUserLogin')){
- function checkUserLogin() {
- $token = \think\facade\Cookie::get('auth_token');
- if (!$token) {
- return null;
- }
-
- return parseToken($token);
- }
- }
- /**
- * 检查用户权限
- *
- * @param array $user 用户信息数组
- * @param string $controller 控制器名称
- * @param string $action 操作名称
- * @param bool $checkIp 是否检查IP白名单,默认false
- * @return bool 有权限返回true,无权限返回false
- */
- if(!function_exists('checkPermission')){
- function checkPermission($user, $controller, $action, $checkIp = false) {
- // 超级管理员拥有所有权限
- $superAdminRoleId = \think\facade\Config::get('permission.super_admin_role_id', 1);
- if ($user['user_role'] == $superAdminRoleId) {
- // 即使是超级管理员,如果需要检查IP,也要验证
- if ($checkIp) {
- return checkUserIpWhiteList($user);
- }
- return true;
- }
-
- // 获取用户角色权限
- $role = \app\model\UserRoleModel::getRoleById($user['user_role'], $user['merchant_id']);
- if (!$role) {
- return false;
- }
-
- $privileges = $role->privileges;
-
- // 检查是否有对应权限
- $hasPermission = isset($privileges[$controller]) &&
- is_array($privileges[$controller]) &&
- in_array($action, $privileges[$controller]);
-
- // 如果有权限且需要检查IP,则进一步验证IP白名单
- if ($hasPermission && $checkIp) {
- return checkUserIpWhiteList($user);
- }
-
- return $hasPermission;
- }
- }
- /**
- * 检查用户IP白名单
- *
- * @param array $user 用户信息数组
- * @return bool IP在白名单中返回true,否则返回false
- */
- if(!function_exists('checkUserIpWhiteList')){
- function checkUserIpWhiteList($user) {
- // 获取用户完整信息
- $userModel = \app\model\UserModel::where('user_id', $user['user_id'])
- ->where('merchant_id', $user['merchant_id'])
- ->find();
-
- if (!$userModel) {
- return false;
- }
-
- // 获取客户端IP
- $clientIp = getClientIp();
-
- // 检查IP白名单
- return \app\service\IpWhiteListService::checkIpWhiteList($clientIp, $userModel->white_list_ip);
- }
- }
- /**
- * 检查用户登录状态并验证IP白名单
- *
- * @param bool $checkIp 是否检查IP白名单,默认false
- * @return array|null 验证通过返回用户信息数组,失败返回null
- */
- if(!function_exists('checkUserLoginWithIp')){
- function checkUserLoginWithIp($checkIp = false) {
- $user = checkUserLogin();
- if (!$user) {
- return null;
- }
-
- // 如果需要检查IP白名单
- if ($checkIp && !checkUserIpWhiteList($user)) {
- return null;
- }
-
- return $user;
- }
- }
|