aboutsummaryrefslogtreecommitdiff
path: root/examples/csrf/src/main.rs
blob: 10486890e897e97033987ec2c792c75e948ab9f1 (plain)
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
use std::convert::Infallible;
use hyper::service::{service_fn, make_service_fn};
use hyper::{Method, Server, StatusCode, Body};
use hyper::http::request::Parts;
use hyper::http::response::Builder;
use serde::Deserialize;
use sputnik::{mime, request::{SputnikParts, SputnikBody}, response::SputnikBuilder};
use sputnik::request::CsrfProtectedFormError;

type Response = hyper::Response<Body>;

#[derive(thiserror::Error, Debug)]
enum Error {
    #[error("page not found")]
    NotFound(String),
    #[error("{0}")]
    CsrfError(#[from] CsrfProtectedFormError)
}

fn render_error(err: Error) -> (StatusCode, String) {
    match err {
        Error::NotFound(msg) => (StatusCode::NOT_FOUND, msg),
        Error::CsrfError(err) => (StatusCode::BAD_REQUEST, err.to_string()),
    }
}

async fn route(req: &mut Parts, body: Body) -> Result<Response, Error> {
    match (&req.method, req.uri.path()) {
        (&Method::GET, "/form") => Ok(get_form(req)),
        (&Method::POST, "/form") => post_form(req, body).await,
        _ => return Err(Error::NotFound("page not found".to_owned()))
    }
}

fn get_form(req: &mut Parts) -> Response {
    let mut response = Builder::new();
    let csrf_input = req.csrf_token(&mut response).html_input();
    response.content_type(mime::TEXT_HTML).body(
        format!("<form method=post>
        <input name=text>{}<button>Submit</button></form>", csrf_input).into()
    ).unwrap()
}

#[derive(Deserialize)]
struct FormData {text: String}

async fn post_form(req: &mut Parts, body: Body) -> Result<Response, Error> {
    let msg: FormData = body.into_form_csrf(req).await?;
    Ok(Builder::new().body(
        format!("hello {}", msg.text).into()
    ).unwrap())
}

async fn service(req: hyper::Request<hyper::Body>) -> Result<hyper::Response<hyper::Body>, Infallible> {
    let (mut parts, body) = req.into_parts();
    match route(&mut parts, body).await {
        Ok(res) => Ok(res),
        Err(err) => {
            let (code, message) = render_error(err);
            // you can easily wrap or log errors here
            Ok(hyper::Response::builder().status(code).body(message.into()).unwrap())
        }
    }
}

#[tokio::main]
async fn main() {
    let service = make_service_fn(move |_| {
        async move {
            Ok::<_, hyper::Error>(service_fn(move |req| {
                service(req)
            }))
        }
    });

    let addr = ([127, 0, 0, 1], 8000).into();
    let server = Server::bind(&addr).serve(service);
    println!("Listening on http://{}", addr);
    server.await;
}