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
|
use axum::{response::Response, routing::post, Router};
use serde::Deserialize;
use time::{Duration, OffsetDateTime};
use tower_cookies::{Cookie, Cookies};
use crate::{
public::docs::{EndpointDocumentation, EndpointMethod},
types::{
extract::{AuthorizedUser, Check, CheckResult, Database, Json, Log},
http::ResponseCode,
session::Session,
user::User,
},
};
pub const AUTH_REGISTER: EndpointDocumentation = EndpointDocumentation {
uri: "/api/auth/register",
method: EndpointMethod::Post,
description: "Registeres a new account",
body: Some(
r#"
{
"firstname": "[Object]",
"lastname": "object]",
"email": "object@object.object",
"password": "i love js",
"gender": "object",
"day": 1,
"month": 1,
"year": 1970
}
"#,
),
responses: &[
(201, "Successfully registered new user"),
(400, "Body does not match parameters"),
],
cookie: None,
};
#[derive(Deserialize, Debug)]
pub struct RegistrationRequet {
pub firstname: String,
pub lastname: String,
pub email: String,
pub password: String,
pub gender: String,
pub day: u8,
pub month: u8,
pub year: u32,
}
impl Check for RegistrationRequet {
fn check(&self) -> CheckResult {
Self::assert_length(
&self.firstname,
1,
20,
"First name can only by 1-20 characters long",
)?;
Self::assert_length(
&self.lastname,
1,
20,
"Last name can only by 1-20 characters long",
)?;
Self::assert_length(&self.email, 1, 50, "Email can only by 1-50 characters long")?;
Self::assert_length(
&self.password,
1,
50,
"Password can only by 1-50 characters long",
)?;
Self::assert_length(
&self.gender,
1,
100,
"Gender can only by 1-100 characters long",
)?;
Self::assert_range(
u64::from(self.day),
1,
255,
"Birthday day can only be between 1-255",
)?;
Self::assert_range(
u64::from(self.month),
1,
255,
"Birthday month can only be between 1-255",
)?;
Self::assert_range(
u64::from(self.year),
1,
4_294_967_295,
"Birthday year can only be between 1-4294967295",
)?;
Ok(())
}
}
async fn register(
cookies: Cookies,
Database(db): Database,
Json(body): Json<RegistrationRequet>,
) -> Response {
let user = match User::new(&db, body) {
Ok(user) => user,
Err(err) => return err,
};
let session = match Session::new(&db, user.user_id) {
Ok(session) => session,
Err(err) => return err,
};
let mut now = OffsetDateTime::now_utc();
now += Duration::weeks(52);
let mut cookie = Cookie::new("auth", session.token);
cookie.set_secure(false);
cookie.set_http_only(false);
cookie.set_expires(now);
cookie.set_path("/");
cookies.add(cookie);
ResponseCode::Created.text("Successfully created new user, auth cookie is returned")
}
pub const AUTH_LOGIN: EndpointDocumentation = EndpointDocumentation {
uri: "/api/auth/login",
method: EndpointMethod::Post,
description: "Logs into an existing account",
body: Some(
r#"
{
"email": "object@object.object",
"password": "i love js"
}
"#,
),
responses: &[
(200, "Successfully logged in, auth cookie is returned"),
(
400,
"Body does not match parameters, or invalid email password combination",
),
],
cookie: None,
};
#[derive(Deserialize)]
struct LoginRequest {
email: String,
password: String,
}
impl Check for LoginRequest {
fn check(&self) -> CheckResult {
Ok(())
}
}
async fn login(
cookies: Cookies,
Database(db): Database,
Json(body): Json<LoginRequest>,
) -> Response {
let Ok(user) = User::from_email(&db, &body.email) else {
return ResponseCode::BadRequest.text("Email is not registered")
};
if user.password != body.password {
return ResponseCode::BadRequest.text("Password is not correct");
}
let session = match Session::new(&db, user.user_id) {
Ok(session) => session,
Err(err) => return err,
};
let mut now = OffsetDateTime::now_utc();
now += Duration::weeks(52);
let mut cookie = Cookie::new("auth", session.token);
cookie.set_secure(false);
cookie.set_http_only(false);
cookie.set_expires(now);
cookie.set_path("/");
cookies.add(cookie);
ResponseCode::Success.text("Successfully logged in")
}
pub const AUTH_LOGOUT: EndpointDocumentation = EndpointDocumentation {
uri: "/api/auth/logout",
method: EndpointMethod::Post,
description: "Logs out of a logged in account",
body: None,
responses: &[
(200, "Successfully logged out"),
(401, "Unauthorized"),
(500, "Failed to log out user"),
],
cookie: None,
};
async fn logout(
cookies: Cookies,
AuthorizedUser(user): AuthorizedUser,
Database(db): Database,
_: Log,
) -> Response {
cookies.remove(Cookie::new("auth", ""));
if let Err(err) = Session::delete(&db, user.user_id) {
return err;
}
ResponseCode::Success.text("Successfully logged out")
}
pub fn router() -> Router {
Router::new()
.route("/register", post(register))
.route("/login", post(login))
.route("/logout", post(logout))
}
|