-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
98 lines (82 loc) · 2.19 KB
/
auth.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
package server
import (
"context"
"net/http"
"time"
"github.com/go-chi/jwtauth"
"github.com/iwanhae/Jupynetes/pkg/common"
"github.com/lestrrat-go/jwx/jwt"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
)
var userKey = &struct {
key string
}{"user_id"}
//AuthorizeUser middleware for validating user token and embed to userinfo to context
func AuthorizeUser(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
token, claims, err := jwtauth.FromContext(r.Context())
if err != nil {
send(w, http.StatusUnauthorized, common.GetReason("fail to parse token"))
return
}
if token == nil || jwt.Validate(token) != nil {
send(w, http.StatusUnauthorized, common.GetReason("fail to validate token"))
return
}
user, ok := claims["user_id"].(string)
if !ok {
send(w, http.StatusUnauthorized, common.GetReason("fail to parse user_id from token"))
return
}
if user == "" {
send(w, http.StatusUnauthorized, common.GetReason("invalid user_id"))
return
}
ctx := r.Context()
ctx = context.WithValue(ctx, userKey, user)
log.Ctx(ctx).UpdateContext(func(c zerolog.Context) zerolog.Context {
return c.Str("user_id", user)
})
r = r.WithContext(ctx)
// Token is authenticated, pass it through
next.ServeHTTP(w, r)
})
}
//GetUser get user from context
func GetUser(ctx context.Context) string {
_, claims, err := jwtauth.FromContext(ctx)
if err != nil {
return ""
}
user, ok := claims["user_id"].(string)
if user == "" || !ok {
return ""
}
return user
}
//GenerateTokenCookie generate cookie which includes JWT
func GenerateTokenCookie(userID string) (*http.Cookie, error) {
token, err := GenerateToken(userID)
if err != nil {
return nil, err
}
cookie := &http.Cookie{
Name: "jwt",
Value: token,
HttpOnly: true,
}
return cookie, nil
}
//GenerateToken generate token for user auth
func GenerateToken(userID string) (string, error) {
claims := make(map[string]interface{})
claims["user_id"] = userID
jwtauth.SetExpiryIn(claims, time.Duration(time.Hour*1))
jwtauth.SetIssuedNow(claims)
_, token, err := tokenAuth.Encode(claims)
if err != nil {
return "", err
}
return token, nil
}