6
1
mirror of https://git.mills.io/saltyim/saltyim.git synced 2024-06-29 18:21:06 +00:00
prologic-saltyim/identity.go
xuu d1d33e45c6 feat: hax for great justice (#14)
- Dont send message on empty
- inbox flag to override $USER
- Filter messages to only chat with partner.

NOTE: might be better to parse the message in loop to handle events outside the formatting code.

NOTE NOTE: i think we might need to revisit read recipts.. maybe including user@domain?

Co-authored-by: Jon Lundy <jon@xuu.cc>
Reviewed-on: https://git.mills.io/prologic/saltyim/pulls/14
Co-authored-by: xuu <xuu@noreply@mills.io>
Co-committed-by: xuu <xuu@noreply@mills.io>
2022-03-19 21:33:03 +00:00

86 lines
1.9 KiB
Go

package saltyim
import (
"bufio"
"fmt"
"io"
"os"
"strings"
"github.com/keys-pub/keys"
"go.mills.io/salty"
)
func readUser(fd io.Reader) (Addr, error) {
scan := bufio.NewScanner(fd)
var a Addr
for scan.Scan() {
if strings.HasPrefix(scan.Text(), "# user:") {
user := strings.Split(strings.TrimSpace(strings.TrimPrefix(scan.Text(), "# user:")), "@")
if len(user) != 2 {
return Addr{}, fmt.Errorf("user not found")
}
a.User, a.Domain = user[0], user[1]
}
}
return a, scan.Err()
}
// DefaultIdentity returns a default identity file (if one exists) otherwise
// returns an empty string
func DefaultIdentity() string {
return os.ExpandEnv("$HOME/.salty/$USER.key")
}
// DefaultInbox returns a default inbox file (if one exists) otherwise
// returns an empty string
func DefaultInbox() string {
return os.ExpandEnv("$USER")
}
// CreateIdentity ...
func CreateIdentity(fn, user string) error {
f, err := os.OpenFile(fn, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600)
if err != nil {
return fmt.Errorf("error opening identity %s for writing: %w", fn, err)
}
defer f.Close()
salty.GenerateKeys(f)
f.Write([]byte(fmt.Sprintf("# user: %s\n", user)))
if err := f.Sync(); err != nil {
return fmt.Errorf("error syncing identity %s for writing: %w", fn, err)
}
if err := f.Close(); err != nil {
return fmt.Errorf("error closing identity %s for writing: %w", fn, err)
}
return nil
}
// GetIdentity ...
func GetIdentity(fn string) (*keys.EdX25519Key, Addr, error) {
id, err := os.Open(fn)
if err != nil {
return nil, Addr{}, fmt.Errorf("error opening identity file: %q", fn)
}
defer id.Close()
key, err := salty.ParseIdentity(id)
if err != nil {
return nil, Addr{}, fmt.Errorf("error reading private key: %q", fn)
}
id.Seek(0, 0)
me, err := readUser(id)
if err != nil {
return key, Addr{}, fmt.Errorf("error reading user from keyfile: %q", fn)
}
return key, me, nil
}