summaryrefslogtreecommitdiff
path: root/src/types/extract.rs
blob: a76eac4dd0eefa35e29fc4b60a52e60568143ab5 (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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
use std::{
    io::{Cursor, Read},
    net::{IpAddr, SocketAddr},
};

use axum::{
    async_trait,
    body::HttpBody,
    extract::{ConnectInfo, FromRequest, FromRequestParts},
    http::{header::USER_AGENT, request::Parts, Request},
    response::Response,
    BoxError, RequestExt, middleware::Next,
};
use bytes::Bytes;
use image::{io::Reader, DynamicImage, ImageFormat};
use serde::de::DeserializeOwned;
use tokio::sync::Mutex;
use tower_cookies::Cookies;

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

pub struct RequestIp(pub IpAddr);

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

    async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self> {
        let headers = &parts.headers;

        let forwardedfor = headers
            .get("x-forwarded-for")
            .and_then(|h| h.to_str().ok())
            .and_then(|h| {
                h.split(',')
                    .rev()
                    .find_map(|s| s.trim().parse::<IpAddr>().ok())
            });

        if let Some(forwardedfor) = forwardedfor {
            return Ok(Self(forwardedfor));
        }

        let realip = headers
            .get("x-real-ip")
            .and_then(|hv| hv.to_str().ok())
            .and_then(|s| s.parse::<IpAddr>().ok());

        if let Some(realip) = realip {
            return Ok(Self(realip));
        }

        let realip = headers
            .get("x-real-ip")
            .and_then(|hv| hv.to_str().ok())
            .and_then(|s| s.parse::<IpAddr>().ok());

        if let Some(realip) = realip {
            return Ok(Self(realip));
        }

        let info = parts.extensions.get::<ConnectInfo<SocketAddr>>();

        if let Some(info) = info {
            return Ok(Self(info.0.ip()));
        }

        Err(ResponseCode::Forbidden.text("You have no ip"))
    }
}

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::<Cookies>::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 Some(db) = parts.extensions.get::<DatabaseExtention>() else {
            return Err(ResponseCode::InternalServerError.text("Could not connect to database"))
        };

        let db = db.0.lock().await;

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

        let Ok(user) = User::from_user_id(&db, 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 AdminUser;

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

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

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

        let check = admin::get_secret().await;

        if check != secret.value() {
            return Err(ResponseCode::Unauthorized.text("Auth token invalid"));
        }

        Ok(Self)
    }
}

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 Png(pub DynamicImage);

#[async_trait]
impl<S, B> FromRequest<S, B> for Png
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> {
        let bytes = match read_body(req, state).await {
            Ok(body) => body,
            Err(err) => return Err(err),
        };

        let mut reader = Reader::new(Cursor::new(bytes));
        reader.set_format(ImageFormat::Png);

        let Ok(img) = reader.decode()  else {
            return Err(ResponseCode::BadRequest.text("Failed to decode png image"))
        };

        Ok(Self(img))
    }
}

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("Body does not match paramaters"))
        };

        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 struct UserAgent(pub String);

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

    async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self> {
        let agent = parts.headers.get(USER_AGENT);

        let Some(agent) = agent else {
            return Err(ResponseCode::BadRequest.text("Bad Request"));
        };

        let Ok(agent) = agent.to_str() else {
            return Err(ResponseCode::BadRequest.text("Bad Request"));
        };

        Ok(Self(agent.to_string()))
    }
}

pub struct DatabaseExtention(pub Mutex<database::Database>);
pub struct Database(pub database::Database);

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

    async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self> {
        let db = parts.extensions.remove::<DatabaseExtention>();
        let Some(db) = db else {
            return Err(ResponseCode::InternalServerError.text("Database is not loaded"))
        };

        Ok(Self(db.0.into_inner()))
    }
}

pub async fn connect<B>(mut req: Request<B>, next: Next<B>) -> Response
where
    B: Send,
{
    if let Ok(db) = database::Database::connect() {
        let ex = DatabaseExtention(Mutex::new(db));
        req.extensions_mut().insert(ex);
    }

    next.run(req).await
}

async fn read_body<S, B>(mut req: Request<B>, state: &S) -> Result<Vec<u8>>
where
    B: HttpBody + Sync + Send + 'static,
    B::Data: Send,
    B::Error: Into<BoxError>,
    S: Send + Sync,
{
    let Ok(RequestIp(ip)) = req.extract_parts::<RequestIp>().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 {
        return Err(ResponseCode::BadRequest.text("Request can be at most 512kb"));
    };

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

    Ok(bytes.bytes().flatten().collect())
}

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(RequestIp(ip)) = req.extract_parts::<RequestIp>().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 {
        return Err(ResponseCode::BadRequest.text("Request can be at most 512kb"));
    };

    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);