Skip to main content

hirust_auth/
lib.rs

1use serde_derive::{Deserialize, Serialize};
2use std::collections::HashMap;
3use std::sync::{LazyLock, Mutex};
4
5#[derive(Serialize, Deserialize, Debug, Clone, Default)]
6pub struct Auth {
7    pub method: String,
8    pub path: String,
9    pub tag: String,
10    pub desc: String,
11    pub middleware: String,
12    pub auth: String,
13}
14
15impl Auth {
16    #[allow(dead_code)]
17    pub fn get_auth(&self) -> bool {
18        if self.auth.eq("true") {
19            return true;
20        }
21        return false;
22    }
23}
24
25static AUTH_COLLECT: LazyLock<Mutex<HashMap<String, Auth>>> =
26    LazyLock::new(|| Mutex::new(HashMap::new()));
27
28type PrintFn = fn(t: &String, a: &Auth);
29
30#[allow(unused)]
31pub fn print(f: PrintFn) {
32    for (tag, auth_info) in AUTH_COLLECT.lock().unwrap().iter() {
33        f(tag, auth_info);
34    }
35}
36
37#[allow(unused)]
38pub fn insert(auth_info: Auth) {
39    AUTH_COLLECT
40        .lock()
41        .unwrap()
42        .insert(auth_info.tag.clone(), auth_info.clone());
43}
44
45#[allow(unused)]
46pub fn get(tag: String) -> Auth {
47    AUTH_COLLECT.lock().unwrap().get(&tag).unwrap().clone()
48}
49
50#[allow(unused)]
51pub fn exist(tag: String) -> Option<Auth> {
52    match AUTH_COLLECT.lock().unwrap().get(&tag) {
53        Some(a) => Some(a.clone()),
54        None => None,
55    }
56}
57
58///
59/// Examples
60///```text
61/// async fn test(req: actix_web::HttpRequest) -> impl Responder {
62///     return throw!(&req, errcode::VALID_CODE_ERROR);
63/// }
64///```
65///
66#[macro_export]
67#[allow(unused_macros)]
68macro_rules! throw {
69    ($a:expr, $b:expr) => {
70        $b.throw($a)
71    };
72}
73
74///
75/// Examples
76///```text
77/// async fn test(req: actix_web::HttpRequest) -> impl Responder {
78///     return throw_tips!(&req, errcode::VALID_CODE_ERROR, "kkk");
79/// }
80///```
81///
82#[macro_export]
83#[allow(unused_macros)]
84macro_rules! throw_tips {
85    ($a:expr, $b:expr, $c:expr) => {
86        $b.throw_tips($a, $c)
87    };
88}