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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
// Copyright 2023 Fondazione LINKS

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at

//     http://www.apache.org/licenses/LICENSE-2.0

// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.



use std::iter::zip;

use indexmap::IndexMap;
use json_unflattening::{flattening::flatten, unflattening::unflatten};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json, Map, value::Index};


use super::payloads::Payloads;

#[derive(Clone, Debug, Default, PartialEq, Eq, Deserialize, Serialize)]
pub struct Claims (pub Vec<String>);


#[derive(Clone, Debug, Default, PartialEq, Eq, Deserialize, Serialize)]
pub struct CustomValue {
    value: Value,
    #[serde(skip_serializing)]
    flattening: bool
}

/** These claims are taken from the JWT RFC (https://tools.ietf.org/html/rfc7519) 
 * making the hypothesis that in the future will be used also for the JPTs **/

#[derive(Clone, Debug, Default, PartialEq, Eq, Deserialize, Serialize)]
pub struct JptClaims {

    /** Apparently the "aud" that in JWT was a claim, now should be an presentation protected header parameter 
      * (https://datatracker.ietf.org/doc/html/draft-ietf-jose-json-web-proof#name-presentation-protected-head) **/
    /// Who issued the JWP
    #[serde(skip_serializing_if = "Option::is_none")]
    pub iss: Option<String>,
    /// Subject of the JPT.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sub: Option<String>,
    /// Expiration time
    #[serde(skip_serializing_if = "Option::is_none")]
    pub exp: Option<i64>,
    /// Time before which the JPT MUST NOT be accepted
    #[serde(skip_serializing_if = "Option::is_none")]
    pub nbf: Option<i64>,
    /// Issuance time
    #[serde(skip_serializing_if = "Option::is_none")]
    pub iat: Option<i64>,
    /// Unique ID for the JPT.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub jti: Option<String>,
    /// Other custom claims (age, name, surname, Verifiable Credential, ...)
    #[serde(flatten)]
    pub custom: IndexMap<String, Value>
}

impl JptClaims {

    pub fn new() -> Self {
        Self {
            iss: None,
            sub: None,
            exp: None, 
            nbf: None, 
            iat: None, 
            jti: None, 
            custom: IndexMap::new() }
    }

    pub fn set_iss(&mut self, value: String) {
        self.iss = Some(value);
    }

    pub fn set_sub(&mut self, value: String) {
        self.sub = Some(value);
    }

    pub fn set_exp(&mut self, value: i64) {
        self.exp = Some(value);
    }

    pub fn set_nbf(&mut self, value: i64) {
        self.nbf = Some(value);
    }

    pub fn set_iat(&mut self, value: i64) {
        self.iat = Some(value);
    }

    pub fn set_jti(&mut self, value: String) {
        self.jti = Some(value);
    }

    pub fn set_claim<T: Serialize>(&mut self, claim: Option<&str>, value: T, flattened: bool) {

        let serde_value = serde_json::to_value(value).unwrap();
        if !serde_value.is_object() {
            self.custom.insert(claim.unwrap_or("").to_string(), serde_value);

        } else {
            if flattened {
                let v = match claim {
                    Some(c) => json!({c: serde_value}),
                    None => serde_value,
                };
                self.custom.extend(flatten(&v).unwrap());
            } else {
                self.custom.insert(claim.unwrap_or("").to_string(), serde_value);
            }
        };
        
    }


    pub fn get_claim(&self, claim: &str) -> Option<&Value> {
        self.custom.get(claim)
    }


    /// Extracts claims and payloads into separate vectors.
    pub fn get_claims_and_payloads(&self) -> (Claims, Payloads){

        let jptclaims_json_value = serde_json::to_value(self).unwrap();

        let claims_payloads_pairs = jptclaims_json_value.as_object().unwrap().to_owned();
        
        let (keys, values): (Vec<String>, Vec<Value>) = claims_payloads_pairs.to_owned().into_iter().unzip();

        (Claims(keys), Payloads::new_from_values(values))
        
    }


    /// Reconstruct JptClaims from Claims and Payloads
    pub fn from_claims_and_payloads(claims: &Claims, payloads: &Payloads) -> Self {
        let zip: Map<String, Value> = zip(claims.0.clone(), payloads.get_values()).collect();
        let unflat = unflatten(&zip).unwrap();
        let jpt_claims: Self = serde_json::from_value(unflat).unwrap();

        jpt_claims
        
    }
  
}