summaryrefslogtreecommitdiff
path: root/src/types/extract.rs
blob: 4d92a3b6e34d92acf2b782e497876e514b0fb979 (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
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
use std::io::Read;

use axum::{
    async_trait,
    body::HttpBody,
    extract::{FromRequest, FromRequestParts},
    headers::Cookie,
    http::{request::Parts, Request},
    response::Response,
    BoxError, RequestExt, TypedHeader,
};
use axum_client_ip::ClientIp;
use bytes::Bytes;
use serde::de::DeserializeOwned;

use crate::{
    console,
    types::{
        http::{ResponseCode, Result},
        session::Session,
        user::User,
    },
};

pub struct AuthorizedUser(pub User);

#[async_trait]
impl<S> FromRequestParts<S> for AuthorizedUser
where
    S: Send + Sync,
{
    type Rejection = Response;

    async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self> {
        let Ok(Some(cookies)) = Option::<TypedHeader<Cookie>>::from_request_parts(parts, state).await else {
            return Err(ResponseCode::Forbidden.text("No cookies provided"))
        };

        let Some(token) = cookies.get("auth") else {
            return Err(ResponseCode::Forbidden.text("No auth token provided"))
        };

        let Ok(session) = Session::from_token(token) else {
            return Err(ResponseCode::Unauthorized.text("Auth token invalid"))
        };

        let Ok(user) = User::from_user_id(session.user_id, true)  else {
            tracing::error!("Valid token but no valid user");
            return Err(ResponseCode::InternalServerError.text("Valid token but no valid user"))
        };

        Ok(Self(user))
    }
}

pub struct Log;

#[async_trait]
impl<S, B> FromRequest<S, B> for Log
where
    B: HttpBody + Sync + Send + 'static,
    B::Data: Send,
    B::Error: Into<BoxError>,
    S: Send + Sync,
{
    type Rejection = Response;

    async fn from_request(req: Request<B>, state: &S) -> Result<Self> {
        parse_body(req, state).await?;
        Ok(Self)
    }
}

pub struct Json<T>(pub T);

#[async_trait]
impl<T, S, B> FromRequest<S, B> for Json<T>
where
    T: DeserializeOwned + Check,
    B: HttpBody + Sync + Send + 'static,
    B::Data: Send,
    B::Error: Into<BoxError>,
    S: Send + Sync,
{
    type Rejection = Response;

    async fn from_request(req: Request<B>, state: &S) -> Result<Self> {
        let body = match parse_body(req, state).await {
            Ok(body) => body,
            Err(err) => return Err(err),
        };

        let Ok(value) = serde_json::from_str::<T>(&body) else {
            return Err(ResponseCode::BadRequest.text("Invalid request body"))
        };

        if let Err(msg) = value.check() {
            return Err(ResponseCode::BadRequest.text(&msg));
        }

        Ok(Self(value))
    }
}

pub type CheckResult = std::result::Result<(), String>;

pub trait Check {
    fn check(&self) -> CheckResult;

    fn assert_length(string: &str, min: usize, max: usize, message: &str) -> CheckResult {
        if string.len() < min || string.len() > max {
            return Err(message.to_string());
        }
        Ok(())
    }

    fn assert_range(number: u64, min: u64, max: u64, message: &str) -> CheckResult {
        if number < min || number > max {
            return Err(message.to_string());
        }
        Ok(())
    }
}

pub async fn parse_body<S, B>(mut req: Request<B>, state: &S) -> Result<String>
where
    B: HttpBody + Sync + Send + 'static,
    B::Data: Send,
    B::Error: Into<BoxError>,
    S: Send + Sync,
{
    let Ok(ClientIp(ip)) = req.extract_parts::<ClientIp>().await else {
        tracing::error!("Failed to read client ip");
        return Err(ResponseCode::InternalServerError.text("Failed to read client ip"));
    };

    let method = req.method().clone();
    let uri = req.uri().clone();
    let path = req
        .extensions()
        .get::<RouterURI>()
        .map_or("", |path| path.0);

    let Ok(bytes) = Bytes::from_request(req, state).await else {
        tracing::error!("Failed to read request body");
        return Err(ResponseCode::InternalServerError.text("Failed to read request body"));
    };

    let Ok(body) = String::from_utf8(bytes.bytes().flatten().collect()) else {
        return Err(ResponseCode::BadRequest.text("Invalid utf8 body"))
    };

    console::log(
        ip,
        method,
        uri,
        Some(path.to_string()),
        Some(body.to_string()),
    )
    .await;

    Ok(body)
}

#[derive(Clone)]
pub struct RouterURI(pub &'static str);