Skip to content

Commit

Permalink
Merge pull request #1 from javiertlopez/feature-refactor-fastly-token
Browse files Browse the repository at this point in the history
Refactor Fastly token
  • Loading branch information
houseofmackee authored Dec 23, 2020
2 parents 0ca341a + a3b8b18 commit 46c0daa
Show file tree
Hide file tree
Showing 3 changed files with 91 additions and 22 deletions.
22 changes: 0 additions & 22 deletions fastlyExp.go

This file was deleted.

39 changes: 39 additions & 0 deletions fastly_exp.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package main

import (
"encoding/base64"
"encoding/binary"
"encoding/hex"
"fmt"
"os"
"strings"
"time"
)

func main() {
if len(os.Args) > 1 {
token, err := decode(os.Args[1])
if err != nil {
fmt.Printf("Error: %s", err.Error())
}
fmt.Printf("Token expires: %s", token)
} else {
fmt.Println("Missing token.")
}
}

// decode a Fastly Token. Returns expiration or error.
func decode(token string) (string, error) {
decoded, err := base64.StdEncoding.DecodeString(strings.Replace(token, "%3D", "=", -1))
if err != nil {
return "", err
}

decToken := string(decoded)
byteTime, err := hex.DecodeString(decToken[:strings.Index(decToken, "_")])
if err != nil {
return "", err
}

return time.Unix(int64(binary.BigEndian.Uint32(byteTime)), 0).UTC().String(), nil
}
52 changes: 52 additions & 0 deletions fastly_exp_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package main

import "testing"

func Test_decode(t *testing.T) {
type args struct {
token string
}
tests := []struct {
name string
args args
want string
wantErr bool
}{
{
"success",
args{
"NWZmY2U4MWFfY2ViMDViZWRkOWYwZTRkY2NkYTIxOWE3NjRhYmNlMjczZWViMWNmYWQ2ZTc4OTQzYmViNTE0YWMwZjBlMjFjNQ%3D%3D",
},
"2021-01-12 00:06:50 +0000 UTC",
false,
},
{
"error (not base64)",
args{
"NWZmY2U4MWFfY2ViM",
},
"",
true,
},
{
"error (not hex)",
args{
"aGVsbG9fdGhlcmU=",
},
"",
true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := decode(tt.args.token)
if (err != nil) != tt.wantErr {
t.Errorf("decode() error = %v, wantErr %v", err, tt.wantErr)
return
}
if got != tt.want {
t.Errorf("decode() = %v, want %v", got, tt.want)
}
})
}
}

0 comments on commit 46c0daa

Please sign in to comment.