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
use iron::{self, status, IronError, Response};

use std::convert::From;
use std::error::Error;
use std::fmt;

/// The type of Errors used in this middleware.
///
/// Used to convey extra information inside an `iron::IronError`
#[derive(Debug)]
pub enum CsrfError {
    /// No token was provided with the request
    TokenMissing,

    /// A token was provided, but it didn't match the cookie
    TokenInvalid,

    /// No cookie was provided with the request
    CookieMissing,

    /// An error was encountered while generating a random token
    NoRandom(::std::io::Error),
}

impl CsrfError {
    fn http_status(&self) -> status::Status {
        use CsrfError::*;

        match *self {
            NoRandom(_) => status::InternalServerError,
            _ => status::BadRequest,
        }
    }
}

impl Error for CsrfError {
    fn description(&self) -> &str {
        use CsrfError::*;

        match *self {
            TokenMissing => "csrf token is missing",
            TokenInvalid => "csrf token is invalid",
            CookieMissing => "csrf cookie is missing",
            NoRandom(_) => "failed to generate random bytes",
        }
    }

    fn cause(&self) -> Option<&Error> {
        match *self {
            CsrfError::NoRandom(ref x) => Some(x),
            _ => None,
        }
    }
}

impl fmt::Display for CsrfError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.description())
    }
}

impl From<CsrfError> for iron::IronError {
    fn from(f: CsrfError) -> Self {
        IronError {
            response: Response::with((f.http_status(), f.description())),
            error: Box::new(f),
        }
    }
}