/
pasetoencoder.go
60 lines (54 loc) · 1.89 KB
/
pasetoencoder.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package PasetoprojectBackend
import (
"aidanwoods.dev/go-paseto"
"encoding/json"
"fmt"
"time"
)
func EncodeWithRole(role, username, privatekey string) (string, error) {
token := paseto.NewToken()
token.SetIssuedAt(time.Now())
token.SetNotBefore(time.Now())
token.SetExpiration(time.Now().Add(2 * time.Hour))
token.SetString("user", username)
token.SetString("role", role)
key, err := paseto.NewV4AsymmetricSecretKeyFromHex(privatekey)
return token.V4Sign(key, nil), err
}
func Decoder(publickey, tokenstr string) (payload Payload, err error) {
var token *paseto.Token
var pubKey paseto.V4AsymmetricPublicKey
pubKey, err = paseto.NewV4AsymmetricPublicKeyFromHex(publickey) // this wil fail if given key in an invalid format
if err != nil {
fmt.Println("Decode NewV4AsymmetricPublicKeyFromHex : ", err)
}
parser := paseto.NewParser() // only used because this example token has expired, use NewParser() (which checks expiry by default)
token, err = parser.ParseV4Public(pubKey, tokenstr, nil) // this will fail if parsing failes, cryptographic checks fail, or validation rules fail
if err != nil {
fmt.Println("Decode ParseV4Public : ", err)
} else {
json.Unmarshal(token.ClaimsJSON(), &payload)
}
return payload, err
}
func DecodeGetUser(PublicKey, tokenStr string) (pay string, err error) {
key, err := Decoder(PublicKey, tokenStr)
if err != nil {
fmt.Println("Cannot decode the token", err.Error())
}
return key.User, nil
}
func DecodeGetRole(PublicKey, tokenStr string) (pay string, err error) {
key, err := Decoder(PublicKey, tokenStr)
if err != nil {
fmt.Println("Cannot decode the token", err.Error())
}
return key.Role, nil
}
func DecodeGetRoleandUser(PublicKey, tokenStr string) (pay string, use string) {
key, err := Decoder(PublicKey, tokenStr)
if err != nil {
fmt.Println("Cannot decode the token", err.Error())
}
return key.Role, key.User
}