Helper.php 3.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. <?php
  2. /**
  3. * 用户CP服务端登录验证(SDK和聚合全都使用同一个接口)
  4. */
  5. namespace app\api\controller\v1;
  6. use think\Cache;
  7. use app\api\controller\Api;
  8. use think\Config;
  9. use think\Env;
  10. class Helper extends Api
  11. {
  12. public function _initialize()
  13. {
  14. self::initDevice();
  15. }
  16. /**
  17. * 校验Token 是否有效
  18. */
  19. public function checkToken()
  20. {
  21. log_message("Helper@checkToken.input: " . json_encode(input()), 'log', LOG_PATH . 'Helper/input/');
  22. if (request()->isPost()) {
  23. $token = input('post.token');
  24. if(!$token){
  25. $token = $_POST['token']??""; // 兼容某些特殊情况post取不到值
  26. }
  27. $username = input('post.username');
  28. $result = $this->validate(
  29. [
  30. 'token' => $token,
  31. 'username' => $username
  32. ],
  33. [
  34. ['token', 'require', 'token不能为空'],
  35. ['username', 'require', 'username不能为空']
  36. ]);
  37. if (true !== $result) {
  38. $this->result('', 0, $result, 'json');
  39. }
  40. // 空格转换为+
  41. $token = str_replace(" ", "+", $token);
  42. // 检查字符串中是否包含反斜线
  43. if (strpos($token, '\\') !== false) {
  44. // 如果包含反斜线,则使用 stripslashes
  45. $token = stripslashes($token);
  46. }
  47. log_message($username . "====" . $token, 'log', LOG_PATH . 'Helper/checkToken/');
  48. $r = Cache::store('redis')->get($token);
  49. if ( !$r ) {
  50. log_message('验证不通过的参数'.$username."====".$token,'log',LOG_PATH . 'Helper/checkToken/');
  51. $this->result('',0,'无效token','json');
  52. }
  53. if(!auth_code($token, "DECODE", Env::get($this->authKey))){
  54. $this->jsonResult('', -135, '登陆异常, 请重新登录!', 'json');
  55. }
  56. //聚合渠道时,$sub_username对应的值是mg_username
  57. list($userid2, $username2, $gameid2,$sub_username,$token_random,$type) = explode('|', auth_code($token,"DECODE", Env::get($this->authKey)));
  58. $redisTokenRandom = Cache::store('redis')->get('token|'.$type.'|'.$userid2.'|'.$gameid2);
  59. //redis中玩家登录安全控制的随机码不存在时
  60. if ( !$redisTokenRandom ) {
  61. Cache::store('redis')->rm($token);
  62. $this->result('',0,'token随机码不存在','json');
  63. }
  64. //两个token随机码不同时
  65. elseif($redisTokenRandom!=$token_random){
  66. Cache::store('redis')->rm($token);
  67. $this->result('',0,'token随机码错误','json');
  68. }
  69. if (strtolower($sub_username) != strtolower($username)) {
  70. $this->result('',0,'username错误','json');
  71. }
  72. $this->result('',1,'有效token','json');
  73. }
  74. else{
  75. $this->result('',0,'请认真查看文档,使用正确的请求方式','json');
  76. }
  77. }
  78. }