Files
uncloud/internal/cli/user.go
T

52 lines
964 B
Go

package cli
import (
"fmt"
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
"net/netip"
"uncloud/internal/secret"
)
type User struct {
privateKey wgtypes.Key
}
func NewUser(privateKey secret.Secret) (*User, error) {
var (
wgKey wgtypes.Key
err error
)
if privateKey == nil {
wgKey, err = wgtypes.GeneratePrivateKey()
if err != nil {
return nil, fmt.Errorf("generate key for user: %w", err)
}
privateKey = wgKey[:]
} else {
wgKey, err = wgtypes.NewKey(privateKey)
if err != nil {
return nil, fmt.Errorf("invalid key: %w", err)
}
privateKey = wgKey[:]
}
return &User{
privateKey: wgKey,
}, nil
}
func (u *User) PrivateKey() secret.Secret {
return u.privateKey[:]
}
func (u *User) PublicKey() secret.Secret {
pubKey := u.privateKey.PublicKey()
return pubKey[:]
}
func (u *User) Address() netip.Addr {
pubKey := u.PublicKey()
bytes := [16]byte{0xfd, 0xcc}
copy(bytes[2:], pubKey[:14])
return netip.AddrFrom16(bytes)
}