Auth.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. namespace addons\alioss\library;
  3. use app\common\library\Upload;
  4. class Auth
  5. {
  6. public function __construct()
  7. {
  8. }
  9. public function params($name, $md5, $callback = true)
  10. {
  11. $config = get_addon_config('alioss');
  12. $callback_param = array(
  13. 'callbackUrl' => isset($config['notifyurl']) ? $config['notifyurl'] : '',
  14. 'callbackBody' => 'filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}',
  15. 'callbackBodyType' => "application/x-www-form-urlencoded"
  16. );
  17. $base64_callback_body = base64_encode(json_encode($callback_param));
  18. $now = time();
  19. $end = $now + $config['expire']; //设置该policy超时时间是10s. 即这个policy过了这个有效时间,将不能访问
  20. $expiration = $this->gmt_iso8601($end);
  21. preg_match('/(\d+)(\w+)/', $config['maxsize'], $matches);
  22. $type = strtolower($matches[2]);
  23. $typeDict = ['b' => 0, 'k' => 1, 'kb' => 1, 'm' => 2, 'mb' => 2, 'gb' => 3, 'g' => 3];
  24. $size = (int)$config['maxsize'] * pow(1024, isset($typeDict[$type]) ? $typeDict[$type] : 0);
  25. //最大文件大小.用户可以自己设置
  26. $condition = array(0 => 'content-length-range', 1 => 0, 2 => $size);
  27. $conditions[] = $condition;
  28. //表示用户上传的数据,必须是以$dir开始, 不然上传会失败,这一步不是必须项,只是为了安全起见,防止用户通过policy上传到别人的目录
  29. //$start = array(0 => 'starts-with', 1 => '$key', 2 => $dir);
  30. //$conditions[] = $start;
  31. $arr = array('expiration' => $expiration, 'conditions' => $conditions);
  32. $policy = base64_encode(json_encode($arr));
  33. $signature = base64_encode(hash_hmac('sha1', $policy, $config['accessKeySecret'], true));
  34. $key = (new Upload())->getSavekey($config['savekey'], $name, $md5);
  35. $key = ltrim($key, "/");
  36. $response = array();
  37. $response['id'] = $config['accessKeyId'];
  38. $response['key'] = $key;
  39. $response['policy'] = $policy;
  40. $response['signature'] = $signature;
  41. $response['expire'] = $end;
  42. $response['callback'] = '';
  43. return $response;
  44. }
  45. public function check($signature, $policy)
  46. {
  47. $config = get_addon_config('alioss');
  48. $sign = base64_encode(hash_hmac('sha1', $policy, $config['accessKeySecret'], true));
  49. return $signature == $sign;
  50. }
  51. private function gmt_iso8601($time)
  52. {
  53. $dtStr = date("c", $time);
  54. $mydatetime = new \DateTime($dtStr);
  55. $expiration = $mydatetime->format(\DateTime::ISO8601);
  56. $pos = strpos($expiration, '+');
  57. $expiration = substr($expiration, 0, $pos);
  58. return $expiration . "Z";
  59. }
  60. }