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
|
use axum::extract::State;
use chrono::{DateTime, Duration, Utc};
use entity::users::{self};
use sea_orm::{
ActiveModelTrait, ActiveValue::Set, ColumnTrait, EntityTrait, IntoActiveModel, ModelTrait,
QueryFilter,
};
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
use utoipa_axum::{router::OpenApiRouter, routes};
use crate::{
ApiResult, AppState, ClientError, GlobalResponses, JwtClaims, ServerError, SuccessResponse,
create_jwt, create_password,
extract::{ApiJson, Auth},
tags::ACCOUNT,
validate_password,
};
#[derive(Serialize, ToSchema)]
#[schema(description = "Account information")]
struct Account {
#[schema(examples(1))]
id: i64,
#[schema(examples("john_doe", "ivanov_ivan"))]
username: String,
#[schema(examples("John", "Иван"))]
first_name: String,
#[schema(examples("Doe", "Иванов"))]
last_name: String,
}
#[derive(Serialize, ToSchema)]
#[schema(description = "Authorization token information")]
struct Token {
token: String,
expired_at: DateTime<Utc>,
}
#[derive(Deserialize, ToSchema)]
#[schema(description = "Account register data")]
struct RegisterRequest {
#[schema(examples("john_doe", "ivanov_ivan"))]
username: String,
#[schema(examples("secret-password"))]
password: String,
#[schema(examples("John", "Иван"))]
first_name: String,
#[schema(examples("Doe", "Иванов"))]
last_name: String,
}
#[derive(Deserialize, ToSchema, Default)]
#[serde(rename_all = "UPPERCASE")]
#[schema(description = "Account token life time")]
enum TokenLifetime {
Day = 1,
#[default]
Week = 7,
Month = 31,
}
#[derive(Deserialize, ToSchema)]
#[schema(description = "Account login data")]
struct LoginRequest {
#[schema(examples("john_doe", "ivanov_ivan"))]
username: String,
#[schema(examples("secret-password"))]
password: String,
#[serde(default)]
#[schema(default = "WEEK")]
token_lifetime: TokenLifetime,
}
#[derive(Deserialize, ToSchema)]
#[schema(description = "Change account password data")]
struct ChangePasswordRequest {
#[schema(examples("secret-password"))]
old_password: String,
#[schema(examples("super-secret-password"))]
new_password: String,
}
#[derive(Deserialize, ToSchema)]
#[schema(description = "Account delete data")]
struct DeleteUserRequest {
#[schema(examples("secret-password"))]
password: String,
}
#[utoipa::path(
get,
path = "/me",
tag = ACCOUNT,
summary = "Get me",
responses(
(
status = 200, body = SuccessResponse<Account>,
description = "Success response with your account data"
),
GlobalResponses
),
security(("auth" = [])),
)]
async fn me(Auth(user): Auth) -> ApiResult<Account> {
return Ok(SuccessResponse::ok(Account {
id: user.id,
username: user.username,
first_name: user.first_name,
last_name: user.last_name,
}));
}
#[utoipa::path(
post,
path = "/register",
tag = ACCOUNT,
summary = "Register",
responses(
(
status = 200, body = SuccessResponse<Account>,
description = "Success response with created account data"
),
GlobalResponses
),
request_body = RegisterRequest
)]
async fn register(
State(state): State<AppState>,
ApiJson(req): ApiJson<RegisterRequest>,
) -> ApiResult<Account> {
let user_exists = users::Entity::find()
.filter(users::Column::Username.eq(&req.username))
.one(&state.db)
.await?
.is_some();
if user_exists {
return Err(ClientError::UserAlreadyExists {
username: req.username,
}
.into());
}
let user = users::ActiveModel {
username: Set(req.username),
password_hash: Set(create_password(&req.password)?),
password_issue_date: Set(Utc::now().naive_utc()),
first_name: Set(req.first_name),
last_name: Set(req.last_name),
..Default::default()
}
.insert(&state.db)
.await?;
Ok(SuccessResponse::ok(Account {
id: user.id,
username: user.username,
first_name: user.first_name,
last_name: user.last_name,
}))
}
#[utoipa::path(
post,
path = "/login",
tag = ACCOUNT,
summary = "Login",
responses(
(
status = 200, body = SuccessResponse<Token>,
description = "Success response with auth token data"
),
GlobalResponses
),
request_body = LoginRequest
)]
async fn login(
State(state): State<AppState>,
ApiJson(req): ApiJson<LoginRequest>,
) -> ApiResult<Token> {
let user = users::Entity::find()
.filter(users::Column::Username.eq(&req.username))
.one(&state.db)
.await?
.ok_or(ClientError::InvalidPassword)?;
if !validate_password(&req.password, &user.password_hash)? {
return Err(ClientError::InvalidPassword.into());
}
let expired_at = Utc::now() + Duration::days(req.token_lifetime as i64);
let token = create_jwt(
&JwtClaims {
sub: user.id,
iat: user.password_issue_date.and_utc().timestamp(),
exp: expired_at.timestamp(),
},
&state.secret,
)
.map_err(|e| ServerError::Token(e.to_string()))?;
Ok(SuccessResponse::ok(Token { token, expired_at }))
}
#[utoipa::path(
put,
path = "/change/password",
tag = ACCOUNT,
summary = "Change password",
request_body = ChangePasswordRequest,
responses(
(
status = 200, body = SuccessResponse<Account>,
description = "Success response with changed account data"
),
GlobalResponses
),
security(("auth" = []))
)]
async fn change_password(
State(state): State<AppState>,
Auth(user): Auth,
ApiJson(req): ApiJson<ChangePasswordRequest>,
) -> ApiResult<Account> {
if !validate_password(&req.old_password, &user.password_hash)? {
return Err(ClientError::InvalidPassword.into());
}
let mut active_user = user.into_active_model();
active_user.password_hash = Set(create_password(&req.new_password)?);
active_user.password_issue_date = Set(Utc::now().naive_utc());
let user = active_user.update(&state.db).await?;
Ok(SuccessResponse::ok(Account {
id: user.id,
username: user.username,
first_name: user.first_name,
last_name: user.last_name,
}))
}
#[utoipa::path(
delete,
path = "/delete",
tag = ACCOUNT,
summary = "Delete",
request_body = DeleteUserRequest,
responses(
(
status = 200, body = SuccessResponse<Account>,
description = "Success response with deleted account data"
),
GlobalResponses
),
security(("auth" = []))
)]
async fn delete(
State(state): State<AppState>,
Auth(user): Auth,
ApiJson(req): ApiJson<DeleteUserRequest>,
) -> ApiResult<Account> {
if !validate_password(&req.password, &user.password_hash)? {
return Err(ClientError::InvalidPassword.into());
}
user.clone().delete(&state.db).await?;
Ok(SuccessResponse::ok(Account {
id: user.id,
username: user.username,
first_name: user.first_name,
last_name: user.last_name,
}))
}
pub(crate) fn router() -> OpenApiRouter<AppState> {
OpenApiRouter::new()
.routes(routes!(me))
.routes(routes!(register))
.routes(routes!(login))
.routes(routes!(change_password))
.routes(routes!(delete))
}
|