feat: support webauthn login (#4945)

* feat: support webauthn login

* manually merge

* fix: clear user cache after updating authn

* decrease db size of Authn

* change authn type to text

* simplify code structure

---------

Co-authored-by: Andy Hsu <i@nn.ci>
This commit is contained in:
itsHenry
2023-08-14 22:54:38 +08:00
committed by GitHub
parent 13e8d36e1a
commit 1aa024ed6b
11 changed files with 396 additions and 2 deletions

View File

@ -1,7 +1,11 @@
package db
import (
"encoding/base64"
"github.com/alist-org/alist/v3/internal/model"
"github.com/alist-org/alist/v3/pkg/utils"
"github.com/go-webauthn/webauthn/webauthn"
"github.com/pkg/errors"
)
@ -59,3 +63,40 @@ func GetUsers(pageIndex, pageSize int) (users []model.User, count int64, err err
func DeleteUserById(id uint) error {
return errors.WithStack(db.Delete(&model.User{}, id).Error)
}
func UpdateAuthn(userID uint, authn string) error {
return db.Model(&model.User{ID: userID}).Update("authn", authn).Error
}
func RegisterAuthn(u *model.User, credential *webauthn.Credential) error {
if u == nil {
return errors.New("user is nil")
}
exists := u.WebAuthnCredentials()
if credential != nil {
exists = append(exists, *credential)
}
res, err := utils.Json.Marshal(exists)
if err != nil {
return err
}
return UpdateAuthn(u.ID, string(res))
}
func RemoveAuthn(u *model.User, id string) error {
exists := u.WebAuthnCredentials()
for i := 0; i < len(exists); i++ {
idEncoded := base64.StdEncoding.EncodeToString(exists[i].ID)
if idEncoded == id {
exists[len(exists)-1], exists[i] = exists[i], exists[len(exists)-1]
exists = exists[:len(exists)-1]
break
}
}
res, err := utils.Json.Marshal(exists)
if err != nil {
return err
}
return UpdateAuthn(u.ID, string(res))
}