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
use std::time::{Instant, Duration};

use anyhow::bail;

use serde::Deserialize;
use serde::Serialize;

#[derive(Serialize, Deserialize, Debug)]
pub struct JWTJson {
    pub token: String,
}

#[derive(Debug)]
pub struct JWT {
    token: Option<String>,
    time: Option<Instant>
}

impl JWT {
    pub fn new() -> Self {
        Self { token: None, time: None }
    }
    pub fn is_expired(&mut self) -> bool {
        if let None = self.time {
            return true;
        }
        let duration = Instant::now() - self.time.unwrap();

        if duration >= Duration::from_secs(300) {
            self.token = None;
            self.time = None;
            return true;
        }

        return false;
    }

    pub fn get(&mut self) -> anyhow::Result<String> {
        if self.is_expired() {
            bail!("expired jwt");
        }

        if let Some(x) = self.token.clone() {
            return Ok(x);
        }

        bail!("No jwt yet");
    }

    pub fn set(&mut self, token: String) -> () {
        self.time = Some(Instant::now());
        self.token = Some(token);
    }
}