-
Notifications
You must be signed in to change notification settings - Fork 61
/
mysql_repository.go
248 lines (205 loc) · 7.22 KB
/
mysql_repository.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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
// SPDX-License-Identifier: AGPL-3.0-only
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, version 3.
//
// This program 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>
package auth
import (
"context"
"errors"
"strconv"
"time"
"github.com/goccy/go-json"
"go.uber.org/zap"
"gorm.io/gorm"
"github.com/bangumi/server/internal/dal/dao"
"github.com/bangumi/server/internal/dal/query"
"github.com/bangumi/server/internal/domain"
"github.com/bangumi/server/internal/model"
"github.com/bangumi/server/internal/pkg/errgo"
"github.com/bangumi/server/internal/pkg/gstr"
"github.com/bangumi/server/internal/pkg/logger"
"github.com/bangumi/server/internal/pkg/logger/log"
"github.com/bangumi/server/internal/pkg/random"
)
func NewMysqlRepo(q *query.Query, log *zap.Logger) domain.AuthRepo {
return mysqlRepo{q: q, log: log.Named("auth.mysqlRepo")}
}
type mysqlRepo struct {
q *query.Query
log *zap.Logger
}
func (m mysqlRepo) GetByEmail(ctx context.Context, email string) (domain.AuthUserInfo, []byte, error) {
u, err := m.q.Member.WithContext(ctx).Where(m.q.Member.Email.Eq(email)).First()
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return domain.AuthUserInfo{}, nil, domain.ErrNotFound
}
m.log.Error("unexpected error happened", zap.Error(err))
return domain.AuthUserInfo{}, nil, errgo.Wrap(err, "gorm")
}
return domain.AuthUserInfo{
RegTime: time.Unix(u.Regdate, 0),
ID: u.ID,
GroupID: u.Groupid,
}, u.PasswordCrypt, nil
}
func (m mysqlRepo) GetByToken(ctx context.Context, token string) (domain.AuthUserInfo, error) {
access, err := m.q.AccessToken.WithContext(ctx).
Where(m.q.AccessToken.AccessToken.Eq(token), m.q.AccessToken.ExpiredAt.Gte(time.Now())).
First()
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return domain.AuthUserInfo{}, domain.ErrNotFound
}
m.log.Error("unexpected error happened", zap.Error(err))
return domain.AuthUserInfo{}, errgo.Wrap(err, "gorm")
}
id, err := gstr.ParseUint32(access.UserID)
if err != nil || id == 0 {
m.log.Error("wrong UserID in OAuth Access table", zap.String("user_id", access.UserID))
return domain.AuthUserInfo{}, errgo.Wrap(err, "parsing user id")
}
u, err := m.q.Member.WithContext(ctx).Where(m.q.Member.ID.Eq(model.UserID(id))).First()
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
m.log.Error("can't find user of access token",
zap.String("token", token), zap.String("uid", access.UserID))
return domain.AuthUserInfo{}, domain.ErrNotFound
}
m.log.Error("unexpected error happened", zap.Error(err))
return domain.AuthUserInfo{}, errgo.Wrap(err, "gorm")
}
return domain.AuthUserInfo{
RegTime: time.Unix(u.Regdate, 0),
ID: u.ID,
GroupID: u.Groupid,
}, nil
}
func (m mysqlRepo) GetPermission(ctx context.Context, groupID uint8) (domain.Permission, error) {
r, err := m.q.UserGroup.WithContext(ctx).Where(m.q.UserGroup.ID.Eq(groupID)).First()
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
m.log.Error("can't find permission for group", log.UserGroup(groupID))
return domain.Permission{}, nil
}
m.log.Error("unexpected error", zap.Error(err))
return domain.Permission{}, errgo.Wrap(err, "dal")
}
p, err := parsePhpSerializedPermission(r.Perm)
if err != nil {
m.log.Error("failed to decode php serialized content", zap.Error(err), log.UserGroup(groupID))
return domain.Permission{}, nil
}
return p, nil
}
const defaultAccessTokenLength = 40
func (m mysqlRepo) CreateAccessToken(
ctx context.Context, id model.UserID, name string, expiration time.Duration,
) (string, error) {
token := random.Base62String(defaultAccessTokenLength)
var now = time.Now()
var info = TokenInfo{
Name: name,
CreatedAt: now,
}
var expiredAt = now.Add(expiration)
if expiration < 0 {
expiredAt = time.Time{}
}
infoByte, err := json.Marshal(info)
if err != nil {
// marshal simple struct should never fail
m.log.Fatal("marshal simple struct should never fail",
zap.Error(err), zap.String("name", name), zap.Time("now", now))
panic("unexpected json encode error")
}
err = m.q.AccessToken.WithContext(ctx).Create(&dao.AccessToken{
Type: TokenTypeAccessToken,
AccessToken: token,
ClientID: "access token",
UserID: strconv.FormatUint(uint64(id), 10),
ExpiredAt: expiredAt,
Scope: nil,
Info: infoByte,
})
if err != nil {
m.log.Error("unexpected error happened", zap.Error(err))
return "", errgo.Wrap(err, "dal")
}
return token, nil
}
type TokenInfo struct {
CreatedAt time.Time `json:"created_at"`
Name string `json:"name"`
}
func (m mysqlRepo) ListAccessToken(ctx context.Context, userID model.UserID) ([]domain.AccessToken, error) {
records, err := m.q.AccessToken.WithContext(ctx).
Where(m.q.AccessToken.UserID.Eq(strconv.FormatUint(uint64(userID), 10)),
m.q.AccessToken.ExpiredAt.Gte(time.Now())).Find()
if err != nil {
m.log.Error("unexpected error happened", zap.Error(err))
return nil, errgo.Wrap(err, "dal")
}
var tokens = make([]domain.AccessToken, len(records))
for i, record := range records {
tokens[i] = convertAccessToken(record)
}
return tokens, errgo.Wrap(err, "dal")
}
const defaultOauthAccessExpiration = time.Hour * 168
func convertAccessToken(t *dao.AccessToken) domain.AccessToken {
var createdAt time.Time
var name = "oauth token"
switch t.Type {
case TokenTypeAccessToken:
if len(t.Info) > 0 {
var info TokenInfo
if err := json.UnmarshalNoEscape(t.Info, &info); err != nil {
logger.Fatal("unexpected error when trying to unmarshal json data",
zap.Error(err), zap.ByteString("raw", t.Info))
}
name = info.Name
createdAt = info.CreatedAt
} else {
name = "personal access token"
}
case TokenTypeOauthToken:
createdAt = t.ExpiredAt.Add(-defaultOauthAccessExpiration)
}
v, err := strconv.ParseUint(t.UserID, 10, 32)
if err != nil {
logger.Fatal("parsing UserID", zap.String("raw", t.UserID), zap.Error(err))
}
return domain.AccessToken{
ExpiredAt: t.ExpiredAt,
CreatedAt: createdAt,
Name: name,
UserID: model.UserID(v),
ClientID: t.ClientID,
ID: t.ID,
}
}
func (m mysqlRepo) DeleteAccessToken(ctx context.Context, id uint32) (bool, error) {
info, err := m.q.AccessToken.WithContext(ctx).Where(m.q.AccessToken.ID.Eq(id)).Delete()
return info.RowsAffected > 0, errgo.Wrap(err, "dal.Delete")
}
func (m mysqlRepo) GetTokenByID(ctx context.Context, id uint32) (domain.AccessToken, error) {
record, err := m.q.AccessToken.WithContext(ctx).Where(m.q.AccessToken.ID.Eq(id)).First()
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return domain.AccessToken{}, domain.ErrNotFound
}
m.log.Error("unexpected error happened", zap.Error(err))
return domain.AccessToken{}, errgo.Wrap(err, "dal")
}
return convertAccessToken(record), errgo.Wrap(err, "dal")
}