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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
use crate::loginmanager::LoginInfo;
use actix_web::{
    dev::Payload, error::InternalError, http::StatusCode, Error, FromRequest, HttpMessage,
    HttpRequest,
};
use futures::Future;
use serde::{de::DeserializeOwned, Serialize};
use std::pin::Pin;
use std::rc::Rc;
/// the base user trait
/// ### Example: Get user from database
/// ```rust
/// # use actix_web::{HttpRequest,Data};
/// # use futures::Future;
/// # use std::pin::Pin;
/// # use sqlx;
/// type Pool = sqlx::SqlitePool;
///
/// #[derive(Serialize, Deserialize)]
/// pub struct User { ... }
///
/// impl UserMinix for User {
///     type Future = Pin<Box<dyn Future<Output = Option<Self>>>>;
///     type Key = i32;
///     fn get_user(id: &i32, req: &HttpRequest) -> Self::Future {
///         let req = req.clone();
///         let id = id.clone();
///         Box::pin(async move {
///             if let Some(pool) = req.app_data::<Data<Pool>>(){
///                 let pool = pool.get_ref();  
///                 todo!()   // get user from pool instance,return Some(user) or None
///             }else{
///                 None
///             }
///         })
///     }
///     fn get_id(&self) -> i32 {
///         self.id
///     }
/// }
/// ```
pub trait UserMinix: Sized {
    ///
    type Future: Future<Output = Option<Self>>;

    /// The type of User, must be same as Loginmanager.
    /// Otherwise no user will be returned.
    type Key: Serialize + DeserializeOwned;

    /// Get user from id and req,Tip:can use req.app_data to obtain
    /// database connection defined in Web app.
    fn get_user(id: &Self::Key, req: &HttpRequest) -> Self::Future;

    /// Return the User id
    fn get_id(&self) -> &Self::Key;

    /// return user's actual authentication status, default True.
    fn is_authenticated(&self) -> bool {
        true
    }

    /// return user's actual active status, default True.
    fn is_actived(&self) -> bool {
        true
    }
}

/// The wrap of user Instance. It implements `FromRequest` trait.  
///
/// It will return `401 Unauthorized` if no key or error key.  
///
/// If loginmanager set redirect true,then will rediret login_view.
/// ```rust
/// #[get("/index")]
/// async fn index(UserWrap(user): UserWrap<User>) -> impl Responder{
///     todo()!
/// }
/// ```
pub struct UserWrap<T>(pub Rc<T>);

impl<T> Clone for UserWrap<T> {
    fn clone(&self) -> Self {
        Self(self.0.clone())
    }
}

impl<T: 'static> UserWrap<T>
where
    T: UserMinix,
{
    pub fn new(user: T) -> Self {
        Self(Rc::new(user))
    }

    pub fn user(&self) -> &T {
        self.0.as_ref()
    }
}

impl<U> From<U> for UserWrap<U> {
    fn from(u: U) -> Self {
        UserWrap(Rc::new(u))
    }
}

impl<U> AsRef<U> for UserWrap<U> {
    fn as_ref(&self) -> &U {
        self.0.as_ref()
    }
}

impl<T: 'static> FromRequest for UserWrap<T>
where
    T: UserMinix,
{
    type Error = Error;
    type Future = Pin<Box<dyn Future<Output = Result<Self, Self::Error>>>>;

    #[inline]
    fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future {
        let req_clone: HttpRequest = req.clone();
        Box::pin(async move {
            let extensions = &mut req_clone.extensions_mut();
            if let Some(user) = extensions.get::<Self>() {
                return Ok(user.clone());
            } else {
                match extensions.get::<LoginInfo>() {
                    Some(LoginInfo {
                        key_str: Some(key_str),
                        ..
                    }) => match serde_json::from_str::<T::Key>(&key_str) {
                        Ok(key) => {
                            let real_user = T::get_user(&key, &req_clone).await;
                            if let Some(real_user) = real_user {
                                let user = UserWrap(Rc::new(real_user));
                                extensions.insert(user.clone());
                                return Ok(user);
                            }
                        }
                        _ => {}
                    },
                    _ => {}
                };
            };
            return Err(InternalError::new("No authentication.", StatusCode::UNAUTHORIZED).into());
        })
    }
}

/// The wrap of userwrap Instance. It will check if the user is actived and authenticated
pub struct UserWrapAuth<U>(pub UserWrap<U>);

impl<U> From<U> for UserWrapAuth<U> {
    fn from(u: U) -> Self {
        UserWrapAuth(UserWrap(Rc::new(u)))
    }
}

impl<U> AsRef<U> for UserWrapAuth<U> {
    fn as_ref(&self) -> &U {
        self.0 .0.as_ref()
    }
}

impl<U: 'static> FromRequest for UserWrapAuth<U>
where
    U: UserMinix,
{
    type Error = Error;
    type Future = Pin<Box<dyn Future<Output = Result<Self, Self::Error>>>>;

    #[inline]
    fn from_request(req: &HttpRequest, pl: &mut Payload) -> Self::Future {
        let userwrap_future = UserWrap::from_request(req, pl);
        Box::pin(async move {
            let userwrap = userwrap_future.await?;
            let userwrapauth = Self(userwrap);
            let user = userwrapauth.as_ref();
            if user.is_actived() && user.is_authenticated() {
                return Ok(userwrapauth);
            } else {
                return Err(
                    InternalError::new("No authentication.", StatusCode::UNAUTHORIZED).into(),
                );
            }
        })
    }
}