common.php 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. <?php
  2. require_once "common/GameGameConfig.php";
  3. use Firebase\JWT\JWT;
  4. use Firebase\JWT\Key;
  5. /// 加密密钥
  6. $GLOBALS['token_key_secret'] = "z.1i8L?Ld+ovuA4r%4YZrz?w1Y%-NYvlrJ=TqV$[W[5=B#C[=l2gHV8gJ,DhZc";
  7. /// COOKIE 有效期
  8. $GLOBALS['cookieExpire'] = 60 * 60 * 24 * 3;
  9. /**
  10. * 响应成功json
  11. */
  12. if(!function_exists('json_success')){
  13. function json_success($data = [], $message = "", $code = 0){
  14. return json([
  15. 'state' => 1,
  16. 'code' => $code,
  17. 'data' => $data,
  18. 'message' => $message ?? ""
  19. ]);
  20. }
  21. }
  22. /**
  23. * 响应失败json
  24. */
  25. if(!function_exists('json_error')){
  26. function json_error($data = [], $message = "", $code = 0){
  27. return json([
  28. 'state' => 0,
  29. 'code' => $code,
  30. 'data' => $data,
  31. 'message' => $message ?? ""
  32. ]);
  33. }
  34. }
  35. /**
  36. * 获取用户真实请求IP
  37. * 使用ThinkPHP内置的Request::ip()方法
  38. *
  39. * @return string 返回客户端真实IP地址
  40. */
  41. if(!function_exists('getClientIp')){
  42. function getClientIp() {
  43. return \think\facade\Request::ip();
  44. }
  45. }
  46. /**
  47. * 生成JWT Token
  48. *
  49. * @param array $data 待加密数据
  50. * @param int $expire 过期时间(秒),0表示使用默认过期时间
  51. * @return string
  52. */
  53. if(!function_exists('generateToken')){
  54. function generateToken($data = [], $expire = 0){
  55. $payload = [
  56. 'exp' => time() + ($expire > 0 ? $expire : $GLOBALS['cookieExpire']), // 有效期
  57. 'iat' => time(), // 签发时间
  58. ];
  59. $payload = array_merge($payload, $data);
  60. $token = JWT::encode($payload, $GLOBALS['token_key_secret'], 'HS256');
  61. return $token;
  62. }
  63. }
  64. /**
  65. * 解析JWT Token
  66. *
  67. * @param string $token JWT Token字符串
  68. * @return array|null 解析成功返回payload数组,失败返回null
  69. */
  70. if(!function_exists('parseToken')){
  71. function parseToken($token) {
  72. try {
  73. if (empty($token)) {
  74. return null;
  75. }
  76. // 使用JWT库解析token
  77. $decoded = JWT::decode($token, new Key($GLOBALS['token_key_secret'], 'HS256'));
  78. // 转换为数组
  79. $payload = (array) $decoded;
  80. // 检查是否过期
  81. if (isset($payload['exp']) && $payload['exp'] < time()) {
  82. return null;
  83. }
  84. return $payload;
  85. } catch (\Firebase\JWT\ExpiredException $e) {
  86. // Token已过期
  87. return null;
  88. } catch (\Firebase\JWT\SignatureInvalidException $e) {
  89. // 签名无效
  90. return null;
  91. } catch (\Firebase\JWT\BeforeValidException $e) {
  92. // Token尚未生效
  93. return null;
  94. } catch (\Exception $e) {
  95. // 其他异常
  96. return null;
  97. }
  98. }
  99. }
  100. /**
  101. * 验证Token是否有效
  102. *
  103. * @param string $token JWT Token字符串
  104. * @return bool
  105. */
  106. if(!function_exists('verifyToken')){
  107. function verifyToken($token) {
  108. return parseToken($token) !== null;
  109. }
  110. }
  111. /**
  112. * 检查用户登录状态
  113. *
  114. * @return array|null 登录成功返回用户信息数组,失败返回null
  115. */
  116. if(!function_exists('checkUserLogin')){
  117. function checkUserLogin() {
  118. $token = \think\facade\Cookie::get('auth_token');
  119. if (!$token) {
  120. return null;
  121. }
  122. return parseToken($token);
  123. }
  124. }
  125. /**
  126. * 获取当前登录用户ID
  127. */
  128. if(!function_exists('getUserId')){
  129. function getUserId(): int {
  130. $userInfo = checkUserLogin();
  131. return $userInfo ? (int)$userInfo['user_id'] : 0;
  132. }
  133. }
  134. /**
  135. * 获取当前登录用户角色ID
  136. */
  137. if(!function_exists('getUserRoleId')){
  138. function getUserRoleId(int $userId): int {
  139. if (!$userId) {
  140. return 0;
  141. }
  142. $user = \app\model\UserModel::where('user_id', $userId)->find();
  143. return $user ? (int)$user->user_role : 0;
  144. }
  145. }
  146. /**
  147. * 检查用户权限
  148. *
  149. * @param array $user 用户信息数组
  150. * @param string $controller 控制器名称
  151. * @param string $action 操作名称
  152. * @param bool $checkIp 是否检查IP白名单,默认false
  153. * @return bool 有权限返回true,无权限返回false
  154. */
  155. if(!function_exists('checkPermission')){
  156. function checkPermission($user, $controller, $action, $checkIp = false) {
  157. $userId = is_array($user) ? (int)$user['user_id'] : 0;
  158. if (!$userId) {
  159. return false;
  160. }
  161. // 使用PermissionService统一权限检查
  162. $hasPermission = \app\service\PermissionService::checkPermission($userId, $controller, $action);
  163. // 如果有权限且需要检查IP,则进一步验证IP白名单
  164. if ($hasPermission && $checkIp) {
  165. return checkUserIpWhiteList($user);
  166. }
  167. return $hasPermission;
  168. }
  169. }
  170. /**
  171. * 检查用户IP白名单
  172. *
  173. * @param array $user 用户信息数组
  174. * @return bool IP在白名单中返回true,否则返回false
  175. */
  176. if(!function_exists('checkUserIpWhiteList')){
  177. function checkUserIpWhiteList($user) {
  178. // 获取用户完整信息
  179. $userModel = \app\model\UserModel::where('user_id', $user['user_id'])
  180. ->where('merchant_id', $user['merchant_id'])
  181. ->find();
  182. if (!$userModel) {
  183. return false;
  184. }
  185. // 获取客户端IP
  186. $clientIp = getClientIp();
  187. // 检查IP白名单
  188. return \app\service\IpWhiteListService::checkIpWhiteList($clientIp, $userModel->white_list_ip);
  189. }
  190. }
  191. /**
  192. * 检查用户登录状态并验证IP白名单
  193. *
  194. * @param bool $checkIp 是否检查IP白名单,默认false
  195. * @return array|null 验证通过返回用户信息数组,失败返回null
  196. */
  197. if(!function_exists('checkUserLoginWithIp')){
  198. function checkUserLoginWithIp($checkIp = false) {
  199. $user = checkUserLogin();
  200. if (!$user) {
  201. return null;
  202. }
  203. // 如果需要检查IP白名单
  204. if ($checkIp && !checkUserIpWhiteList($user)) {
  205. return null;
  206. }
  207. return $user;
  208. }
  209. }