-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
166 lines (140 loc) · 3.78 KB
/
main.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
package main
import (
"encoding/json"
"fmt"
"github.com/dgrijalva/jwt-go"
"log"
"net/http"
"time"
)
var users = map[string]string{
"user1": "password1",
"user2": "password2",
}
// Create the JWT key used to create the signature
var jwtKey = []byte("some_secret_key")
func main() {
http.HandleFunc("/signin",SignIn )
http.HandleFunc("/welcome", Welcome)
http.HandleFunc("/refresh", Refresh)
log.Fatal(http.ListenAndServe(":8000", nil))
}
// Create a struct to read the username and password from the request body
type Credentials struct {
Password string `json:"password"`
Username string `json:"username"`
}
// Create a struct that will be encoded to a JWT.
// We add jwt.StandardClaims as an embedded type, to provide fields like expiry time
type Claims struct {
Username string `json:"username"`
jwt.StandardClaims
}
//SignIn take the users credentials and log them in
func SignIn(w http.ResponseWriter, r *http.Request){
var cred Credentials
err:= json.NewDecoder(r.Body).Decode(&cred)
if err != nil{
w.WriteHeader(http.StatusBadRequest)
return
}
correctPass,ok := users[cred.Username]
if !ok || correctPass != cred.Password{
w.WriteHeader(http.StatusUnauthorized)
return
}
expirationTime := time.Now().Add(5 * time.Minute)
// Create the JWT claims, which includes the username and expiry time
claims := &Claims{
Username: cred.Username,
StandardClaims: jwt.StandardClaims{
// In JWT, the expiry time is expressed as unix milliseconds
ExpiresAt: expirationTime.Unix(),
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
tokenString, err := token.SignedString(jwtKey)
if err != nil{
w.WriteHeader(http.StatusInternalServerError)
return
}
http.SetCookie(w, &http.Cookie{
Name: "token",
Value: tokenString,
Expires: expirationTime,
})
}
func Welcome(w http.ResponseWriter, r *http.Request){
c, err := r.Cookie("token")
if err != nil {
w.WriteHeader(http.StatusUnauthorized)
return
}
tokenString := c.Value
claims := &Claims{}
token, err := jwt.ParseWithClaims(tokenString, claims,func(token *jwt.Token)(interface{}, error) {
return jwtKey,nil
})
if err != nil {
if err == jwt.ErrSignatureInvalid{
w.WriteHeader(http.StatusUnauthorized)
return
}
w.WriteHeader(http.StatusBadRequest)
return
}
if !token.Valid {
w.WriteHeader(http.StatusUnauthorized)
return
}
w.Write([]byte(fmt.Sprintf("Welcome %s", claims.Username)))
}
func Refresh(w http.ResponseWriter, r *http.Request){
// (BEGIN) The code uptil this point is the same as the first part of the `Welcome` route
c, err := r.Cookie("token")
if err != nil {
if err == http.ErrNoCookie {
w.WriteHeader(http.StatusUnauthorized)
return
}
w.WriteHeader(http.StatusBadRequest)
return
}
tknStr := c.Value
claims := &Claims{}
tkn, err := jwt.ParseWithClaims(tknStr, claims, func(token *jwt.Token) (interface{}, error) {
return jwtKey, nil
})
if !tkn.Valid {
w.WriteHeader(http.StatusUnauthorized)
return
}
if err != nil {
if err == jwt.ErrSignatureInvalid {
w.WriteHeader(http.StatusUnauthorized)
return
}
w.WriteHeader(http.StatusBadRequest)
return
}
//give 30 seconds before is expired
if time.Unix(claims.ExpiresAt, 0).Sub(time.Now()) > 30*time.Second {
w.WriteHeader(http.StatusBadRequest)
return
}
// Now, create a new token for the current use, with a renewed expiration time
expirationTime := time.Now().Add(5 * time.Minute)
claims.ExpiresAt = expirationTime.Unix()
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
tokenString, err := token.SignedString(jwtKey)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
// Set the new token as the users `token` cookie
http.SetCookie(w, &http.Cookie{
Name: "token",
Value: tokenString,
Expires: expirationTime,
})
}