forked from G-Node/gin-repo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jwt.go
85 lines (67 loc) · 1.32 KB
/
jwt.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
77
78
79
80
81
82
83
84
85
package auth
import (
"crypto/rand"
"errors"
"fmt"
"io/ioutil"
"os"
"os/user"
"path/filepath"
"time"
"github.com/dgrijalva/jwt-go"
)
var (
ErrNoAuth = errors.New("no authentication provided")
)
type Claims struct {
*jwt.StandardClaims
TokenType string
}
func ReadSharedSecret() ([]byte, error) {
path := "."
_, err := os.Stat("gin.secret")
if err != nil {
path = ""
}
if path == "" {
u, err := user.Current()
if err == nil {
path = u.HomeDir
}
}
if path == "" {
path = os.Getenv("HOME")
}
filename := filepath.Join(path, "gin.secret")
secret, err := ioutil.ReadFile(filename)
return secret, err
}
func CreateSharedSecret() ([]byte, error) {
key := make([]byte, 23)
_, err := rand.Read(key)
err = ioutil.WriteFile("gin.secret", key, 0600)
if err != nil {
return key, fmt.Errorf("could not write to shared secret: %v", err)
}
return key, nil
}
func MakeServiceToken(key []byte) (string, error) {
token := jwt.New(jwt.SigningMethodHS256)
host, err := os.Hostname()
if err != nil {
host = "localhost"
}
token.Claims = &Claims{
&jwt.StandardClaims{
Issuer: "gin-repo@" + host,
IssuedAt: time.Now().Unix(),
ExpiresAt: time.Now().Add(time.Minute * 120).Unix(),
},
"service",
}
str, err := token.SignedString(key)
if err != nil {
return "", err
}
return str, nil
}