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
189
190
191
192
193
194
195
196
197
198
199
200
use actix_web::http::{header, header::SET_COOKIE, HeaderValue};
use actix_web::HttpMessage;
use actix_web::{
    dev::{ServiceRequest, ServiceResponse},
    Error, HttpRequest, HttpResponse,
};

use time::{Duration, OffsetDateTime};

use actix_web::cookie::{Cookie, CookieJar, Key, SameSite};
use serde::{Deserialize, Serialize};

use crypto::sha2::Sha512;

use crypto::digest::Digest;

use crate::loginmanager::{DecodeRequest, LoginInfo, LoginState};

/// use cookie as session to storage the info of user key.
pub struct CookieSession {
    key: Key,
    name: String,
    path: String,
    domain: Option<String>,
    secure: bool,
    http_only: bool,
    max_age: Option<Duration>,
    expires_in: Option<Duration>,
    same_site: Option<SameSite>,
}

fn __create_identifier(request: &ServiceRequest) -> String {
    let mut sha512 = Sha512::new();
    if let Some(addr) = actix_web::dev::ConnectionInfo::get(request.head(), request.app_config())
        .realip_remote_addr()
    {
        if let Some(ip) = addr.split(":").next() {
            sha512.input_str(ip);
        };
    }
    if let Some(agent) = request.headers().get(header::USER_AGENT) {
        if let Ok(agent) = agent.to_str() {
            sha512.input_str(agent);
        };
    };
    return sha512.result_str();
}

fn _create_identifier(request: &HttpRequest) -> String {
    let mut sha512 = Sha512::new();
    if let Some(addr) = actix_web::dev::ConnectionInfo::get(request.head(), request.app_config())
        .realip_remote_addr()
    {
        if let Some(ip) = addr.split(":").next() {
            sha512.input_str(ip);
        };
    }
    if let Some(agent) = request.headers().get(header::USER_AGENT) {
        if let Ok(agent) = agent.to_str() {
            sha512.input_str(agent);
        };
    };
    return sha512.result_str();
}

#[derive(Serialize, Deserialize)]
struct Session {
    id: String,
    user_id: Option<String>,
}

impl CookieSession {
    pub fn new(key: &[u8]) -> Self {
        Self {
            key: Key::derive_from(key),
            name: "_session".to_owned(),
            path: "/".to_owned(),
            domain: None,
            secure: true,
            http_only: true,
            max_age: None,
            expires_in: None,
            same_site: None,
        }
    }

    pub fn name(mut self, name: &'static str) -> Self {
        self.name = name.to_owned();
        self
    }

    pub fn secure(mut self, secure: bool) -> Self {
        self.secure = secure;
        self
    }

    pub fn http_only(mut self, http_only: bool) -> Self {
        self.http_only = http_only;
        self
    }

    pub fn domain(mut self, domain: Option<String>) -> Self {
        self.domain = domain;
        self
    }

    pub fn max_age(mut self, max_age: Option<Duration>) -> Self {
        self.max_age = max_age;
        self
    }

    pub fn expires_in(mut self, expires_in: Option<Duration>) -> Self {
        self.expires_in = expires_in;
        self
    }

    pub fn same_site(mut self, same_site: Option<SameSite>) -> Self {
        self.same_site = same_site;
        self
    }
}

impl DecodeRequest for CookieSession {
    fn decode(&self, req: &ServiceRequest) -> Option<String> {
        if let Some(cookie) = req.cookie(&self.name) {
            let mut jar = CookieJar::new();
            jar.add_original(cookie.clone());
            let cookie_opt = jar.private(&self.key).get(&self.name);
            if let Some(cookie) = cookie_opt {
                if let Ok(val) = serde_json::from_str::<Session>(cookie.value()) {
                    if val.id == __create_identifier(&req) {
                        return val.user_id;
                    };
                }
            }
        };
        None
    }

    fn update_<B>(&self, res: &mut ServiceResponse<B>) -> Result<(), Error> {
        let key = match res.request().extensions().get::<LoginInfo>() {
            Some(LoginInfo {
                key_str,
                state: LoginState::Login | LoginState::Update,
            }) => {
                key_str.clone()
            }
            Some(LoginInfo {
                state: LoginState::Logout,
                ..
            }) => Some("".to_owned()),
            _ => None,
        };
        let key = match key {
            Some(x) if x == "".to_owned() => None,
            Some(key) => Some(key),
            _ => return Ok(()),
        };

        let session = Session {
            id: _create_identifier(res.request()),
            user_id: key,
        };

        let value = serde_json::to_string(&session).map_err(|_| ())?;

        let mut cookie = Cookie::new(self.name.clone(), value);

        cookie.set_path(self.path.clone());
        cookie.set_secure(self.secure);
        cookie.set_http_only(self.http_only);

        if let Some(ref domain) = self.domain {
            cookie.set_domain(domain.clone());
        }

        if let Some(expires_in) = self.expires_in {
            cookie.set_expires(OffsetDateTime::now_utc() + expires_in);
        }

        if let Some(max_age) = self.max_age {
            cookie.set_max_age(max_age);
        }

        if let Some(same_site) = self.same_site {
            cookie.set_same_site(same_site);
        }

        let mut jar = CookieJar::new();

        jar.private(&self.key).add(cookie);

        for cookie in jar.delta() {
            let val = HeaderValue::from_str(&cookie.encoded().to_string()).map_err(|_| ())?;
            res.headers_mut().append(SET_COOKIE, val);
        }

        Ok(())
    }
}