From 3753e759ddc0a2104f17a42ab1514c24a30bf934 Mon Sep 17 00:00:00 2001 From: Liang Tao Date: Mon, 24 Mar 2014 14:55:57 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0authorize=5Fdownload=5Furl()?= =?UTF-8?q?=EF=BC=8C=E7=94=A8=E4=BA=8E=E5=AF=B9=E7=A7=81=E6=9C=89=E8=B5=84?= =?UTF-8?q?=E6=BA=90=E4=B8=8B=E8=BD=BDURL=E8=BF=9B=E8=A1=8C=E6=8E=88?= =?UTF-8?q?=E6=9D=83=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- lib/qiniu/auth.rb | 51 ++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 50 insertions(+), 1 deletion(-) diff --git a/lib/qiniu/auth.rb b/lib/qiniu/auth.rb index 867e4a3..1f5d59a 100755 --- a/lib/qiniu/auth.rb +++ b/lib/qiniu/auth.rb @@ -1,5 +1,7 @@ # -*- encoding: utf-8 -*- +require 'hmac-sha1' + require 'qiniu/exceptions' module Qiniu @@ -19,7 +21,54 @@ module Qiniu [code, data] end - end + EMPTY_ARGS = {} + + ### 生成下载授权URL + def authorize_download_url(url, args = EMPTY_ARGS) + ### 提取AK/SK信息 + ak = args[:access_key] + if ak.nil? then + ak = Config.settings[:access_key] + end + + sk = args[:access_key] + if sk.nil? then + sk = Config.settings[:secret_key] + end + + ### 授权期计算 + if args[:expires].is_a?(Integer) && args[:expires] > 0 then + # 指定相对时间,单位:秒 + e = Time.now.to_i + args[:expires] + elsif args[:deadline].is_a?(Integer) then + # 指定绝对时间,常用于调试和单元测试 + e = args[:deadline] + else + # 默认授权期1小时 + e = Time.now.to_i + 3600 + end + + ### URL变换:追加授权期参数 + if url.index('?').is_a?(Fixnum) then + # 已有参数 + download_url = "#{url}&e=#{e}" + else + # 尚无参数 + download_url = "#{url}?e=#{e}" + end + + ### 生成数字签名 + sign = HMAC::SHA1.new(secret_key).update(download_url) + encoded_sign = Utils.urlsafe_base64_encode(sign) + + ### 生成下载授权凭证 + dntoken = "#{access_key}:#{encoded_sign}" + + ### 返回下载授权URL及相关参数 + return "#{download_url}&token=#{dntoken}", e, dntoken + end # authorize_download_url + + end # class << self end # module Auth end # module Qiniu