Skip to main content

waveless_runtime/services/auth/
login.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 LoginSvc;
9
10impl Service<RequestCx> for LoginSvc {
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, request_params, .. } = cx;
25
26            let headers = request.headers();
27
28            let request_params = request_params
29                .iter()
30                .filter_map(|entry| {
31                    if let (key, ParamValue::Client(Some(value))) = entry {
32                        Some((key.to_owned(), value.to_owned()))
33                    } else {
34                        None
35                    }
36                })
37                .collect();
38
39            let auth_config = RuntimeCx::acquire()
40                .build()
41                .read()
42                .await
43                .config()
44                .authentication()
45                .to_owned()
46                .ok_or(RequestError::Other(eyre!(
47                    "Authentication is not set for the current build."
48                )))?;
49
50            let auth_method = {
51                if auth_config.backends().len() == 1 {
52                    auth_config.backends().first().unwrap()
53                } else if let Some(auth_backend_name) = headers.get("AuthenticationType") {
54                    // Checks for authentication type header if set.
55                    if let Ok(auth_backend_name) = auth_backend_name.to_str() {
56                        auth_config
57                            .backends()
58                            .iter()
59                            .find(|auth_method| auth_method.name() == auth_backend_name)
60                            .ok_or(RequestError::Expected(
61                                StatusCode::BAD_REQUEST,
62                                "Cannot find the requested authentication method."
63                                    .into(),
64                            ))?
65                    } else {
66                        return Err(RequestError::Expected(
67                            StatusCode::BAD_REQUEST,
68                            "Cannot deserialize the `AuthenticationMethod` header."
69                                .into(),
70                        ));
71                    }
72                } else {
73                    return Err(RequestError::Expected(
74                        StatusCode::BAD_REQUEST,
75                        "No authentication method has been set. HINT: set one using the `AuthenticationMethod` header."
76                            .into(),
77                    ));
78                }
79            };
80
81            let Ok(auth_db_conns) = auth_method.get_db_handle() else {
82                return Err(RequestError::Other(eyre!(
83                    "Cannot get the database connection for the authentication databases."
84                )));
85            };
86
87            match auth_method.check(auth_db_conns, request_params).await {
88                Ok(Some(user_id)) => {
89                    // Create a new session.
90                    let session_method = auth_config.session();
91
92                    let Ok(session_db_conns) = session_method.get_db_handle() else {
93                        return Err(RequestError::Other(eyre!(
94                            "Cannot get the database connection for the session databases."
95                        )));
96                    };
97
98                    let session_token =
99                        session_method
100                            .new(session_db_conns, user_id)
101                            .await
102                            .map_err(|err| {
103                                RequestError::Other(eyre!(
104                                    "Cannot check the session token. {}",
105                                    err
106                                ))
107                            })?;
108
109                    let mut headers = HashMap::new();
110
111                    // TODO: should add the secure param to `Set-Cookie`.
112                    headers.insert(
113                        "Set-Cookie".into(),
114                        format!(
115                            "Authorization={}; SameSite=Lax; Path=/; {}",
116                            session_token,
117                            session_method
118                                .max_age()
119                                .map(|max_age| format!("Max-Age={}", max_age))
120                                .unwrap_or_default()
121                        )
122                        .into(),
123                    );
124
125                    Ok(ResponseCx::new(headers, Some(BodyValue::Json(
126                        json!({
127                            "token": session_token
128                        }),
129                    ))))
130                }
131                Ok(None) => Err(RequestError::Expected(
132                    StatusCode::FORBIDDEN,
133                    format!("Login failed, invalid credentials.").into(),
134                )),
135                Err(err) => Err(RequestError::Other(err)),
136            }
137        }).into();
138
139        future as Self::Future // Actually, this is not an error! https://github.com/rust-lang/rust/issues/92929
140    }
141}