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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
#[cfg(feature = "plugin_utoipa")]
use crate::auth::{
AuthMessageResponse, AuthTokenResponse, JwtSecurityAddon, UserSessionJson, UserSessionResponse,
};
use actix_http::StatusCode;
use actix_web::cookie::{Cookie, SameSite};
use actix_web::{delete, get, post, web, Error as AWError, Result};
use actix_web::{
web::{Data, Json, Path, Query},
HttpRequest, HttpResponse,
};
use serde_json::json;
#[cfg(feature = "plugin_utoipa")]
use utoipa::OpenApi;
use crate::auth::{
controller,
controller::{
ActivationInput, ChangeInput, ForgotInput, LoginInput, RegisterInput, ResetInput,
COOKIE_NAME,
},
Auth, PaginationParams, ID,
};
use crate::Database;
use crate::Mailer;
#[cfg_attr(feature = "plugin_utoipa", utoipa::path(
context_path = "/api/auth",
params(PaginationParams),
responses(
(status = 200, description = "success, returns a json payload with all the sessions belonging to the authenticated user", body = UserSessionResponse),
(status = 401, description = "Error: Unauthorized"),
(status = 500, description = "Could not fetch sessions."),
),
tag = "Sessions",
security ( ("JWT" = []))
))]
#[get("/sessions")]
async fn sessions(
db: Data<Database>,
auth: Auth,
Query(info): Query<PaginationParams>,
) -> Result<HttpResponse> {
let result =
web::block(move || controller::get_sessions(db.into_inner().as_ref(), &auth, &info))
.await?;
match result {
Ok(sessions) => Ok(HttpResponse::Ok().json(sessions)),
Err((status_code, error_message)) => Ok(HttpResponse::build(
StatusCode::from_u16(status_code as u16).unwrap(),
)
.body(json!({ "message": error_message }).to_string())),
}
}
#[cfg_attr(feature = "plugin_utoipa", utoipa::path(
context_path = "/api/auth",
responses(
(status = 200, description = "Deleted", body = AuthMessageResponse),
(status = 401, description = "User not authenticated"),
(status = 404, description = "User session could not be found, or does not belong to authenticated user.", body = AuthMessageResponse),
(status = 500, description = "Internal Error.", body = AuthMessageResponse),
(status = 500, description = "Could not delete session.", body = AuthMessageResponse),
),
tag = "Sessions",
security ( ("JWT" = []))
))]
#[delete("/sessions/{id}")]
async fn destroy_session(
db: Data<Database>,
item_id: Path<ID>,
auth: Auth,
) -> Result<HttpResponse> {
let result =
web::block(move || controller::destroy_session(&db, &auth, item_id.into_inner())).await?;
match result {
Ok(_) => Ok(
HttpResponse::build(StatusCode::OK).body(json!({"message": "Deleted."}).to_string())
),
Err((status_code, error_message)) => Ok(HttpResponse::build(
StatusCode::from_u16(status_code as u16).unwrap(),
)
.body(json!({ "message": error_message }).to_string())),
}
}
#[cfg_attr(feature = "plugin_utoipa", utoipa::path(
context_path = "/api/auth",
responses(
(status = 200, description = "Deleted", body = AuthMessageResponse),
(status = 401, description = "User not authenticated"),
(status = 500, description = "Could not delete sessions.", body = AuthMessageResponse),
),
tag = "Sessions",
security ( ("JWT" = []))
))]
#[delete("/sessions")]
async fn destroy_sessions(db: Data<Database>, auth: Auth) -> Result<HttpResponse, AWError> {
let result = web::block(move || controller::destroy_sessions(&db, &auth)).await?;
match result {
Ok(_) => Ok(
HttpResponse::build(StatusCode::OK).body(json!({"message": "Deleted."}).to_string())
),
Err((status_code, error_message)) => Ok(HttpResponse::build(
StatusCode::from_u16(status_code as u16).unwrap(),
)
.body(json!({ "message": error_message }).to_string())),
}
}
#[cfg_attr(feature = "plugin_utoipa", utoipa::path(
context_path = "/api/auth",
request_body(content = LoginInput, content_type = "application/json"),
responses(
(status = 200, description = "session created", body = AuthTokenResponse),
(status = 400, description = "'device' cannot be longer than 256 characters.", body = AuthMessageResponse),
(status = 400, description = "Account has not been activated.", body = AuthMessageResponse),
(status = 401, description = "Invalid credentials.", body = AuthMessageResponse),
(status = 500, description = "An internal server error occurred.", body = AuthMessageResponse),
(status = 500, description = "Could not create a session.", body = AuthMessageResponse),
),
tag = "Sessions",
))]
#[post("/login")]
async fn login(db: Data<Database>, Json(item): Json<LoginInput>) -> Result<HttpResponse, AWError> {
let result = web::block(move || controller::login(&db, &item)).await?;
match result {
Ok((access_token, refresh_token)) => Ok(HttpResponse::build(StatusCode::OK)
.cookie(
Cookie::build(COOKIE_NAME, refresh_token)
.secure(true)
.http_only(true)
.same_site(SameSite::Strict)
.finish(),
)
.body(json!({ "access_token": access_token }).to_string())),
Err((status_code, message)) => Ok(HttpResponse::build(
StatusCode::from_u16(status_code as u16).unwrap(),
)
.body(json!({ "message": message }).to_string())),
}
}
#[cfg_attr(feature = "plugin_utoipa", utoipa::path(
context_path = "/api/auth",
responses(
(status = 200, description = "deletes the \"refresh_token\" cookie"),
(status = 401, description = "Invalid session.", body = AuthMessageResponse),
(status = 401, description = "Could not delete session.", body = AuthMessageResponse),
),
tag = "Sessions",
))]
#[post("/logout")]
async fn logout(db: Data<Database>, req: HttpRequest) -> Result<HttpResponse, AWError> {
let refresh_token = req
.cookie(COOKIE_NAME)
.map(|cookie| String::from(cookie.value()));
let result =
web::block(move || controller::logout(&db, refresh_token.as_ref().map(|t| t.as_ref())))
.await?;
match result {
Ok(_) => {
let mut cookie = Cookie::named(COOKIE_NAME);
cookie.make_removal();
Ok(HttpResponse::Ok().cookie(cookie).finish())
}
Err((status_code, message)) => Ok(HttpResponse::build(
StatusCode::from_u16(status_code as u16).unwrap(),
)
.body(json!({ "message": message }).to_string())),
}
}
#[cfg_attr(feature = "plugin_utoipa", utoipa::path(
context_path = "/api/auth",
responses(
(status = 200, description = "uses the \"refresh_token\" cookie to give the user a new session", body=AuthTokenResponse),
(status = 401, description = "Invalid session.", body = AuthMessageResponse),
(status = 401, description = "Invalid token.", body = AuthMessageResponse),
),
tag = "Sessions",
))]
#[post("/refresh")]
async fn refresh(db: Data<Database>, req: HttpRequest) -> Result<HttpResponse, AWError> {
let refresh_token = req
.cookie(COOKIE_NAME)
.map(|cookie| String::from(cookie.value()));
let result =
web::block(move || controller::refresh(&db, refresh_token.as_ref().map(|t| t.as_ref())))
.await?;
match result {
Ok((access_token, refresh_token)) => Ok(HttpResponse::build(StatusCode::OK)
.cookie(
Cookie::build(COOKIE_NAME, refresh_token)
.secure(true)
.http_only(true)
.same_site(SameSite::Strict)
.finish(),
)
.body(json!({ "access_token": access_token }).to_string())),
Err((status_code, message)) => Ok(HttpResponse::build(
StatusCode::from_u16(status_code as u16).unwrap(),
)
.body(json!({ "message": message }).to_string())),
}
}
#[cfg_attr(feature = "plugin_utoipa", utoipa::path(
context_path = "/api/auth",
request_body(content = RegisterInput, content_type = "application/json"),
responses(
(status = 200, description = "Success, sends an email to the user with a link that will let them activate their account", body=AuthMessageResponse),
(status = 400, description = "Already registered.", body = AuthMessageResponse),
),
tag = "Users",
))]
#[post("/register")]
async fn register(
db: Data<Database>,
Json(item): Json<RegisterInput>,
mailer: Data<Mailer>,
) -> Result<HttpResponse, AWError> {
let result = controller::register(&db, &item, &mailer);
match result {
Ok(()) => Ok(HttpResponse::build(StatusCode::OK)
.body("{ \"message\": \"Registered! Check your email to activate your account.\" }")),
Err((status_code, message)) => Ok(HttpResponse::build(
StatusCode::from_u16(status_code as u16).unwrap(),
)
.body(json!({ "message": message }).to_string())),
}
}
#[cfg_attr(feature = "plugin_utoipa", utoipa::path(
context_path = "/api/auth",
params(ActivationInput),
responses(
(status = 200, description = "Success, account associated with activation_token is activated", body=AuthMessageResponse),
(status = 200, description = "Already activated.", body = AuthMessageResponse),
(status = 400, description = "Invalid token.", body = AuthMessageResponse),
(status = 401, description = "Invalid token", body = AuthMessageResponse),
(status = 500, description = "Could not activate user. ", body = AuthMessageResponse),
),
tag = "Users",
))]
#[get("/activate")]
async fn activate(
db: Data<Database>,
Query(item): Query<ActivationInput>,
mailer: Data<Mailer>,
) -> Result<HttpResponse, AWError> {
let result = controller::activate(&db, &item, &mailer);
match result {
Ok(()) => Ok(HttpResponse::build(StatusCode::OK).body("{ \"message\": \"Activated!\" }")),
Err((status_code, message)) => Ok(HttpResponse::build(
StatusCode::from_u16(status_code as u16).unwrap(),
)
.body(json!({ "message": message }).to_string())),
}
}
#[cfg_attr(feature = "plugin_utoipa", utoipa::path(
context_path = "/api/auth",
request_body(content = ForgotInput, content_type = "application/json"),
responses(
(status = 200, description = "Success, password reset email is sent to users email", body=AuthMessageResponse),
),
tag = "Users",
))]
#[post("/forgot")]
async fn forgot_password(
db: Data<Database>,
Json(item): Json<ForgotInput>,
mailer: Data<Mailer>,
) -> Result<HttpResponse, AWError> {
let result = controller::forgot_password(&db, &item, &mailer);
match result {
Ok(()) => Ok(HttpResponse::build(StatusCode::OK)
.body("{ \"message\": \"Please check your email.\" }")),
Err((status_code, message)) => Ok(HttpResponse::build(
StatusCode::from_u16(status_code as u16).unwrap(),
)
.body(json!({ "message": message }).to_string())),
}
}
#[cfg_attr(feature = "plugin_utoipa", utoipa::path(
context_path = "/api/auth",
request_body(content = ChangeInput, content_type = "application/json"),
responses(
(status = 200, description = "Success, password changed", body=AuthMessageResponse),
(status = 400, description = "Missing password.", body=AuthMessageResponse),
(status = 400, description = "The new password must be different.", body=AuthMessageResponse),
(status = 400, description = "Account has not been activated.", body=AuthMessageResponse),
(status = 400, description = "Invalid credentials.", body=AuthMessageResponse),
(status = 500, description = "Could not find user.", body=AuthMessageResponse),
(status = 500, description = "Could not update password.", body=AuthMessageResponse),
),
tag = "Users",
security ( ("JWT" = []))
))]
#[post("/change")]
async fn change_password(
db: Data<Database>,
Json(item): Json<ChangeInput>,
auth: Auth,
mailer: Data<Mailer>,
) -> Result<HttpResponse, AWError> {
let result = controller::change_password(&db, &item, &auth, &mailer);
match result {
Ok(()) => Ok(HttpResponse::build(StatusCode::OK)
.body(json!({"message": "Password changed."}).to_string())),
Err((status_code, message)) => Ok(HttpResponse::build(
StatusCode::from_u16(status_code as u16).unwrap(),
)
.body(json!({ "message": message }).to_string())),
}
}
#[cfg_attr(feature = "plugin_utoipa", utoipa::path(
context_path = "/api/auth",
responses(
(status = 200, description = "Success, API is running"),
),
tag = "Users",
security ( ("JWT" = []))
))]
#[post("/check")]
async fn check(auth: Auth) -> HttpResponse {
controller::check(&auth);
HttpResponse::Ok().finish()
}
#[cfg_attr(feature = "plugin_utoipa", utoipa::path(
context_path = "/api/auth",
request_body(content = ResetInput, content_type = "application/json"),
responses(
(status = 200, description = "Password changed.", body=AuthMessageResponse),
(status = 400, description = "Invalid token.", body=AuthMessageResponse),
(status = 400, description = "Account has not been activated.", body=AuthMessageResponse),
(status = 400, description = "The new password must be different.", body=AuthMessageResponse),
(status = 401, description = "Invalid token.", body=AuthMessageResponse),
(status = 500, description = "Could not update password.", body=AuthMessageResponse),
),
tag = "Users",
))]
#[post("/reset")]
async fn reset_password(
db: Data<Database>,
Json(item): Json<ResetInput>,
mailer: Data<Mailer>,
) -> Result<HttpResponse, AWError> {
let result = controller::reset_password(&db, &item, &mailer);
match result {
Ok(()) => Ok(HttpResponse::build(StatusCode::OK)
.body(json!({"message": "Password reset"}).to_string())),
Err((status_code, message)) => Ok(HttpResponse::build(
StatusCode::from_u16(status_code as u16).unwrap(),
)
.body(json!({ "message": message }).to_string())),
}
}
pub fn endpoints(scope: actix_web::Scope) -> actix_web::Scope {
scope
.service(sessions)
.service(destroy_session)
.service(destroy_sessions)
.service(login)
.service(logout)
.service(check)
.service(refresh)
.service(register)
.service(activate)
.service(forgot_password)
.service(change_password)
.service(reset_password)
}
#[cfg(feature = "plugin_utoipa")]
#[derive(OpenApi)]
#[openapi(
paths(sessions, destroy_session, destroy_sessions, login, logout, refresh, register, activate, forgot_password, change_password, check, reset_password),
components(
schemas(UserSessionResponse, UserSessionJson, AuthMessageResponse, AuthTokenResponse, LoginInput, RegisterInput, ForgotInput, ChangeInput, ResetInput)
),
tags(
(name = "Auth", description = "users and user_sessions management endpoints"),
(name = "Sessions", description = "Endpoints for user_sessions management"),
(name = "Users", description = "Endpoints for useres management"),
),
modifiers(&JwtSecurityAddon)
)]
pub struct ApiDoc;