Last active
February 7, 2022 14:21
-
-
Save bitkidd/1dccf4ee9b826a2e8ac0c81d171d38d8 to your computer and use it in GitHub Desktop.
KeyCDN Secure Token
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const domain = 'domain' | |
const secret = 'supersecret' | |
const expire = Math.round(Date.now() / 1000) + 120 | |
const links: { original?: string } = {} | |
const path = `/${this.filetype}/${this.uid}.${this.fileext}` | |
const generateToken = ({ path, query = '' }: { path: string; query?: string }): string => { | |
// generate md5 token | |
const md5String = crypto | |
.createHash('md5') | |
.update(path + query + secret + expire) | |
.digest() | |
// encode and format md5 token | |
const token = md5String | |
.toString('base64') | |
.replace(/\+/g, '-') | |
.replace(/\//g, '_') | |
.replace(/\=/g, '') | |
return token | |
} | |
const [width, height] = '600x600'.split('x') | |
let query = width && height ? 'crop=smart' : '' | |
query += width && `&width=${width}` | |
query += height && `&height=${height}` | |
const token = generateToken({ path, query }) | |
const link = `https://${domain}${path}?${query}&token=${token}&expire=${expire}` | |
// Data generated | |
// secure_string: /image/123456.jpgcrop=smart&width=600&height=600supersecret1644242946 | |
// secure_params: |______path_____||____________query____________||__secret_||_expire_| | |
// token: 6Xbv48A73BjLT3KKyzobww | |
// link: https://domain/image/123456.jpg?crop=smart&width=600&height=600&token=6Xbv48A73BjLT3KKyzobww&expire=1644242946 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment