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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
use std::collections::HashMap;
use serde_json::json;

use crate::defs::Config;
use pasetoken_lib::ConfigPaSeToken;

use crate::defs::{
    CLAIM_UID,
    CLAIM_AUTH,
    CLAIM_APP_KEY,
};

#[derive(Debug, Default)]
pub struct UserNotifyData {
    pub key: String,
    pub id: String,
    pub auth: String,
}

impl UserNotifyData {
    pub fn data_claim(&self,_config: &Config) -> HashMap<String,String> { 
        HashMap::from([
            (String::from(CLAIM_UID), self.id.to_owned()),
            (String::from(CLAIM_AUTH), self.auth.to_owned()),
            (String::from(CLAIM_APP_KEY), self.key.to_owned()),
        ])
    }
    pub fn token(&self, server_config: &Config, paseto_config: &ConfigPaSeToken, expire: bool) -> String {
        paseto_config.generate_token("", &self.data_claim(server_config), expire).unwrap_or_else(|e|{
            eprintln!("Error generating token: {}", e);
            String::from("")
        })
    }
    pub fn from_token(token: &str,paseto_config: &ConfigPaSeToken) -> (String,Self) {
        match paseto_config.pasetoken() {
            Ok(paseto) => {
                match paseto.trusted(token, false) {
                    Ok(trusted_token) => {
                        // dbg!(&trusted_token.payload_claims());
                        if let Some(claims) = trusted_token.payload_claims() {
                            // dbg!(&claims);
                            let uid = claims.get_claim(CLAIM_UID).unwrap_or(&json!("")).to_string().replace("\"","");
                            (
                                uid.to_owned(),
                                Self {
                                    key: claims.get_claim(CLAIM_APP_KEY).unwrap_or(&json!("")).to_string().replace("\"",""),
                                    id: uid,
                                    auth: claims.get_claim(CLAIM_AUTH).unwrap_or(&json!("")).to_string().replace("\"",""),
                                }
                            )
                        } else {
                            (String::from(""), Self::default())
                        }
                    },
                    Err(e) => {
                        println!("Token not trusted: {}",e);
                        (String::from(""), Self::default())
                    },
                }
            },
            Err(e) => {
                println!("Error collecting notify data: {}",e);
                (String::from(""), Self::default())
            }
        }
    }
}