mirror of
https://git.mills.io/saltyim/saltyim.git
synced 2024-07-01 03:01:09 +00:00
![xuu](/assets/img/avatar_default.png)
Co-authored-by: Jon Lundy <jon@xuu.cc> Reviewed-on: https://git.mills.io/prologic/saltyim/pulls/30 Co-authored-by: xuu <xuu@noreply@mills.io> Co-committed-by: xuu <xuu@noreply@mills.io>
89 lines
2.0 KiB
Go
89 lines
2.0 KiB
Go
package saltyim
|
|
|
|
import (
|
|
"bufio"
|
|
"fmt"
|
|
"io"
|
|
"os"
|
|
"path/filepath"
|
|
"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{}, nil
|
|
}
|
|
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/.config/salty/$USER.key")
|
|
}
|
|
|
|
// DefaultEndpoint returns a default inbox file (if one exists) otherwise
|
|
// returns an empty string
|
|
func DefaultEndpoint() string {
|
|
return os.ExpandEnv("https://msgbus.mills.io/$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 %q 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 %q for writing: %w", fn, err)
|
|
}
|
|
|
|
if err := f.Close(); err != nil {
|
|
return fmt.Errorf("error closing identity %q for writing: %w", fn, err)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// GetIdentity ...
|
|
func GetIdentity(fn string) (*keys.EdX25519Key, Addr, error) {
|
|
// Handle unix home with `~`
|
|
if strings.HasPrefix(fn, "~/") {
|
|
dirname, _ := os.UserHomeDir()
|
|
fn = filepath.Join(dirname, fn[2:])
|
|
}
|
|
|
|
id, err := os.Open(fn)
|
|
if err != nil {
|
|
return nil, Addr{}, fmt.Errorf("error opening identity %q: %s", fn, err)
|
|
}
|
|
defer id.Close()
|
|
|
|
key, err := salty.ParseIdentity(id)
|
|
if err != nil {
|
|
return nil, Addr{}, fmt.Errorf("error reading identity %q: %s", fn, err)
|
|
}
|
|
|
|
id.Seek(0, 0)
|
|
me, err := readUser(id)
|
|
return key, me, err
|
|
}
|