/
paseto.go
76 lines (64 loc) · 2.03 KB
/
paseto.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package bimo
import (
"encoding/json"
"fmt"
"time"
"aidanwoods.dev/go-paseto"
)
func GenerateKey() (privatekey, publickey string) {
secretKey := paseto.NewV4AsymmetricSecretKey() // don't share this!!!
privatekey = secretKey.ExportHex() // DO share this one
publickey = secretKey.Public().ExportHex()
return privatekey, publickey
}
func Encode(name, username, role, 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("name", name)
token.SetString("username", username)
token.SetString("role", role)
key, err := paseto.NewV4AsymmetricSecretKeyFromHex(privatekey)
return token.V4Sign(key, nil), err
}
func Decode(publickey, tokenstr string) (payload Payload, err error) {
var token *paseto.Token
var pubKey paseto.V4AsymmetricPublicKey
// Pastikan bahwa kunci publik dalam format heksadesimal yang benar
pubKey, err = paseto.NewV4AsymmetricPublicKeyFromHex(publickey)
if err != nil {
return payload, fmt.Errorf("failed to create public key: %s", err)
}
parser := paseto.NewParser()
// Pastikan bahwa token memiliki format yang benar
token, err = parser.ParseV4Public(pubKey, tokenstr, nil)
if err != nil {
return payload, fmt.Errorf("failed to parse token: %s", err)
} else {
// Handle token claims
json.Unmarshal(token.ClaimsJSON(), &payload)
}
return payload, nil
}
func DecodeGetName(publickey string, tokenstring string) string {
payload, err := Decode(publickey, tokenstring)
if err != nil {
fmt.Println("Decode DecodeGetId : ", err)
}
return payload.Name
}
func DecodeGetUsername(publickey string, tokenstring string) string {
payload, err := Decode(publickey, tokenstring)
if err != nil {
fmt.Println("Decode DecodeGetId : ", err)
}
return payload.Username
}
func DecodeGetRole(publickey string, tokenstring string) string {
payload, err := Decode(publickey, tokenstring)
if err != nil {
fmt.Println("Decode DecodeGetId : ", err)
}
return payload.Role
}