-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtoken.go
More file actions
101 lines (80 loc) · 1.8 KB
/
token.go
File metadata and controls
101 lines (80 loc) · 1.8 KB
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package main
import (
"encoding/json"
"fmt"
"os"
"github.com/dgrijalva/jwt-go"
"github.com/joho/godotenv"
)
// load from .env file
var err = godotenv.Load()
var secret = os.Getenv("secret")
type UserValid struct {
User string `json:"user"`
Valid bool `json:"valid"`
}
// Create a token
func CreateToken(username string) string {
type customClaims struct {
Username string `json:"username"`
jwt.StandardClaims
}
claims := customClaims{
Username: username,
StandardClaims: jwt.StandardClaims{
Issuer: "ottochat.com",
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
signedToken, err := token.SignedString([]byte("secureSecretText"))
if err != nil {
}
// fmt.Println(signedToken)
return signedToken
}
// Authenticate token
func AuthenticateToken(userJwt string) []byte {
type customClaims struct {
Username string `json:"username"`
jwt.StandardClaims
}
token, err := jwt.ParseWithClaims(
userJwt,
&customClaims{},
func(token *jwt.Token) (interface{}, error) {
return []byte("secureSecretText"), nil
},
)
fmt.Println(err)
claims, ok := token.Claims.(*customClaims)
if !ok {
println("fucked up token")
var users []UserValid
users = append(users, UserValid{
User: "none",
Valid: false,
})
data, err := json.Marshal(users)
if err != nil {
panic(err)
}
return data
}
// if claims.ExpiresAt < time.Now().UTC().Unix() {
// fmt.Println("jwt Expired", claims.ExpiresAt)
// }
username := claims.Username
// fmt.Println("username ", username)
// Return json {username: otto, Valid: true}
var users []UserValid
users = append(users, UserValid{
User: username,
Valid: true,
})
jsonUsers, err := json.Marshal(users)
if err != nil {
panic(err)
}
println("User is Valid returning {user:otto, Valid:true}")
return jsonUsers
}