Cowherd
Cowherd is an automatic token issuer help create upload/download tokens for Qiniu CDN service in Node.js.
Install cowherd from NPM registry
npm install --save cowherd
Usage
Create a new Node.js project
npm init
Edit index.js
:
var cowherd = ; ;
Run index.js
and send POST request to http://localhost:8020/avatars
to generate an "uptoken".
The key of uploaded file is decided by autoKeyNaming
function
(sha1 checksum of uploaded file for example).
How it works
Cowherd is configured to generate upload token in callbackFetchKey
mode
(see documentation).
After file is uploaded to Qiniu, callbackUrl
is called. callbackBody
is collected and passed to route's
autoKeyNaming
function to decide the key of uploaded file (see strategy/sha1.js for details).
Download Token
Download token is required to access resource from Qiniu private bucket.
Add a get
object to route config object:
var utils = ; ;
Send a GET request to /photos?url=http%3A%2F%2F78re52.com1.z0.glb.clouddn.com%2Fresource%2Fflower.jpg
should
generates a download token for http://78re52.com1.z0.glb.clouddn.com/resource/flower.jpg
expires in 3600 seconds.
Advanced Usage
Authentication
Authentication is implemented in standard connect middleware style. Here's an implementation of JWT authentication:
// simple JWT authenticatorvar jwt = ;var { try var token = jwt; if Date > tokenexpires_at * 1000 return resstatus401; return ; catch e return resstatus401; }; ;
Handle duplicate keys
Upload files with same content will callback with a same qetag. When using naming function generating filename from etag (eg, etag/sha1 naming function) Qiniu would throw an error to the upload client. A workaround is to return a different key to Qiniu and use naming function only in key returned to upload client.
Override callback
function of policy object:
var request = ; policy: //... { var url = `/`; request; }
The data
object is a response object to Qiniu callback. data.key
is key of uploaded file and data.payload
will be sent to upload client.
To avoid error on uploading same file, a simple check of key existence is applied and the key is re-written to .qn-shim/{key}-{uuid}
(and
the file is in bucket now).
It's recommended to setup some task to clean-up these files periodically.
Disable automatic key naming
Use a noop
naming function:
;
License
(The MIT License)