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
use rocket::http::Status;
use rocket::request::{self, FromRequest, Request};
use rocket::Outcome;

//NOTE: we can use FormInput<'c>, url: &'c RawStr, for unvalidated data if/when we need it.
#[derive(Debug, FromForm)]
/// Incoming data from the web based form for a new comment.
pub struct FormInput {
    /// Comment from textarea.
    pub comment: String,
    /// Parent comment if any.
    pub parent: Option<i32>,
    /// Optional name.
    pub name: Option<String>,
    /// Optional email.
    pub email: Option<String>,
    /// Optional website.
    pub url: Option<String>,
    /// Title of post.
    pub title: String,
    /// Path of post.
    pub path: String,
}

impl FormInput {
    /// Yields the senders name with a default if is empty.
    pub fn sender_name(&self) -> String {
        self.name
            .to_owned()
            .unwrap_or_else(|| "anonymous".to_string())
    }

    /// Yields the senders email address with a default if is empty.
    pub fn sender_email(&self) -> String {
        self.email
            .to_owned()
            .unwrap_or_else(|| "noreply@dev.null".to_string())
    }
}

#[derive(Debug, FromForm)]
/// Incoming data from the web based form for an edited comment.
pub struct FormEdit {
    /// Comment from textarea.
    pub comment: String,
    /// Optional name.
    pub name: Option<String>,
    /// Optional email.
    pub email: Option<String>,
    /// Optional website.
    pub url: Option<String>,
}

/// Hash of the user which wants to edit/delete a comment.
#[derive(PartialEq)]
pub struct AuthHash(String);

impl<'a, 'r> FromRequest<'a, 'r> for AuthHash {
    type Error = ();

    fn from_request(request: &'a Request<'r>) -> request::Outcome<AuthHash, ()> {
        let keys: Vec<_> = request.headers().get("x-auth-hash").collect();
        if keys.len() != 1 {
            return Outcome::Failure((Status::BadRequest, ()));
        }

        let key = keys[0];
        Outcome::Success(AuthHash(key.to_string()))
    }
}

impl AuthHash {
    /// Checkhs if the current hash matches with the `compared` hash.
    pub fn matches(&self, compare: &str) -> bool {
        let &AuthHash(ref hash) = self;
        hash == compare
    }
}