about summary refs log tree commit diff
path: root/src/util.rs
blob: a3cc0641715b1bd696b0ff568c15fe4c9ac5f230 (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
use core::fmt;
use std::ops::Deref;

use axum::{
	async_trait,
	extract::FromRequestParts,
	http::{header, request::Parts, HeaderName, StatusCode},
	RequestPartsExt,
};
use sha2::{Digest, Sha256};
use time::{format_description::FormatItem, macros::format_description, OffsetDateTime};

#[derive(Debug, Clone)]
pub struct RemoteIp(String);

#[async_trait]
impl<S> FromRequestParts<S> for RemoteIp
where
	S: Send + Sync,
{
	type Rejection = (StatusCode, &'static str);

	async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
		if let Some(forwarded_for) = parts
			.headers
			.get(HeaderName::from_static("x-forwarded-for"))
		{
			match forwarded_for.to_str() {
				Err(_e) => Err((StatusCode::INTERNAL_SERVER_ERROR, "server error")),
				Ok(remoteip) => Ok(Self(remoteip.to_owned())),
			}
		} else {
			Err((StatusCode::INTERNAL_SERVER_ERROR, "server error"))
		}
	}
}

impl Deref for RemoteIp {
	type Target = str;

	fn deref(&self) -> &Self::Target {
		&self.0
	}
}

const FMT: &[FormatItem<'_>] = format_description!("[year]-[month]-[day]");

#[derive(Debug, Copy, Clone)]
pub struct SessionId([u8; 4]);

#[async_trait]
impl<S> FromRequestParts<S> for SessionId
where
	S: Send + Sync,
{
	type Rejection = (StatusCode, &'static str);

	async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
		let remote = parts
			.extract::<RemoteIp>()
			.await
			.map(|rip| rip.0)
			.unwrap_or(String::from("127.0.0.1"));

		let agent = parts
			.headers
			.get(header::USER_AGENT)
			.and_then(|ua| ua.to_str().ok())
			.unwrap_or("unknown");

		let date = OffsetDateTime::now_local().unwrap_or_else(|_| OffsetDateTime::now_utc());

		let string = format!("{remote} - {agent} - {}", date.format(FMT).unwrap());

		let mut hasher = Sha256::new();
		hasher.update(string.as_bytes());
		let hash = hasher.finalize();
		let slc: [u8; 4] = hash.as_slice()[0..4].try_into().unwrap();

		Ok(Self(slc))
	}
}

impl fmt::Display for SessionId {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		for byte in self.0.as_slice() {
			write!(f, "{byte:02X}")?;
		}

		Ok(())
	}
}

#[derive(Debug, Clone)]
pub struct Referer(String);

#[async_trait]
impl<S> FromRequestParts<S> for Referer
where
	S: Send + Sync,
{
	type Rejection = (StatusCode, &'static str);

	async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
		if let Some(refer) = parts.headers.get(header::REFERER) {
			match refer.to_str() {
				Err(_e) => Err((StatusCode::INTERNAL_SERVER_ERROR, "server error")),
				Ok(refer) => match url::Url::parse(refer) {
					Err(_e) => Err((
						StatusCode::INTERNAL_SERVER_ERROR,
						"failed to parse referer url",
					)),
					Ok(url) => match url.host_str() {
						None => Err((StatusCode::INTERNAL_SERVER_ERROR, "referer url had no host")),
						Some(str) => Ok(Referer(str.to_owned())),
					},
				},
			}
		} else {
			Err((StatusCode::INTERNAL_SERVER_ERROR, "server error"))
		}
	}
}

impl Deref for Referer {
	type Target = str;

	fn deref(&self) -> &Self::Target {
		&self.0
	}
}

impl fmt::Display for Referer {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		write!(f, "{}", self.0)
	}
}