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