github.com/cloudreve/Cloudreve/v3@v3.0.0-20240224133659-3edb00a6484c/models/user_authn.go (about)

     1  package model
     2  
     3  import (
     4  	"encoding/base64"
     5  	"encoding/binary"
     6  	"encoding/json"
     7  	"fmt"
     8  	"net/url"
     9  
    10  	"github.com/cloudreve/Cloudreve/v3/pkg/hashid"
    11  	"github.com/duo-labs/webauthn/webauthn"
    12  )
    13  
    14  /*
    15  	`webauthn.User` 接口的实现
    16  */
    17  
    18  // WebAuthnID 返回用户ID
    19  func (user User) WebAuthnID() []byte {
    20  	bs := make([]byte, 8)
    21  	binary.LittleEndian.PutUint64(bs, uint64(user.ID))
    22  	return bs
    23  }
    24  
    25  // WebAuthnName 返回用户名
    26  func (user User) WebAuthnName() string {
    27  	return user.Email
    28  }
    29  
    30  // WebAuthnDisplayName 获得用于展示的用户名
    31  func (user User) WebAuthnDisplayName() string {
    32  	return user.Nick
    33  }
    34  
    35  // WebAuthnIcon 获得用户头像
    36  func (user User) WebAuthnIcon() string {
    37  	avatar, _ := url.Parse("/api/v3/user/avatar/" + hashid.HashID(user.ID, hashid.UserID) + "/l")
    38  	base := GetSiteURL()
    39  	base.Scheme = "https"
    40  	return base.ResolveReference(avatar).String()
    41  }
    42  
    43  // WebAuthnCredentials 获得已注册的验证器凭证
    44  func (user User) WebAuthnCredentials() []webauthn.Credential {
    45  	var res []webauthn.Credential
    46  	err := json.Unmarshal([]byte(user.Authn), &res)
    47  	if err != nil {
    48  		fmt.Println(err)
    49  	}
    50  	return res
    51  }
    52  
    53  // RegisterAuthn 添加新的验证器
    54  func (user *User) RegisterAuthn(credential *webauthn.Credential) error {
    55  	exists := user.WebAuthnCredentials()
    56  	exists = append(exists, *credential)
    57  	res, err := json.Marshal(exists)
    58  	if err != nil {
    59  		return err
    60  	}
    61  
    62  	return DB.Model(user).Update("authn", string(res)).Error
    63  }
    64  
    65  // RemoveAuthn 删除验证器
    66  func (user *User) RemoveAuthn(id string) {
    67  	exists := user.WebAuthnCredentials()
    68  	for i := 0; i < len(exists); i++ {
    69  		idEncoded := base64.StdEncoding.EncodeToString(exists[i].ID)
    70  		if idEncoded == id {
    71  			exists[len(exists)-1], exists[i] = exists[i], exists[len(exists)-1]
    72  			exists = exists[:len(exists)-1]
    73  			break
    74  		}
    75  	}
    76  
    77  	res, _ := json.Marshal(exists)
    78  	DB.Model(user).Update("authn", string(res))
    79  }