use
Qiniu::Util
qw/encode_json safe_b64_encode hmac_sha1/
;
our
$VERSION
=
'0.05'
;
use
constant
DEFAULT_AUTH_SECONDS
=> 3600;
has
[
qw/access_key secret_key/
] => (
is
=>
'ro'
,
required
=> 1,
);
has
Fields
=> (
is
=>
'rw'
,
default
=>
sub
{
return
{
scope
=>
""
,
saveKey
=>
""
,
endUser
=>
""
,
returnUrl
=>
""
,
returnBody
=>
""
,
callbackUrl
=>
""
,
callbackBody
=>
""
,
callbackBodyType
=>
""
,
persistentOps
=>
""
,
persistentNotifyUrl
=>
""
,
insertOnly
=>
""
,
fsizeLimit
=>
""
,
detectMime
=>
""
,
mimeLimit
=>
""
,
deadline
=>
""
,
}
}
);
sub
upload_token {
my
(
$self
,
$bucket
,
$key
,
$expires_in
,
$args
) =
@_
;
die
"need bucket"
if
!
$bucket
;
$self
->setPolicy(
$args
)
if
$args
;
my
$scope
=
defined
$key
?
"${bucket}:${key}"
:
$bucket
;
my
$calculateDeadLine
= calculateDeadLine(
$expires_in
);
$self
->setPolicy(
scope
=>
$scope
);
$self
->setPolicy(
deadline
=>
$calculateDeadLine
);
my
$encodedPutPolicy
= safe_b64_encode(
$self
->PUTPolicy);
return
$self
->createToken(
$encodedPutPolicy
) .
':'
.
$encodedPutPolicy
;
}
sub
PUTPolicy {
my
(
$self
) =
@_
;
my
$Fields
=
$self
->Fields;
my
%args
=
map
{
$_
=>
$Fields
->{
$_
} }
grep
{
$Fields
->{
$_
} }
keys
%$Fields
;
return
encode_json(\
%args
)
}
sub
private_url {
my
$self
=
shift
;
my
$download_url
=
shift
;
my
$e
=
time
()+3600;
$download_url
=
$download_url
.
"?e=$e"
;
my
$token
=
$self
->crate_token(
$download_url
);
return
$download_url
.
"&token="
.
$token
;
}
sub
manage_token {
my
$self
=
shift
;
return
$self
->createToken(
@_
)
}
sub
createToken {
my
(
$self
,
$signing_str
) =
@_
;
my
$sign
= hmac_sha1(
$signing_str
,
$self
->secret_key);
my
$encoded_sign
= safe_b64_encode(
$sign
);
return
$self
->access_key .
':'
.
$encoded_sign
;
}
sub
setPolicy {
my
(
$self
,
$key
,
$value
) =
@_
;
if
(
ref
$key
eq
'HASH'
) {
while
(
my
(
$k
,
$v
) =
each
%$key
) {
$self
->Fields->{
$k
} =
$v
if
$v
;
}
}
else
{
$self
->Fields->{
$key
} =
$value
}
}
sub
calculateDeadLine() {
my
(
$expires_in
,
$deadline
) =
@_
;
if
(
$expires_in
and
$expires_in
> 0) {
return
time
() +
$expires_in
;
}
return
time
() + DEFAULT_AUTH_SECONDS;
}
1;