-
Notifications
You must be signed in to change notification settings - Fork 0
/
handleRefresh.go
83 lines (73 loc) · 2.4 KB
/
handleRefresh.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
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"strings"
"time"
"github.com/dgrijalva/jwt-go"
)
func handleRefresh(w http.ResponseWriter, r *http.Request) {
auth := r.Header.Get("Authorization")
if auth == "" {
// Bad Request
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(400)
json.NewEncoder(w).Encode(ErrorMessage{Code: "400", Message: http.StatusText(400)})
return
}
tokenString := strings.TrimPrefix(auth, "Bearer ")
claims := &Claims{}
tkn, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
return jwtKey, nil
})
if err != nil {
log.Println("INCORRECT TOKEN STRING")
// Bad Request
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(401)
json.NewEncoder(w).Encode(ErrorMessage{Code: "401", Message: http.StatusText(401)})
return
}
if !tkn.Valid {
// Unauthorized
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(401)
json.NewEncoder(w).Encode(ErrorMessage{Code: "401", Message: http.StatusText(401)})
return
}
if err != nil {
if err == jwt.ErrSignatureInvalid {
// Unauthorized
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(400)
json.NewEncoder(w).Encode(ErrorMessage{Code: "400", Message: http.StatusText(400)})
return
}
// Bad Request
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(401)
json.NewEncoder(w).Encode(ErrorMessage{Code: "401", Message: http.StatusText(401)})
return
}
// Now, create a new token for the current use, with a renewed expiration time
expiresAtTime := time.Now().Add(time.Duration(cfg.Jwt.ExpirationTime) * time.Minute)
claims.ExpiresAt = expiresAtTime.Unix()
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
newTokenString, err := token.SignedString(jwtKey)
if err != nil {
// Internal Server Error
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(500)
json.NewEncoder(w).Encode(ErrorMessage{Code: "500", Message: http.StatusText(500)})
return
}
response := map[string]string{
"token": newTokenString,
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
responseM, _ := json.Marshal(response)
fmt.Fprint(w, string(responseM))
log.Printf("REFRESH: (%s) Token expires at: %s\n", claims.Username, time.Unix(claims.ExpiresAt, 0))
}