/
jwt.go
130 lines (109 loc) · 2.84 KB
/
jwt.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
package model
import (
"context"
"errors"
// "go-graphql-jwt/graph/model"
// "go-graphql-jwt/graph/utils"
"net"
"net/http"
"strings"
"github.com/dgrijalva/jwt-go"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
// UserAuth - user auth middleware structure
type UserAuth struct {
UserID string
Roles []string
IPAddress string
Token string
}
var userCtxKey = &contextKey{name: "user"}
type contextKey struct {
name string
}
// UserClaims for jwt
type UserClaims struct {
UserID string `json:"id"`
jwt.StandardClaims
}
// JwtMiddleware middleware for http server
func JwtMiddleware() func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
token := TokenFromHTTPRequestgo(r)
userID := UserIDFromHTTPRequestgo(token)
ip, _, _ := net.SplitHostPort(r.RemoteAddr)
userAuth := UserAuth{
UserID: userID,
IPAddress: ip,
}
// put it in context
ctx := context.WithValue(r.Context(), userCtxKey, &userAuth)
r = r.WithContext(ctx)
next.ServeHTTP(w, r)
})
}
}
// TokenFromHTTPRequestgo - get jwt token from request
func TokenFromHTTPRequestgo(r *http.Request) string {
reqToken := r.Header.Get("Authorization")
var tokenString string
splitToken := strings.Split(reqToken, "Bearer ")
if len(splitToken) > 1 {
tokenString = splitToken[1]
}
return tokenString
}
// UserIDFromHTTPRequestgo - get user id from request
func UserIDFromHTTPRequestgo(tokenString string) string {
token, err := DecodeJwt(tokenString)
if err != nil {
return "err"
}
if claims, ok := token.Claims.(*UserClaims); ok && token.Valid {
if claims == nil {
return "err"
}
return claims.UserID
}
return "Err"
}
// GetAuthFromContext - Gets context
func GetAuthFromContext(ctx context.Context) *UserAuth {
raw := ctx.Value(userCtxKey)
if raw == nil {
return nil
}
return raw.(*UserAuth)
}
var issuer = []byte("github/thealmarques")
// DecodeJwt decode jwt
func DecodeJwt(token string) (*jwt.Token, error) {
return jwt.ParseWithClaims(token, &UserClaims{}, func(token *jwt.Token) (interface{}, error) {
return issuer, nil
})
}
// GenerateJwt create jwt
func GenerateJwt(userID string, expiredAt int64) string {
claims := UserClaims{
StandardClaims: jwt.StandardClaims{
ExpiresAt: expiredAt,
Issuer: string(issuer),
},
UserID: userID,
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
signedToken, _ := token.SignedString(issuer)
return signedToken
}
func GetAuthStat(coredb *gorm.DB, ctx context.Context, errorMessage string) (bool, User, error) {
userAuth := GetAuthFromContext(ctx)
if userAuth.UserID == "err" {
return false, User{}, errors.New(errorMessage)
}
user := User{}
// preload everything with this
coredb.Preload(clause.Associations).First(&user, "id = ?", userAuth.UserID)
return true, user, nil
}