aboutsummaryrefslogtreecommitdiffstats
path: root/src/web_server/front_end_cookie.rs
blob: 020793335f75e8e60602528edbeca77dacabb92c (plain) (blame)
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
use futures::future::{ok, Ready};

use actix_web::{
    dev::Payload,
    http::header::{COOKIE, LOCATION, SET_COOKIE},
    FromRequest, HttpRequest, HttpResponse,
};
use serde::Deserialize;

#[derive(PartialEq, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum FrontEnd {
    Lazy,
    Tmtu,
}

impl FrontEnd {
    const COOKIE_NAME: &'static str = "front-end";

    fn cookie(&self) -> String {
        let name = match self {
            FrontEnd::Lazy => "lazy",
            FrontEnd::Tmtu => "tmtu",
        };

        format!("{}={}", Self::COOKIE_NAME, name)
    }
}

impl FromRequest for FrontEnd {
    type Error = ();
    type Future = Ready<Result<Self, ()>>;
    type Config = ();

    fn from_request(req: &HttpRequest, _payload: &mut Payload) -> Self::Future {
        for header in req.headers().get_all(COOKIE) {
            if let Ok(value) = header.to_str() {
                for c in value.split(';').map(|s| s.trim()) {
                    let mut split = c.split('=');
                    if Some(Self::COOKIE_NAME) == split.next() {
                        match split.next() {
                            Some("lazy") => return ok(FrontEnd::Lazy),
                            Some("tmtu") => return ok(FrontEnd::Tmtu),
                            _ => (),
                        }
                    }
                }
            }
        }

        ok(FrontEnd::Lazy)
    }
}

pub fn set_front_end(front: FrontEnd) -> HttpResponse {
    HttpResponse::Found()
        .header(SET_COOKIE, front.cookie())
        .header(LOCATION, "/")
        .finish()
}