ApiSignFacadeRepository.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. namespace app\Repositories\Eloquent;
  3. use App\Repositories\Eloquent\BaseRepository;
  4. use App\Repositories\Contracts\ApiSignInterface;
  5. use Illuminate\Support\Facades\Redis;
  6. /**
  7. *
  8. * @author lilin
  9. *
  10. */
  11. class ApiSignFacadeRepository extends BaseRepository implements ApiSignInterface
  12. {
  13. public function auth($encryptedStr, $random, $timesTamp)
  14. {
  15. //api请求最大时间差
  16. $apiMaxTime = config('console.apiMaxTime');
  17. $logArr = [
  18. 'encryptedStr' => $encryptedStr,
  19. 'random' => $random,
  20. 'timesTamp' => $timesTamp
  21. ];
  22. if (!$encryptedStr || !$random || strlen($timesTamp) > 10){
  23. $this->setLog('api请求验证, 验证参数不正确', $this->startTime(), $logArr);
  24. $this->error()->authenticationFailed();
  25. }
  26. if (time() - $timesTamp > $apiMaxTime) {
  27. $this->setLog('api请求验证, 请求时间差大于配制时间', $this->startTime, $logArr);
  28. $this->error()->authenticationFailed();
  29. }
  30. $pemPath = public_path('rsa/api_rsa_private_key.pem');
  31. $privateKey = file_get_contents($pemPath);
  32. $piKey = openssl_pkey_get_private($privateKey);
  33. $decrypted = '';
  34. openssl_private_decrypt(base64_decode($encryptedStr), $decrypted, $piKey, OPENSSL_PKCS1_PADDING);
  35. $data = json_decode($decrypted, true);
  36. if (!$decrypted){
  37. $this->setLog('api请求验证,签名解密失败', $this->startTime, $logArr);
  38. $this->error()->authenticationFailed();
  39. }
  40. //从redis里找有没有用过
  41. $key = config('console.redis_key.api_auth').$random;
  42. $exists = Redis::EXISTS($key);
  43. if ($exists){
  44. $this->setLog('api请求验证,使用了重复的签名', $this->startTime, $logArr);
  45. $this->error()->authenticationFailed();
  46. }
  47. if (!isset($data['appid']) || $data['appid'] != config('console.apiAppid')){
  48. $this->setLog('api请求验证,appid错误', $this->startTime, $logArr);
  49. $this->error()->authenticationFailed();
  50. }
  51. if (!isset($data['random']) || !isset($data['timestamp']) || $data['random'] != $random || $data['timestamp'] != $timesTamp) {
  52. $this->setLog('api请求验证,random和timestamp不一致', $this->startTime, $logArr);
  53. $this->error()->authenticationFailed();
  54. }
  55. //验证通过加入reids,过期时间为最大时间差
  56. Redis::SET($key, $encryptedStr);
  57. Redis::EXPIRE($key, $apiMaxTime);
  58. return $this->response();
  59. }
  60. }