Files

81 lines
2.2 KiB
Go
Raw Permalink Normal View History

2022-01-14 23:03:31 +08:00
// Copyright 2021 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
2022-01-14 23:03:31 +08:00
package webauthn
import (
"context"
2022-01-14 23:03:31 +08:00
"encoding/binary"
"encoding/gob"
"code.gitea.io/gitea/models/auth"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/util"
2022-01-14 23:03:31 +08:00
"github.com/go-webauthn/webauthn/protocol"
"github.com/go-webauthn/webauthn/webauthn"
2022-01-14 23:03:31 +08:00
)
2022-01-20 18:46:10 +01:00
// WebAuthn represents the global WebAuthn instance
2022-01-14 23:03:31 +08:00
var WebAuthn *webauthn.WebAuthn
2022-01-20 18:46:10 +01:00
// Init initializes the WebAuthn instance from the config.
2022-01-14 23:03:31 +08:00
func Init() {
2025-11-26 23:25:34 +08:00
gob.Register(&webauthn.SessionData{}) // TODO: CHI-SESSION-GOB-REGISTER.
2022-01-14 23:03:31 +08:00
appURL, _ := protocol.FullyQualifiedOrigin(setting.AppURL)
2022-01-14 23:03:31 +08:00
WebAuthn = &webauthn.WebAuthn{
Config: &webauthn.Config{
RPDisplayName: setting.AppName,
RPID: setting.Domain,
RPOrigins: []string{appURL},
2022-01-14 23:03:31 +08:00
AuthenticatorSelection: protocol.AuthenticatorSelection{
2024-06-30 00:50:03 +02:00
UserVerification: protocol.VerificationDiscouraged,
2022-01-14 23:03:31 +08:00
},
AttestationPreference: protocol.PreferDirectAttestation,
},
}
}
// user represents an implementation of webauthn.User based on User model
type user struct {
ctx context.Context
User *user_model.User
defaultAuthFlags protocol.AuthenticatorFlags
}
var _ webauthn.User = (*user)(nil)
func NewWebAuthnUser(ctx context.Context, u *user_model.User, defaultAuthFlags ...protocol.AuthenticatorFlags) webauthn.User {
return &user{ctx: ctx, User: u, defaultAuthFlags: util.OptionalArg(defaultAuthFlags)}
}
2022-01-14 23:03:31 +08:00
2022-01-20 18:46:10 +01:00
// WebAuthnID implements the webauthn.User interface
func (u *user) WebAuthnID() []byte {
2022-01-14 23:03:31 +08:00
id := make([]byte, 8)
binary.PutVarint(id, u.User.ID)
2022-01-14 23:03:31 +08:00
return id
}
2022-01-20 18:46:10 +01:00
// WebAuthnName implements the webauthn.User interface
func (u *user) WebAuthnName() string {
return util.IfZero(u.User.LoginName, u.User.Name)
2022-01-14 23:03:31 +08:00
}
2022-01-20 18:46:10 +01:00
// WebAuthnDisplayName implements the webauthn.User interface
func (u *user) WebAuthnDisplayName() string {
return u.User.DisplayName()
2022-01-14 23:03:31 +08:00
}
2024-06-30 00:50:03 +02:00
// WebAuthnCredentials implements the webauthn.User interface
func (u *user) WebAuthnCredentials() []webauthn.Credential {
dbCreds, err := auth.GetWebAuthnCredentialsByUID(u.ctx, u.User.ID)
2022-01-14 23:03:31 +08:00
if err != nil {
return nil
}
return dbCreds.ToCredentials(u.defaultAuthFlags)
2022-01-14 23:03:31 +08:00
}