Skip to main content

waveless_runtime/services/auth/session/
logout.rs

1// Waveless
2// Copyright (C) 2026 Oscar Alvarez Gonzalez
3
4use crate::*;
5
6/// TODO: add documentation.
7#[derive(Clone, Constructor, Debug)]
8pub struct LogoutSvc;
9
10impl Service<RequestCx> for LogoutSvc {
11    type Response = ResponseCx;
12
13    type Error = RequestError;
14
15    type Future = BoxFuture<'static, Result<Self::Response, Self::Error>>;
16
17    fn poll_ready(&mut self, _cx: &mut std::task::Context<'_>) -> Poll<Result<(), Self::Error>> {
18        Poll::Ready(Ok(()))
19    }
20
21    #[instrument(skip_all)]
22    fn call(&mut self, cx: RequestCx) -> Self::Future {
23        let future: Pin<_> = Box::pin(async move {
24            let RequestCx { request_params, endpoint, .. } = cx;
25
26            let ExecutionTarget::Http(http_target) = endpoint.execution_target() else {
27                unreachable!()
28            };
29
30            let auth_config = RuntimeCx::acquire()
31                .build()
32                .read()
33                .await
34                .config()
35                .authentication()
36                .to_owned()
37                .ok_or(RequestError::Other(eyre!(
38                    "Authentication is not set for the current build."
39                )))?;
40
41            let all_sessions = http_target.route().split("/").last().unwrap().to_lowercase() == "all";
42
43            let user_id =
44                match request_params
45                    .get("user_id")
46                    .ok_or(RequestError::Other(eyre!(
47                        "Cannot logout as there is no session active.",
48                    )))? {
49                    ParamValue::Internal(user_id) => Ok(user_id.to_owned()),
50                    _ => Err(RequestError::Expected(
51                        StatusCode::FORBIDDEN,
52                        "User id injection from the client is forbidden. HINT: if you are debugging your app you can try creating a new session manually.".into(),
53                    )),
54                }?.parse::<UserId>().map_err(|_| RequestError::Other(eyre!("Cannot convert user id to it's internal representation.")))?;
55
56
57            let token =
58                match request_params
59                    .get("token")
60                    .unwrap() {
61                    ParamValue::Internal(token) if !all_sessions => Ok(Some(token.to_owned())),
62                    ParamValue::Internal(_) if all_sessions => Ok(None),
63                    _ => Err(RequestError::Expected(
64                        StatusCode::FORBIDDEN,
65                        "Session token injection from the client is forbidden. HINT: if you are debugging your app you can try creating a new session manually.".into(),
66                    )),
67                }?;
68
69            let session_method = auth_config.session();
70
71            let Ok(db_conns) = session_method.get_db_handle() else {
72                return Err(RequestError::Other(eyre!(
73                    "Cannot get the database connection for the session databases.",
74                )));
75            };
76
77            session_method.invalidate(db_conns, user_id, token).await?;
78
79            Ok(ResponseCx::new(Default::default(), Some(BodyValue::Json(json!({})))))
80        })
81        .into();
82
83        future as Self::Future // Actually, this is not an error! https://github.com/rust-lang/rust/issues/92929
84    }
85}