~core/sage

ref: 1b55b7345f207d2f2acda0fb8189704eba9f845e sage/src/identity.rs -rw-r--r-- 1.3 KiB
1b55b734 — core rel: v0.1.1 21 days ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
use anyhow::bail;
use serde::{Deserialize, Serialize};
use std::fmt::{Debug, Formatter};
use std::str::FromStr;

#[derive(Serialize, Deserialize, Clone)]
pub struct Identity {
    pub name: String,
    pub email: String,
    pub keys: IdKeyData,
}
#[derive(Serialize, Deserialize, Clone)]
pub enum IdKeyData {
    Local(String),
    Peer(String),
}

impl Debug for Identity {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{} <{}>", self.name, self.email)
    }
}
impl IdKeyData {
    pub fn pk(&self) -> anyhow::Result<String> {
        match self {
            IdKeyData::Local(id) => {
                let k = match age::x25519::Identity::from_str(id) {
                    Ok(k) => k,
                    Err(e) => {
                        bail!(e);
                    }
                };
                Ok(k.to_public().to_string())
            }
            IdKeyData::Peer(pk) => Ok(pk.clone()),
        }
    }
    pub fn keyid(&self) -> anyhow::Result<String> {
        let pk = self.pk()?;
        let s0 = &pk[4..12];
        Ok(s0.to_string())
    }
}

pub fn escape(i: String) -> String {
    urlencoding::encode(&i).to_string()
}
pub fn unescape(i: String) -> anyhow::Result<String> {
    Ok(urlencoding::decode(&i)?.to_string())
}