-
Notifications
You must be signed in to change notification settings - Fork 0
/
jwtauth.go
106 lines (88 loc) · 2.11 KB
/
jwtauth.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
package jwtauth
import (
"context"
"fmt"
"log"
"net/http"
"os"
"strings"
"github.com/dgrijalva/jwt-go"
"github.com/joho/godotenv"
"github.com/mitchellh/mapstructure"
)
//Auth .
type Auth struct {
Token string `json:"token"`
Refresh string `json:"refresh"`
Type string `json:"type"`
}
//Access .
type Access struct {
ID int64 `json:"id"`
Login string `json:"login"`
Password string `json:"password"`
Email string `json:"email"`
}
//TokenAuth .
type TokenAuth struct {
Access Access `json:"access,omitempty"`
Exp int64 `json:"exp,omitempty"`
jwt.StandardClaims
}
func ExtractToken(bearToken string) string {
strArr := strings.Split(bearToken, " ")
if len(strArr) == 2 {
return strArr[1]
}
return ""
}
//CreateToken .
func CreateToken(tokenAuth TokenAuth, hash string) Auth {
err := godotenv.Load()
if err != nil {
log.Fatal("Error loading .env file")
}
token := jwt.NewWithClaims(jwt.GetSigningMethod("HS256"), &tokenAuth)
tokenstring, err := token.SignedString([]byte(os.Getenv("HASH_CRYPT")))
if err != nil {
log.Fatalln(err)
}
return Auth{
Token: tokenstring,
Refresh: hash,
Type: "refreshToken",
}
}
//VerifyToken .
func VerifyToken(bearToken string) (bool, Access) {
err := godotenv.Load()
if err != nil {
log.Fatal("Error loading .env file")
}
access := Access{}
token, err := jwt.Parse(ExtractToken(bearToken), func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
}
return []byte(os.Getenv("HASH_CRYPT")), nil //crie em uma variavel de ambiente
})
if err != nil {
return false, access
}
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
mapstructure.Decode(claims["access"], &access)
} else {
return false, access
}
return true, access
}
func SetContextData(r *http.Request, d *Access) (ro *http.Request) {
ctx := r.Context()
ctx = context.WithValue(ctx, 1, d)
ro = r.WithContext(ctx)
return
}
func GetContextData(r *http.Request) (d Access) {
d = *r.Context().Value(1).(*Access)
return
}