meowlib/client/identity.go
2022-09-06 17:07:35 +02:00

78 lines
2.1 KiB
Go

package client
import (
"encoding/json"
"io/ioutil"
"forge.redroom.link/yves/meowlib"
"github.com/ProtonMail/gopenpgp/v2/helper"
)
const key = "3pw0c8#6ZG8{75b5;3?fe80$2"
type Identity struct {
Nickname string `json:"nickname,omitempty"`
RootKp meowlib.KeyPair `json:"id_kp,omitempty"`
Status string `json:"status,omitempty"`
Peers PeerList `json:"peers,omitempty"`
KnownServers InternalServerList `json:"known_servers,omitempty"`
MessageServers InternalServerList `json:"message_servers,omitempty"`
}
func CreateIdentity(nickname string) *Identity {
var id Identity
id.Nickname = nickname
id.RootKp = meowlib.NewKeyPair()
return &id
}
func (id *Identity) InvitePeer(MyName string, ContactName string, MessageServerIdxs []int) (*Peer, *meowlib.ContactCard) {
var peer Peer
var myContactCard meowlib.ContactCard
peer.Me = meowlib.NewKeyPair()
peer.EncryptionKp = meowlib.NewKeyPair()
peer.LookupKp = meowlib.NewKeyPair()
peer.Name = ContactName
for _, i := range MessageServerIdxs {
srv := id.MessageServers.Servers[i].ServerData
myContactCard.PullServers = append(myContactCard.PullServers, &srv)
}
myContactCard.Name = MyName
myContactCard.ContactPublicKey = peer.Me.Public
myContactCard.EncryptionPublicKey = peer.EncryptionKp.Public
myContactCard.LookupPublicKey = peer.LookupKp.Public
id.Peers = append(id.Peers, peer)
return &id.Peers[len(id.Peers)-1], &myContactCard
}
func (*Identity) FinalizeInvitation(peer *Peer, ReceivedContact *meowlib.ContactCard) {
peer.Contact = *ReceivedContact
}
func LoadIdentity(file string) (*Identity, error) {
var id Identity
indata, err := ioutil.ReadFile(file)
if err != nil {
return nil, err
}
pass, err := helper.DecryptMessageWithPassword([]byte(key), string(indata))
if err != nil {
return nil, err
}
err = json.Unmarshal([]byte(pass), &id)
return &id, err
}
func (id *Identity) Save(file string) error {
b, _ := json.Marshal(id)
armor, err := helper.EncryptMessageWithPassword([]byte(key), string(b))
if err != nil {
return err
}
err = ioutil.WriteFile(file, []byte(armor), 0644)
return err
}