li7y/tests/auth.rs

78 lines
2.2 KiB
Rust
Raw Normal View History

2024-07-27 22:16:12 +02:00
// SPDX-FileCopyrightText: 2024 Simon Bruder <simon@sbruder.de>
//
// SPDX-License-Identifier: AGPL-3.0-or-later
use actix_http::header;
use actix_web::{cookie::Cookie, test};
use sqlx::PgPool;
mod common;
#[sqlx::test]
async fn protected_route_requires_login(pool: PgPool) {
let srv = test::init_service(li7y::app(&common::config(), &pool)).await;
let req = test::TestRequest::get().uri("/items").to_request();
let res = test::call_service(&srv, req).await;
assert!(common::assert_redirect(res.map_into_boxed_body()).starts_with("/login"));
}
#[sqlx::test]
async fn login(pool: PgPool) {
let srv = test::init_service(li7y::app(&common::config(), &pool)).await;
// This is identical to common::session_cookie,
// but copied here explicitly to ensure the right functionality is tested.
let req = test::TestRequest::post()
.uri("/login")
.set_form(common::LoginForm::default())
.to_request();
let res = test::call_service(&srv, req).await;
let session = Cookie::parse_encoded(
res.headers()
.clone()
.get(header::SET_COOKIE)
.unwrap()
.to_str()
.unwrap()
.to_string(),
)
.unwrap();
assert!(common::assert_redirect(res.map_into_boxed_body()).starts_with("/"));
let req = test::TestRequest::get()
.uri("/")
.cookie(session.clone())
.to_request();
let res = test::call_service(&srv, req).await;
assert!(res.status().is_success());
}
#[ignore = "actix_session::CookieSessionStore does not support invalidating sessions"]
#[sqlx::test]
async fn logout(pool: PgPool) {
let srv = test::init_service(li7y::app(&common::config(), &pool)).await;
let session_cookie = common::session_cookie(&srv).await;
let req = test::TestRequest::post()
.uri("/logout")
.cookie(session_cookie.clone())
.to_request();
test::call_service(&srv, req).await;
let req = test::TestRequest::get()
.uri("/items")
.cookie(session_cookie.clone())
.to_request();
let res = test::call_service(&srv, req).await;
assert!(common::assert_redirect(res.map_into_boxed_body()).starts_with("/login"));
}