UNPKG

yinxing

Version:
120 lines (97 loc) 3.05 kB
const moment=require('moment') const R=require("ramda") const {hmac}=require("utility") const superagent=require('superagent') const SERVER="https://service-hc5rz9qa-1252957949.gz.apigw.tencentcs.com/release/sec" const SECRETID = "AKIDEOJ44ea4y6afWpIrIzdcuYV52T81dHvqVKsD" const SECRETKEY = "k66d99m4gs9f05x6vqgp2yrkrvpdemhhpnhj68FX" const SOURCE="ccc" const EXP=3600 //'Sat, 15 Feb 2020 12:33:40 GMT' const gmt_now=()=>new Date().toGMTString() const now=()=>moment().unix() const sha1=(a,b)=>hmac('sha1',a,b,'base64') /* { Source: 'ccc', Date: 'Sat, 15 Feb 2020 13:07:19 GMT', Authorization: 'hmac id="AKIDEOJ44ea4y6afWpIrIzdcuYV52T81dHvqVKsD", algorithm="hmac-sha1", headers="date source", signature="aSqvktrLNYBwKDeMS43788rJ4rU="' } */ const getSimpleSign =(dateTime=gmt_now(),source=SOURCE, SecretId=SECRETID, SecretKey=SECRETKEY)=>{ var auth = "hmac id=\"" + SecretId + "\", algorithm=\"hmac-sha1\", headers=\"date source\", signature=\""; var signStr = "date: " + dateTime + "\n" + "source: " + source; const sign = auth + sha1(SecretKey,signStr) + "\"" return { "Source":source, "Date":dateTime, "Authorization":sign } } const getSimpleSign1 =(dateTime=gmt_now(),source=SOURCE, SecretId=SECRETID, SecretKey=SECRETKEY)=>{ var auth = "hmac id=\"" + SecretId + "\", algorithm=\"hmac-sha1\", headers=\"x-date source\", signature=\""; var signStr = "x-date: " + dateTime + "\n" + "source: " + source; const sign = auth + sha1(SecretKey,signStr) + "\"" return { "Source":source, "X-Date":dateTime, "Authorization":sign } } const check_source=(s="")=>s == SOURCE const check_time=(t="")=>{ let t1=now() let t0=moment(t.trim()).unix() let d=t1-t0 return (d>0) && (d < EXP) } const check_auth=(source,dateTime,au="")=>{ let o=R.pipe(R.split(','),R.map(R.split('"')),R.map(R.map(R.invoker(0,'trim'))),R.map(([k,v])=>[k.replace('=',''),v]),R.fromPairs)(au) let a= o['hmac id'] == SECRETID let {algorithm,headers,signature}=o var signStr = "date: " + dateTime + "\n" + "source: " + source; let s=sha1(SECRETKEY,signStr) //console.log(s,signature) let b = s == signature return a && b } const verify=(x={})=>{ let a=check_source(x.Source) let b=check_time(x.Date) let c=check_auth(x.Source,x.Date,x.Authorization) //console.log(a,b,c) if (a && b && c) { return true }else{ return false } } const get=(u=SERVER,d={})=>superagent .get(u) .set(getSimpleSign1()) .query(d) .type('json') const test=()=>{ assert.equal(sha1('x','y'),'LBxi4Eilgk37PtaY7475b1GFo2k=') let t='Sat, 15 Feb 2020 13:07:19 GMT' let h=getSimpleSign(t) let r=verify(h) console.log(r) } const test1=async ()=>{ let t='Sat, 15 Feb 2020 13:07:19 GMT' let h=getSimpleSign1(t) console.log(h) console.log(getSimpleSign1()) let r=await get() console.log(r.body) } //test() module.exports={ getSimpleSign, getSimpleSign1, verify, get, test, test1, }