Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save BluntBlade/10103223 to your computer and use it in GitHub Desktop.
Save BluntBlade/10103223 to your computer and use it in GitHub Desktop.
def calculate_deadline(expires_in, deadline = nil)
### 授权期计算
if expires_in.is_a?(Integer) && expires_in > 0 then
# 指定相对时间,单位:秒
return Time.now.to_i + expires_in
elsif deadline.is_a?(Integer) then
# 指定绝对时间,常用于调试和单元测试
return deadline
end
# 默认授权期1小时
return Time.now.to_i + DEFAULT_AUTH_SECONDS
end # calculate_deadline
### 生成下载授权URL
def authorize_download_url(url, args = EMPTY_ARGS)
### 提取AK/SK信息
access_key = Config.settings[:access_key]
secret_key = Config.settings[:secret_key]
### 授权期计算
e = Auth.calculate_deadline(args[:expires_in], args[:deadline])
### 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).digest
encoded_sign = Utils.urlsafe_base64_encode(sign)
### 生成下载授权凭证
dntoken = "#{access_key}:#{encoded_sign}"
### 返回下载授权URL
return "#{download_url}&token=#{dntoken}"
end # authorize_download_url
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment