forked from QuantumNous/new-api
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtelegram.go
More file actions
340 lines (319 loc) · 11.1 KB
/
Copy pathtelegram.go
File metadata and controls
340 lines (319 loc) · 11.1 KB
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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
package controller
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"errors"
"net/http"
"net/url"
"sort"
"strconv"
"strings"
"time"
"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/middleware"
"github.com/QuantumNous/new-api/model"
"github.com/QuantumNous/new-api/service"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
)
const (
// The legacy Telegram widget has no nonce. Keep its signed assertion short-lived
// so captured callbacks cannot be reused indefinitely.
telegramAuthorizationMaxAge = 5 * time.Minute
telegramAuthorizationFutureSkew = 2 * time.Minute
telegramBindFlowTTL = 5 * time.Minute
telegramBindErrorDisabled = "TELEGRAM_BIND_DISABLED"
telegramBindErrorInvalidRequest = "TELEGRAM_BIND_INVALID_REQUEST"
telegramBindErrorFlowInvalid = "TELEGRAM_BIND_FLOW_INVALID"
telegramBindErrorSessionInvalid = "TELEGRAM_BIND_SESSION_INVALID"
telegramBindErrorAlreadyBound = "TELEGRAM_BIND_ALREADY_BOUND"
telegramBindErrorUserDeleted = "TELEGRAM_BIND_USER_DELETED"
telegramBindErrorUserDisabled = "TELEGRAM_BIND_USER_DISABLED"
telegramBindErrorInternal = "TELEGRAM_BIND_INTERNAL_ERROR"
)
var (
errTelegramAccountAlreadyBound = errors.New("telegram account is already bound")
errTelegramBindAssertionInvalid = errors.New("telegram bind assertion is invalid")
errTelegramBindUserDeleted = errors.New("telegram bind user was deleted")
errTelegramBindUserDisabled = errors.New("telegram bind user is disabled")
)
func TelegramBindStart(c *gin.Context) {
if !common.TelegramOAuthEnabled {
c.JSON(http.StatusOK, gin.H{
"message": "管理员未开启通过 Telegram 登录以及注册",
"success": false,
})
return
}
identity, ok := middleware.GetSessionAuthIdentity(c)
if !ok {
c.JSON(http.StatusUnauthorized, gin.H{"success": false, "message": "未登录"})
return
}
expiresAt := time.Now().Add(telegramBindFlowTTL)
flowToken, _, err := model.CreateAuthFlow(model.AuthFlowCreate{
Purpose: model.AuthFlowPurposeTelegramBind,
UserId: identity.UserID,
SessionId: identity.SessionID,
ExpiresAt: expiresAt,
})
if err != nil {
common.ApiError(c, err)
return
}
callbackURL := "/api/oauth/telegram/bind/" + flowToken
c.JSON(http.StatusOK, gin.H{
"success": true,
"message": "",
"data": gin.H{
"flow_token": flowToken,
"callback_url": callbackURL,
"expires_at": expiresAt.Unix(),
},
})
}
func TelegramBind(c *gin.Context) {
if !common.TelegramOAuthEnabled {
telegramBindFailure(c, telegramBindErrorDisabled)
return
}
params := c.Request.URL.Query()
telegramId, err := verifyTelegramAuthorization(params, common.TelegramBotToken, time.Now())
if err != nil {
common.SysLog("TelegramBind authorization failed: " + err.Error())
telegramBindFailure(c, telegramBindErrorInvalidRequest)
return
}
pendingFlow, err := model.GetAuthFlow(c.Param("flow_token"), model.AuthFlowMatch{
Purpose: model.AuthFlowPurposeTelegramBind,
})
if err != nil {
if !errors.Is(err, model.ErrAuthFlowInvalid) &&
!errors.Is(err, model.ErrAuthFlowExpired) &&
!errors.Is(err, model.ErrAuthFlowConsumed) {
common.SysError("TelegramBind flow lookup failed: " + err.Error())
telegramBindFailure(c, telegramBindErrorInternal)
return
}
telegramBindFailure(c, telegramBindErrorFlowInvalid)
return
}
if _, err := service.ValidateSessionReference(pendingFlow.UserId, pendingFlow.SessionId); err != nil {
if !errors.Is(err, service.ErrLoginSessionInvalid) &&
!errors.Is(err, service.ErrLoginSessionRevoked) &&
!errors.Is(err, model.ErrUserSessionInactive) &&
!errors.Is(err, gorm.ErrRecordNotFound) {
common.SysError("TelegramBind session validation failed: " + err.Error())
telegramBindFailure(c, telegramBindErrorInternal)
return
}
var user model.User
userErr := model.DB.First(&user, pendingFlow.UserId).Error
switch {
case errors.Is(userErr, gorm.ErrRecordNotFound):
telegramBindFailure(c, telegramBindErrorUserDeleted)
case userErr != nil:
common.SysError("TelegramBind user status lookup failed: " + userErr.Error())
telegramBindFailure(c, telegramBindErrorInternal)
case user.Status != common.UserStatusEnabled:
telegramBindFailure(c, telegramBindErrorUserDisabled)
default:
telegramBindFailure(c, telegramBindErrorSessionInvalid)
}
return
}
assertion, assertionExpiresAt, err := telegramAuthorizationClaim(params, time.Now())
if err != nil {
common.SysLog("TelegramBind authorization claim failed: " + err.Error())
telegramBindFailure(c, telegramBindErrorInvalidRequest)
return
}
_, err = model.ConsumeAuthFlowWithAction(c.Param("flow_token"), model.AuthFlowMatch{
Purpose: model.AuthFlowPurposeTelegramBind,
UserId: pendingFlow.UserId,
SessionId: pendingFlow.SessionId,
}, func(tx *gorm.DB, flow *model.AuthFlow) error {
if err := model.ClaimExternalAuthAssertionWithTx(tx, model.AuthFlowPurposeTelegramAssertion, assertion, assertionExpiresAt); err != nil {
if errors.Is(err, model.ErrAuthFlowInvalid) || errors.Is(err, model.ErrAuthFlowConsumed) {
return errors.Join(errTelegramBindAssertionInvalid, err)
}
return err
}
var user model.User
if err := tx.First(&user, flow.UserId).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return errTelegramBindUserDeleted
}
return err
}
if user.Status != common.UserStatusEnabled {
return errTelegramBindUserDisabled
}
var session model.UserSession
if err := tx.Where("sid = ? AND user_id = ?", flow.SessionId, flow.UserId).First(&session).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return service.ErrLoginSessionRevoked
}
return err
}
if session.Status != model.UserSessionStatusActive || session.RevokedAt != 0 || session.ExpiresAt <= time.Now().Unix() {
return service.ErrLoginSessionRevoked
}
if session.UserAuthVersion != user.AuthVersion {
return service.ErrLoginSessionRevoked
}
if user.TelegramId != "" {
return errTelegramAccountAlreadyBound
}
if err := model.ClaimExternalIdentityWithTx(
tx,
model.ExternalIdentityProviderTelegram,
telegramId,
user.Id,
); err != nil {
if errors.Is(err, model.ErrExternalIdentityAlreadyClaimed) {
return errTelegramAccountAlreadyBound
}
return err
}
result := tx.Model(&model.User{}).
Where("id = ? AND status = ? AND auth_version = ? AND telegram_id = ?", user.Id, common.UserStatusEnabled, user.AuthVersion, "").
Update("telegram_id", telegramId)
if result.Error != nil {
return result.Error
}
if result.RowsAffected != 1 {
return errTelegramAccountAlreadyBound
}
return nil
})
if err != nil {
switch {
case errors.Is(err, errTelegramBindAssertionInvalid):
telegramBindFailure(c, telegramBindErrorInvalidRequest)
case errors.Is(err, errTelegramAccountAlreadyBound):
telegramBindFailure(c, telegramBindErrorAlreadyBound)
case errors.Is(err, errTelegramBindUserDeleted):
telegramBindFailure(c, telegramBindErrorUserDeleted)
case errors.Is(err, errTelegramBindUserDisabled):
telegramBindFailure(c, telegramBindErrorUserDisabled)
case errors.Is(err, service.ErrLoginSessionRevoked):
telegramBindFailure(c, telegramBindErrorSessionInvalid)
case errors.Is(err, model.ErrAuthFlowInvalid), errors.Is(err, model.ErrAuthFlowExpired), errors.Is(err, model.ErrAuthFlowConsumed):
telegramBindFailure(c, telegramBindErrorFlowInvalid)
default:
common.SysError("TelegramBind failed: " + err.Error())
telegramBindFailure(c, telegramBindErrorInternal)
}
return
}
callback := "/oauth/telegram?telegram_bind=success&flow_token=" + url.QueryEscape(c.Param("flow_token"))
c.Redirect(http.StatusFound, callback)
}
func telegramBindFailure(c *gin.Context, errorCode string) {
query := url.Values{
"telegram_bind": {"error"},
"flow_token": {c.Param("flow_token")},
"error_code": {errorCode},
}
c.Redirect(http.StatusFound, "/oauth/telegram?"+query.Encode())
}
func TelegramLogin(c *gin.Context) {
if !common.TelegramOAuthEnabled {
c.JSON(200, gin.H{
"message": "管理员未开启通过 Telegram 登录以及注册",
"success": false,
})
return
}
params := c.Request.URL.Query()
telegramId, err := verifyTelegramAuthorization(params, common.TelegramBotToken, time.Now())
if err != nil {
common.SysLog("TelegramLogin authorization failed: " + err.Error())
c.JSON(200, gin.H{
"message": "无效的请求",
"success": false,
})
return
}
user := model.User{TelegramId: telegramId}
if err := user.FillUserByTelegramId(); err != nil {
c.JSON(200, gin.H{
"message": err.Error(),
"success": false,
})
return
}
if err := claimTelegramAuthorization(params, time.Now()); err != nil {
common.SysLog("TelegramLogin assertion replay rejected: " + err.Error())
c.JSON(http.StatusForbidden, gin.H{
"message": "该登录凭据已被使用",
"success": false,
})
return
}
setupLogin(&user, c)
}
func claimTelegramAuthorization(params url.Values, now time.Time) error {
assertion, expiresAt, err := telegramAuthorizationClaim(params, now)
if err != nil {
return err
}
return model.ClaimExternalAuthAssertion(model.AuthFlowPurposeTelegramAssertion, assertion, expiresAt)
}
func telegramAuthorizationClaim(params url.Values, now time.Time) (string, time.Time, error) {
authDate, err := strconv.ParseInt(params.Get("auth_date"), 10, 64)
if err != nil {
return "", time.Time{}, errors.New("telegram authorization date is invalid")
}
hashBytes, err := hex.DecodeString(params.Get("hash"))
if err != nil {
return "", time.Time{}, errors.New("telegram authorization signature is invalid")
}
expiresAt := time.Unix(authDate, 0).Add(telegramAuthorizationMaxAge)
if !expiresAt.After(now) {
return "", time.Time{}, errors.New("telegram authorization has expired")
}
return hex.EncodeToString(hashBytes), expiresAt, nil
}
func verifyTelegramAuthorization(params url.Values, token string, now time.Time) (string, error) {
if token == "" {
return "", errors.New("telegram bot token is empty")
}
for _, values := range params {
if len(values) != 1 {
return "", errors.New("telegram authorization contains duplicate parameters")
}
}
telegramID := params.Get("id")
hash := params.Get("hash")
authDateText := params.Get("auth_date")
if telegramID == "" || hash == "" || authDateText == "" {
return "", errors.New("telegram authorization is incomplete")
}
authDate, err := strconv.ParseInt(authDateText, 10, 64)
if err != nil {
return "", errors.New("telegram authorization date is invalid")
}
if authDate < now.Add(-telegramAuthorizationMaxAge).Unix() ||
authDate > now.Add(telegramAuthorizationFutureSkew).Unix() {
return "", errors.New("telegram authorization has expired")
}
strs := make([]string, 0, len(params)-1)
for k, v := range params {
if k == "hash" {
continue
}
strs = append(strs, k+"="+v[0])
}
sort.Strings(strs)
secret := sha256.Sum256([]byte(token))
mac := hmac.New(sha256.New, secret[:])
_, _ = mac.Write([]byte(strings.Join(strs, "\n")))
providedHash, err := hex.DecodeString(hash)
if err != nil || !hmac.Equal(providedHash, mac.Sum(nil)) {
return "", errors.New("telegram authorization signature is invalid")
}
return telegramID, nil
}