gitea源码

webauthn.go 2.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // Copyright 2021 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package webauthn
  4. import (
  5. "context"
  6. "encoding/binary"
  7. "encoding/gob"
  8. "code.gitea.io/gitea/models/auth"
  9. user_model "code.gitea.io/gitea/models/user"
  10. "code.gitea.io/gitea/modules/setting"
  11. "code.gitea.io/gitea/modules/util"
  12. "github.com/go-webauthn/webauthn/protocol"
  13. "github.com/go-webauthn/webauthn/webauthn"
  14. )
  15. // WebAuthn represents the global WebAuthn instance
  16. var WebAuthn *webauthn.WebAuthn
  17. // Init initializes the WebAuthn instance from the config.
  18. func Init() {
  19. gob.Register(&webauthn.SessionData{})
  20. appURL, _ := protocol.FullyQualifiedOrigin(setting.AppURL)
  21. WebAuthn = &webauthn.WebAuthn{
  22. Config: &webauthn.Config{
  23. RPDisplayName: setting.AppName,
  24. RPID: setting.Domain,
  25. RPOrigins: []string{appURL},
  26. AuthenticatorSelection: protocol.AuthenticatorSelection{
  27. UserVerification: protocol.VerificationDiscouraged,
  28. },
  29. AttestationPreference: protocol.PreferDirectAttestation,
  30. },
  31. }
  32. }
  33. // user represents an implementation of webauthn.User based on User model
  34. type user struct {
  35. ctx context.Context
  36. User *user_model.User
  37. defaultAuthFlags protocol.AuthenticatorFlags
  38. }
  39. var _ webauthn.User = (*user)(nil)
  40. func NewWebAuthnUser(ctx context.Context, u *user_model.User, defaultAuthFlags ...protocol.AuthenticatorFlags) webauthn.User {
  41. return &user{ctx: ctx, User: u, defaultAuthFlags: util.OptionalArg(defaultAuthFlags)}
  42. }
  43. // WebAuthnID implements the webauthn.User interface
  44. func (u *user) WebAuthnID() []byte {
  45. id := make([]byte, 8)
  46. binary.PutVarint(id, u.User.ID)
  47. return id
  48. }
  49. // WebAuthnName implements the webauthn.User interface
  50. func (u *user) WebAuthnName() string {
  51. return util.IfZero(u.User.LoginName, u.User.Name)
  52. }
  53. // WebAuthnDisplayName implements the webauthn.User interface
  54. func (u *user) WebAuthnDisplayName() string {
  55. return u.User.DisplayName()
  56. }
  57. // WebAuthnCredentials implements the webauthn.User interface
  58. func (u *user) WebAuthnCredentials() []webauthn.Credential {
  59. dbCreds, err := auth.GetWebAuthnCredentialsByUID(u.ctx, u.User.ID)
  60. if err != nil {
  61. return nil
  62. }
  63. return dbCreds.ToCredentials(u.defaultAuthFlags)
  64. }