-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrest_any_webauthn.go
393 lines (327 loc) · 10.4 KB
/
rest_any_webauthn.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
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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
package main
import (
"encoding/base64"
"io"
"net/http"
"github.com/duo-labs/webauthn/protocol"
"github.com/duo-labs/webauthn/webauthn"
"github.com/gin-gonic/gin"
"github.com/go-redis/redis/v8"
ua "github.com/mileusna/useragent"
"knowlgraph.com/ent"
"knowlgraph.com/ent/terminal"
)
// WebAuthnID is user ID according to the Relying Party
func (u *Terminal) WebAuthnID() []byte {
return ([]byte)(u.Code)
}
// WebAuthnName is user Name according to the Relying Party
func (u *Terminal) WebAuthnName() string {
return u.Name
}
// WebAuthnDisplayName is display Name of the user
func (u *Terminal) WebAuthnDisplayName() string {
return u.Name
}
// WebAuthnIcon is user's icon url
func (u *Terminal) WebAuthnIcon() string {
return ""
}
// WebAuthnCredentials is credentials owned by the user
func (u *Terminal) WebAuthnCredentials() []webauthn.Credential {
credID, err := base64.StdEncoding.DecodeString(u.Cred.CredID)
if err != nil {
return nil
}
publicKey, err := base64.StdEncoding.DecodeString(u.Cred.PublicKey)
if err != nil {
return nil
}
cred := webauthn.Credential{
ID: credID,
PublicKey: publicKey,
AttestationType: u.Cred.AttestationType,
}
return []webauthn.Credential{cred}
}
var (
web *webauthn.WebAuthn
)
func initWebAuthn() {
var err error
web, err = webauthn.New(&webauthn.Config{
RPDisplayName: "Knowledge graph", // Display Name for your site
RPID: config.Rpid, // Generally the FQDN for your site
RPOrigin: config.Rpog,
})
panicIfErrNotNil(err)
}
func getUserAuthInfo(terminalID int, terminalName string, token string, analyticsCode string, onlyOnce bool) gin.H {
return gin.H{"id": terminalID, "name": terminalName, "token": token, "analyticsCode": analyticsCode, "onlyOnce": onlyOnce}
}
func verifyChallenge(c *Context) (string, *Terminal, error) {
var form struct {
State string `form:"state" binding:"required"`
Challenge string `form:"challenge" binding:"required"`
}
if err := c.ShouldBindQuery(&form); err != nil {
return "", nil, &RestfulAPIError{Status: http.StatusBadRequest, Content: err.Error()}
}
var t Terminal
if err := GetV4Redis(RChallenge(form.Challenge), &t); err != nil {
return "", &t, &RestfulAPIError{Status: http.StatusBadRequest, Content: err.Error()}
}
if form.State != t.ClientState {
return "", nil, &RestfulAPIError{Status: http.StatusBadRequest, Content: "Bad state"}
}
if 0 != t.UserID && !t.authorized() {
// 如果已绑定认证账号,但认证账号未授权,则返回“没有权限”
return "", nil, &RestfulAPIError{Status: http.StatusUnauthorized, Content: "Permission denied"}
}
return form.Challenge, &t, nil
}
func beginRegistration(c *Context) error {
challenge, t, err := verifyChallenge(c)
if err != nil {
return c.StatusError(err)
}
_ua := ua.Parse(c.GetHeader("User-Agent"))
userVerification := protocol.VerificationPreferred
if _ua.IsIOS() {
userVerification = protocol.VerificationDiscouraged
}
t.Code = New16bitID()
options, sessionData, err := web.BeginRegistration(t, func(pkcco *protocol.PublicKeyCredentialCreationOptions) {
pkcco.AuthenticatorSelection = protocol.AuthenticatorSelection{
AuthenticatorAttachment: protocol.Platform,
UserVerification: userVerification,
}
})
if err != nil {
return c.InternalServerError(err.Error())
}
if err = SetWebAuthnSession(challenge, sessionData); err != nil {
return c.InternalServerError(err.Error())
}
if err = SetV2Redis(RChallenge(challenge), &t, ExpireTimeChallengeConfirm); err != nil {
return c.InternalServerError(err.Error())
}
return c.Ok(&options)
}
func finishRegistration(c *Context) error {
challenge, t, err := verifyChallenge(c)
if err != nil {
return c.StatusError(err)
}
if t.OnlyOnce {
return c.MethodNotAllowed("Unauthorized access to the interface.")
}
// Get the session data stored from the function above
// using gorilla/sessions it could look like this
sessionData, err := GetWebAuthnSession(challenge)
if err != nil {
return c.BadRequest(err.Error())
}
parsedResponse, err := protocol.ParseCredentialCreationResponseBody(c.Request.Body)
if err != nil {
return c.Unauthorized(err.Error())
}
credential, err := web.CreateCredential(t, sessionData, parsedResponse)
// Handle validation or input errors
// If creation was successful, store the credential object
if err != nil {
return c.Unauthorized(err.Error())
}
id := 0
token := New64BitID()
d := ExpireTimeToken
terminalMap := make(map[int]string)
err = WithTx(ctx, client, func(tx *ent.Tx) error {
if 0 == t.UserID {
user, err1 := tx.User.Create().Save(ctx)
if err1 != nil {
return err1
}
t.UserID = user.ID
} else {
GetV4Redis(RUser(t.UserID), &terminalMap)
}
cidBase64 := base64.StdEncoding.EncodeToString(credential.ID)
publicKeyBase64 := base64.StdEncoding.EncodeToString(credential.PublicKey)
_credential, err1 := tx.Credential.
Create().
SetCredID(cidBase64).
SetPublicKey(publicKeyBase64).
SetAttestationType(credential.AttestationType).
Save(ctx)
if err1 != nil {
return err1
}
terminal, err1 := tx.Terminal.
Create().
SetCode(t.Code).SetName(t.Name).SetUa(t.UA).SetOnlyOnce(false).SetUserID(t.UserID).SetCredential(_credential).
Save(ctx)
if err1 != nil {
return err1
}
id = terminal.ID
terminalMap[id] = token
_, err1 = rdb.Pipelined(ctx, func(pipe redis.Pipeliner) error {
if err1 = SetV2RedisPipe(pipe, RUser(t.UserID), &terminalMap, d); err1 != nil {
return err1
}
pipe.Set(ctx, RToken(token), t.UserID, d)
pipe.Del(ctx, RChallenge(challenge))
return nil
})
return err1
})
if err != nil {
return c.InternalServerError(err.Error())
}
return c.Ok(getUserAuthInfo(id, t.Name, token, GetUserAnalyticsCode(t.UserID), false))
}
// 仅支持用户添加终端时使用
func finishRegOnlyOnce(c *Context) error {
challenge, t, err := verifyChallenge(c)
if err != nil {
return c.StatusError(err)
}
if t.State == TokenStateIdle {
return c.MethodNotAllowed("Unauthorized access to the interface.")
}
id := 0
token := New64BitID()
terminalMap := make(map[int]string)
if err = GetV4Redis(RUser(t.UserID), &terminalMap); err != nil {
return c.InternalServerError(err.Error())
}
err = WithTx(ctx, client, func(tx *ent.Tx) error {
terminal, err1 := tx.Terminal.
Create().
SetCode(t.Code).SetName(t.Name).SetUa(t.UA).SetOnlyOnce(true).SetUserID(t.UserID).
Save(ctx)
if err1 != nil {
return err1
}
id = terminal.ID
terminalMap[id] = token
_, err1 = rdb.Pipelined(ctx, func(pipe redis.Pipeliner) error {
if err1 = SetV2RedisPipe(pipe, RUser(t.UserID), &terminalMap, ExpireTimeToken); err1 != nil {
return err1
}
pipe.Set(ctx, RToken(token), t.UserID, ExpireTimeTokenOnce)
pipe.Del(ctx, RChallenge(challenge))
return nil
})
return err1
})
if err != nil {
return c.InternalServerError(err.Error())
}
return c.Ok(getUserAuthInfo(id, t.Name, token, GetUserAnalyticsCode(t.UserID), true))
}
func beginWebAuthnLogin(_terminal *ent.Terminal) (*protocol.CredentialAssertion, error) {
t := Terminal{
Code: _terminal.Code,
Name: _terminal.Name,
Cred: _terminal.Edges.Credential,
}
options, sessionData, err := web.BeginLogin(&t)
if err != nil {
return nil, &RestfulAPIError{Status: http.StatusInternalServerError, Content: err.Error()}
}
if err = SetWebAuthnSession(_terminal.Code, sessionData); err != nil {
return nil, &RestfulAPIError{Status: http.StatusInternalServerError, Content: err.Error()}
}
return options, nil
}
func beginValidate(c *Context) error {
terminalID := c.QueryInt("id")
_terminal, err := client.Terminal.Query().Where(terminal.ID(terminalID)).WithCredential().WithUser().First(ctx)
if err != nil {
return c.NotFound(err.Error())
}
if _terminal.Edges.User.ID != c.GetInt(GinKeyUserID) {
return c.Unauthorized("The terminal does not belong to you")
}
options, err := beginWebAuthnLogin(_terminal)
if err != nil {
return c.StatusError(err)
}
return c.Ok(&options)
}
func beginLogin(c *Context) error {
terminalID := c.QueryInt("id")
_terminal, err := client.Terminal.Query().Where(terminal.ID(terminalID)).WithCredential().First(ctx)
if err != nil {
return c.NotFound(err.Error())
}
options, err := beginWebAuthnLogin(_terminal)
if err != nil {
return c.StatusError(err)
}
return c.Ok(&options)
}
func finishWebAuthnLogin(credential io.Reader, _terminal *ent.Terminal) error {
// Get the session data stored from the function above
// using gorilla/sessions it could look like this
sessionData, err := GetWebAuthnSession(_terminal.Code)
if err != nil {
return &RestfulAPIError{Status: http.StatusUnauthorized, Content: err.Error()}
}
parsedResponse, err := protocol.ParseCredentialRequestResponseBody(credential)
if err != nil {
return &RestfulAPIError{Status: http.StatusUnauthorized, Content: err.Error()}
}
t := Terminal{
Code: _terminal.Code,
Name: _terminal.Name,
Cred: _terminal.Edges.Credential,
}
if _, err = web.ValidateLogin(&t, sessionData, parsedResponse); err != nil {
return &RestfulAPIError{Status: http.StatusUnauthorized, Content: err.Error()}
}
return nil
}
func finishValidate(c *Context) error {
terminalID := c.QueryInt("id")
_terminal, err := client.Terminal.Query().Where(terminal.ID(terminalID)).WithCredential().WithUser().First(ctx)
if err != nil {
return c.NotFound(err.Error())
}
if _terminal.Edges.User.ID != c.GetInt(GinKeyUserID) {
return c.Unauthorized("The terminal does not belong to you")
}
if err = finishWebAuthnLogin(c.Request.Body, _terminal); err != nil {
return c.StatusError(err)
}
return c.Ok(true)
}
func finishLogin(c *Context) error {
terminalID := c.QueryInt("id")
_terminal, err := client.Terminal.Query().Where(terminal.ID(terminalID)).WithCredential().WithUser().First(ctx)
if err != nil {
return c.NotFound(err.Error())
}
if err = finishWebAuthnLogin(c.Request.Body, _terminal); err != nil {
return c.StatusError(err)
}
token := New64BitID()
userID := _terminal.Edges.User.ID
terminalMap := make(map[int]string)
GetV4Redis(RUser(userID), &terminalMap)
terminalMap[terminalID] = token
d := ExpireTimeToken
_, err = rdb.Pipelined(ctx, func(pipe redis.Pipeliner) error {
if err1 := SetV2RedisPipe(pipe, RUser(userID), &terminalMap, d); err1 != nil {
return err1
}
pipe.Set(ctx, RToken(token), userID, d)
return nil
})
if err != nil {
return c.InternalServerError(err.Error())
}
return c.Ok(getUserAuthInfo(terminalID, _terminal.Name, token, GetUserAnalyticsCode(userID), false))
}