graphvent/user.go

89 lines
1.7 KiB
Go

2023-07-20 22:08:28 -06:00
package graphvent
import (
"time"
"fmt"
"encoding/json"
"crypto/ecdsa"
"crypto/x509"
)
type User struct {
2023-07-24 16:04:56 -06:00
Lockable
2023-07-20 22:08:28 -06:00
Granted time.Time
Pubkey *ecdsa.PublicKey
Shared []byte
2023-07-21 13:33:04 -06:00
Tags []string
2023-07-20 22:08:28 -06:00
}
type UserJSON struct {
2023-07-24 16:04:56 -06:00
LockableJSON
2023-07-20 22:08:28 -06:00
Granted time.Time `json:"granted"`
Pubkey []byte `json:"pubkey"`
Shared []byte `json:"shared"`
2023-07-21 13:33:04 -06:00
Tags []string `json:"tags"`
2023-07-20 22:08:28 -06:00
}
func (user *User) Type() NodeType {
2023-07-20 22:08:45 -06:00
return NodeType("user")
2023-07-20 22:08:28 -06:00
}
func (user *User) Serialize() ([]byte, error) {
2023-07-24 16:04:56 -06:00
lockable_json := NewLockableJSON(&user.Lockable)
2023-07-20 22:08:28 -06:00
pubkey, err := x509.MarshalPKIXPublicKey(user.Pubkey)
if err != nil {
return nil, err
}
return json.MarshalIndent(&UserJSON{
2023-07-24 16:04:56 -06:00
LockableJSON: lockable_json,
2023-07-20 22:08:28 -06:00
Granted: user.Granted,
Shared: user.Shared,
Pubkey: pubkey,
2023-07-21 13:33:04 -06:00
Tags: user.Tags,
2023-07-20 22:08:28 -06:00
}, "", " ")
}
func LoadUser(ctx *Context, id NodeID, data []byte, nodes NodeMap) (Node, error) {
var j UserJSON
err := json.Unmarshal(data, &j)
if err != nil {
return nil, err
}
pub, err := x509.ParsePKIXPublicKey(j.Pubkey)
if err != nil {
return nil, err
}
var pubkey *ecdsa.PublicKey
switch pub.(type) {
case *ecdsa.PublicKey:
pubkey = pub.(*ecdsa.PublicKey)
default:
return nil, fmt.Errorf("Invalid key type")
}
2023-07-21 13:33:04 -06:00
user := NewUser(j.Name, j.Granted, pubkey, j.Shared, j.Tags)
2023-07-20 22:08:28 -06:00
nodes[id] = &user
2023-07-24 16:04:56 -06:00
err = RestoreLockable(ctx, &user.Lockable, j.LockableJSON, nodes)
2023-07-20 22:08:28 -06:00
if err != nil {
return nil, err
}
return &user, nil
}
2023-07-21 13:33:04 -06:00
func NewUser(name string, granted time.Time, pubkey *ecdsa.PublicKey, shared []byte, tags []string) User {
2023-07-20 22:08:28 -06:00
id := KeyID(pubkey)
return User{
2023-07-24 16:04:56 -06:00
Lockable: NewLockable(id, name),
2023-07-20 22:08:28 -06:00
Granted: granted,
Pubkey: pubkey,
Shared: shared,
2023-07-21 13:33:04 -06:00
Tags: tags,
2023-07-20 22:08:28 -06:00
}
}