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
use jsonwebtoken::{self, EncodingKey};
use salvo::jwt_auth::{ConstDecoder, JwtTokenFinder};
use salvo::prelude::*;
use serde::de::DeserializeOwned;
use serde::Serialize;

use crate::web_core::http_error::AnyHttpError;
use crate::HttpErrorKind;

#[allow(dead_code)]
pub fn gen_jwt_auth<T: Send + Sync + DeserializeOwned + 'static>(
    secret_key: String,
    finders: Vec<Box<dyn JwtTokenFinder>>,
) -> JwtAuth<T, ConstDecoder> {
    JwtAuth::new(ConstDecoder::from_secret(secret_key.as_bytes()))
        .finders(finders)
        .force_passed(true)
}

#[allow(dead_code)]
pub fn gen_token<T: Serialize + Send + Sync + 'static>(
    secret_key: String,
    claim: T,
) -> Result<String, jsonwebtoken::errors::Error> {
    jsonwebtoken::encode(
        &jsonwebtoken::Header::default(),
        &claim,
        &EncodingKey::from_secret(secret_key.as_bytes()),
    )
}
pub struct AuthGuard<F: Fn(JwtAuthState) -> AnyHttpError + Send + Sync + 'static> {
    f: F,
}
#[allow(dead_code)]
impl<F> AuthGuard<F>
where
    F: Fn(JwtAuthState) -> AnyHttpError + Send + Sync + 'static,
{
    pub fn new(f: F) -> Self {
        Self { f }
    }
}
#[async_trait]
impl<F> Handler for AuthGuard<F>
where
    F: Fn(JwtAuthState) -> AnyHttpError + Send + Sync + 'static,
{
    async fn handle(
        &self,
        req: &mut Request,
        depot: &mut Depot,
        res: &mut Response,
        ctrl: &mut FlowCtrl,
    ) {
        match depot.jwt_auth_state() {
            JwtAuthState::Authorized => {
                ctrl.call_next(req, depot, res).await;
            }
            JwtAuthState::Unauthorized => {
                res.status_code(StatusCode::UNAUTHORIZED);
                match (self.f)(JwtAuthState::Unauthorized).1 {
                    HttpErrorKind::Html(v) => {
                        res.render(Text::Html(v));
                    }
                    HttpErrorKind::Json(v) => {
                        res.render(Text::Json(v.to_string()));
                    }
                };
                ctrl.skip_rest();
            }
            JwtAuthState::Forbidden => {
                res.status_code(StatusCode::FORBIDDEN);
                match (self.f)(JwtAuthState::Forbidden).1 {
                    HttpErrorKind::Html(v) => {
                        res.render(Text::Html(v));
                    }
                    HttpErrorKind::Json(v) => {
                        res.render(Text::Json(v.to_string()));
                    }
                };
                ctrl.skip_rest();
            }
        };
    }
}

#[macro_export]
macro_rules! expire_time {
    (Days($day:expr)) => {{
        use time::{Duration, OffsetDateTime};
        let tmp = OffsetDateTime::now_utc() + Duration::days($day);
        tmp.unix_timestamp()
    }};
    (Weeks($w:expr)) => {{
        use time::{Duration, OffsetDateTime};
        let tmp = OffsetDateTime::now_utc() + Duration::weeks($w);
        tmp.unix_timestamp()
    }};
    (Hours($h:expr)) => {{
        use time::{Duration, OffsetDateTime};
        let tmp = OffsetDateTime::now_utc() + Duration::hours($h);
        tmp.unix_timestamp()
    }};
    (Minutes($m:expr)) => {{
        use time::{Duration, OffsetDateTime};
        let tmp = OffsetDateTime::now_utc() + Duration::minutes($m);
        tmp.unix_timestamp()
    }};
    (Seconds($s:expr)) => {{
        use time::{Duration, OffsetDateTime};
        let tmp = OffsetDateTime::now_utc() + Duration::seconds($s);
        tmp.unix_timestamp()
    }};
}