common.php 6.1 KB

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