/
jwt_manager.go
164 lines (130 loc) · 3.54 KB
/
jwt_manager.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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
// This file is part of the Smart Home
// Program complex distribution https://github.com/e154/smart-home
// Copyright (C) 2016-2021, Filippov Alex
//
// This library is free software: you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Library General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library. If not, see
// <https://www.gnu.org/licenses/>.
package jwt_manager
import (
"context"
"encoding/hex"
"fmt"
"time"
"github.com/e154/smart-home/common/logger"
"github.com/pkg/errors"
"github.com/e154/smart-home/adaptors"
"github.com/e154/smart-home/common"
m "github.com/e154/smart-home/models"
"github.com/golang-jwt/jwt/v4"
"go.uber.org/fx"
)
var (
log = logger.MustGetLogger("jwt")
)
type jwtManager struct {
adaptors *adaptors.Adaptors
tokenDuration time.Duration
hmacKey []byte
}
// NewJwtManager ...
func NewJwtManager(lc fx.Lifecycle,
adaptors *adaptors.Adaptors) (mananger JwtManager) {
mananger = &jwtManager{adaptors: adaptors}
lc.Append(fx.Hook{
OnStart: func(ctx context.Context) error {
return mananger.Start()
},
})
return
}
// Start ...
func (j *jwtManager) Start() (err error) {
_, err = j.getSecretKey()
return
}
// Generate ...
func (j *jwtManager) Generate(user *m.User, opts ...*time.Time) (accessToken string, err error) {
var exp *int64
if len(opts) > 0 {
exp = common.Int64(opts[0].Unix())
}
now := time.Now()
if exp == nil {
exp = common.Int64(now.AddDate(0, 1, 0).Unix())
}
data := jwt.MapClaims{
"exp": exp,
"iat": now.Unix(),
"iss": "server",
"nbf": now.Unix(),
"i": user.Id,
"n": user.Nickname,
"r": user.RoleName,
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, data)
accessToken, err = token.SignedString(j.hmacKey)
return
}
// Verify ...
func (j *jwtManager) Verify(accessToken string) (claims *UserClaims, err error) {
var token *jwt.Token
token, err = jwt.Parse(accessToken, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, errors.Wrap(ErrUnexpectedSigningMethod, fmt.Sprintf("%v", token.Header["alg"]))
}
return j.hmacKey, nil
})
if err != nil {
return
}
if token == nil {
err = ErrInvalidAccessToken
return
}
if mapClaims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
if err = mapClaims.Valid(); err != nil {
return
}
claims = &UserClaims{}
err = common.Copy(claims, mapClaims, common.JsonEngine)
} else {
return nil, ErrInvalidTokenClaims
}
return
}
func (j *jwtManager) getSecretKey() (hmacKey []byte, err error) {
if j.hmacKey != nil && len(j.hmacKey) > 0 {
return j.hmacKey, nil
}
var variable m.Variable
if variable, err = j.adaptors.Variable.GetByName("hmacKey"); err != nil {
variable = m.Variable{
System: true,
Name: "hmacKey",
Value: common.ComputeHmac256(),
}
if err = j.adaptors.Variable.Add(variable); err != nil {
log.Error(err.Error())
}
}
if hmacKey, err = hex.DecodeString(variable.Value); err != nil {
return
}
j.hmacKey = hmacKey
return
}
// SetHmacKey ...
func (j *jwtManager) SetHmacKey(hmacKey []byte) {
j.hmacKey = hmacKey
}