1
use axum::{
2
    Router,
3
    body::{Body, to_bytes},
4
    http::{Request, StatusCode, header},
5
};
6
use tower::ServiceExt;
7

            
8
use crate::common::{create_test_app_state, test_limiter};
9

            
10
const FORM: &str = "email=nobody%40example.com&password=hunter2";
11

            
12
12
async fn post_login(app: &Router) -> (StatusCode, String) {
13
12
    let response = app
14
12
        .clone()
15
12
        .oneshot(
16
12
            Request::builder()
17
12
                .method("POST")
18
12
                .uri("/auth/login")
19
12
                .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
20
12
                .header(header::ACCEPT, "text/html")
21
12
                .body(Body::from(FORM))
22
12
                .unwrap(),
23
12
        )
24
12
        .await
25
12
        .expect("the router must answer");
26
12
    let status = response.status();
27
12
    let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
28
12
    (status, String::from_utf8(body.to_vec()).unwrap())
29
12
}
30

            
31
2
async fn app() -> Router {
32
2
    let app_state = create_test_app_state().await;
33
2
    web::route::create_api_router(app_state.clone(), test_limiter()).with_state(app_state)
34
2
}
35

            
36
#[supp_macro::shared_runtime_test]
37
1
async fn bad_credentials_reshow_the_login_page_with_the_email_but_not_the_password() {
38
1
    let (status, body) = post_login(&app().await).await;
39
1
    assert_eq!(status, StatusCode::UNAUTHORIZED);
40
1
    assert!(body.contains(r#"id="loginform""#));
41
1
    assert!(body.contains("Invalid email or password"));
42
1
    assert!(body.contains(r#"value="nobody@example.com""#));
43
1
    assert!(!body.contains("hunter2"));
44
}
45

            
46
#[supp_macro::shared_runtime_test]
47
1
async fn a_throttled_login_reshows_the_login_page_with_429() {
48
1
    let app = app().await;
49
1
    for _ in 0..10 {
50
10
        post_login(&app).await;
51
    }
52
1
    let (status, body) = post_login(&app).await;
53
1
    assert_eq!(status, StatusCode::TOO_MANY_REQUESTS);
54
1
    assert!(body.contains(r#"id="loginform""#));
55
1
    assert!(body.contains("Too many attempts, try again later"));
56
1
    assert!(!body.contains("hunter2"));
57
}