-
Notifications
You must be signed in to change notification settings - Fork 0
/
token.go
92 lines (77 loc) · 2.05 KB
/
token.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
package token
import (
"encoding/json"
"errors"
"fmt"
"github.com/dgrijalva/jwt-go"
"log"
"net/http"
"strings"
"time"
)
type errOut struct {
Error string `json:error`
}
const mySigningKey = "Super_Dup3r_S3cret"
func GenerateToken(role string) (string, error) {
// Create the token
token := jwt.New(jwt.SigningMethodHS256)
// Set some claims
token.Claims = jwt.MapClaims{
"exp": time.Now().Add(time.Hour * time.Duration(1)).Unix(),
"iat": time.Now().Unix(),
"role": role,
}
// Sign and get the complete encoded token as a string
tokenString, err := token.SignedString([]byte(mySigningKey))
fmt.Println(tokenString)
return tokenString, err
}
func ParseToken(myToken string) (bool, error) {
token, err := jwt.Parse(myToken, func(token *jwt.Token) (interface{}, error) {
return []byte(mySigningKey), nil
})
//fmt.Println(token.Claims)
if err == nil && token.Valid {
return true, nil
} else {
return false, err
}
}
func ExtractToken(r *http.Request) (string, error) {
auth := r.Header.Get("Authorization")
split := strings.Split(auth, " ")
if split[0] != "Bearer" || split[1] == "" {
return "", errors.New("Malformed Auth Header")
} else {
return split[1], nil
}
}
func TokenHandler(w http.ResponseWriter, r *http.Request) bool {
authToken, err := ExtractToken(r)
if err != nil {
errout := new(errOut)
errout.Error = err.Error()
w.WriteHeader(http.StatusBadRequest)
if err := json.NewEncoder(w).Encode(errout); err != nil {
log.Panic("Error EncodingJson in TokenHandler", err)
}
return false
} else {
tokenStatus, err := ParseToken(authToken)
//fmt.Println("tokenStatus: ", tokenStatus, "err: ", err.Error())
if err != nil || tokenStatus == false {
errout := new(errOut)
errout.Error = err.Error()
w.WriteHeader(http.StatusForbidden)
if err := json.NewEncoder(w).Encode(errout); err != nil {
log.Panic("Error EncodingJson in TokenHandler", err)
}
log.Println("token status err: ", err)
return false
} else {
//w.Header().Set("Access-Control-Allow-Origin", "*")
return true
}
}
}