waveless_runtime/services/auth/
signup.rs1use crate::*;
5
6#[derive(Clone, Constructor, Debug)]
8pub struct SignUpSvc;
9
10impl Service<RequestCx> for SignUpSvc {
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 if !auth_config.allow_signup() {
52 Err(RequestError::Other(eyre!("Signup is disabled for the current build.")))?;
53 }
54
55 let auth_method = {
56 if auth_config.backends().len() == 1 {
57 auth_config.backends().first().unwrap()
58 } else if let Some(auth_backend_name) = headers.get("AuthenticationType") {
59 if let Ok(auth_backend_name) = auth_backend_name.to_str() {
61 auth_config
62 .backends()
63 .iter()
64 .find(|auth_method| auth_method.name() == auth_backend_name)
65 .ok_or(RequestError::Expected(
66 StatusCode::BAD_REQUEST,
67 "Cannot find the requested authentication method."
68 .into(),
69 ))?
70 } else {
71 return Err(RequestError::Expected(
72 StatusCode::BAD_REQUEST,
73 "Cannot deserialize the `AuthenticationMethod` header."
74 .into(),
75 ));
76 }
77 } else {
78 return Err(RequestError::Expected(
79 StatusCode::BAD_REQUEST,
80 "No authentication method has been set. HINT: set one using the `AuthenticationMethod` header."
81 .into(),
82 ));
83 }
84 };
85
86 let Ok(auth_db) = auth_method.get_db_handle() else {
87 return Err(RequestError::Other(eyre!(
88 "Cannot get the database connection for the authentication databases.",
89 )));
90 };
91
92 match auth_method.new(auth_db, request_params).await {
94 Ok(user_id) => {
95 let session_method = auth_config.session();
97
98 let Ok(session_db) = session_method.get_db_handle() else {
99 return Err(RequestError::Other(eyre!(
100 "Cannot get the database connection for the session databases.",
101 )));
102 };
103
104 let session_token =
105 session_method
106 .new(session_db, user_id)
107 .await
108 .map_err(|err| {
109 RequestError::Other(eyre!(
110 "Cannot check the session token. {}",
111 err
112 ))
113 })?;
114
115
116 let mut headers = HashMap::<CompactString, CompactString>::new();
117
118 headers.insert(
120 "Set-Cookie".into(),
121 format!(
122 "Authorization={}; SameSite=Lax; Path=/; {}",
123 session_token,
124 session_method
125 .max_age()
126 .map(|max_age| format!("Max-Age={}", max_age))
127 .unwrap_or_default()
128 )
129 .into(),
130 );
131
132 Ok(ResponseCx::new(Default::default(), Some(BodyValue::Json(
133 json!({
134 "token": session_token
135 }),
136 ))))
137 },
138
139 Err(err) => Err(RequestError::Other(err))
140 }
141 }).into();
142
143 future as Self::Future }
145}