shield 0.6.0

Web authentication for Rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
use std::{any::Any, collections::HashMap, sync::Arc};

#[cfg(feature = "utoipa")]
use convert_case::{Case, Casing};
use ordered_hash_map::OrderedHashMap;
use tracing::warn;
#[cfg(feature = "utoipa")]
use utoipa::{
    IntoParams,
    openapi::{
        OpenApi, PathItem, Paths,
        path::{Operation, ParameterIn},
    },
};

#[cfg(feature = "utoipa")]
use crate::path::{ActionPathParams, MethodActionPathParams};
use crate::{
    action::{Action, ActionForms, ActionMethodForm, ActionProviderForm},
    actions::SignOutAction,
    error::{ActionError, MethodError, ProviderError, SessionError, ShieldError},
    hooks::Hooks,
    method::ErasedMethod,
    options::ShieldOptions,
    request::Request,
    response::ResponseType,
    session::Session,
    storage::{Storage, StorageWithHooks},
    user::User,
};

#[derive(Clone)]
pub struct Shield<U: User> {
    storage: Arc<dyn Storage<U>>,
    actions: Arc<HashMap<String, Arc<dyn Action>>>,
    methods: Arc<OrderedHashMap<String, Arc<dyn ErasedMethod>>>,
    options: ShieldOptions,
    hooks: Vec<Arc<dyn Hooks>>,
}

impl<U: User + 'static> Shield<U> {
    pub fn new<S>(storage: S, methods: Vec<Arc<dyn ErasedMethod>>, options: ShieldOptions) -> Self
    where
        S: Storage<U> + 'static,
    {
        Self::new_with_hooks(storage, methods, options, vec![])
    }

    pub fn new_with_hooks<S>(
        storage: S,
        methods: Vec<Arc<dyn ErasedMethod>>,
        options: ShieldOptions,
        hooks: Vec<Arc<dyn Hooks>>,
    ) -> Self
    where
        S: Storage<U> + 'static,
    {
        let actions: [Arc<dyn Action>; 1] = [Arc::new(SignOutAction)];

        // TOOD: Check for duplicate action and method IDs.

        Self {
            storage: Arc::new(StorageWithHooks::new(storage, hooks.clone())),
            actions: Arc::new(
                actions
                    .into_iter()
                    .map(|action| (action.id().to_owned(), action))
                    .collect(),
            ),
            methods: Arc::new(
                methods
                    .into_iter()
                    .map(|method| (method.erased_id(), method))
                    .collect(),
            ),
            options,
            hooks,
        }
    }

    pub fn storage(&self) -> &dyn Storage<U> {
        &*self.storage
    }

    pub fn options(&self) -> &ShieldOptions {
        &self.options
    }

    pub fn action_by_id(&self, action_id: &str) -> Option<&dyn Action> {
        self.actions.get(action_id).map(|v| &**v)
    }

    pub fn method_by_id(&self, method_id: &str) -> Option<&dyn ErasedMethod> {
        self.methods.get(method_id).map(|v| &**v)
    }

    pub async fn provider_by_id(
        &self,
        method_id: &str,
        provider_id: Option<&str>,
    ) -> Result<Option<Box<dyn Any + Send + Sync>>, ShieldError> {
        match self.method_by_id(method_id) {
            Some(provider) => provider.erased_provider_by_id(provider_id).await,
            None => Ok(None),
        }
    }

    pub async fn action_forms(
        &self,
        action_id: &str,
        session: Session,
    ) -> Result<ActionForms, ShieldError> {
        let mut action_name = None::<String>;
        let mut forms = vec![];
        let mut method_forms = vec![];

        if let Some(action) = self.actions.get(action_id) {
            action_name = Some(action.name().to_owned());
            forms = action.forms().await?;
        }

        for (method_id, method) in self.methods.iter() {
            let Some(action) = method.erased_action_by_id(action_id) else {
                continue;
            };

            let (base_session, method_session) = {
                let session_data = session.data();
                let session_data = session_data
                    .lock()
                    .map_err(|err| SessionError::Lock(err.to_string()))?;

                (
                    session_data.base.clone(),
                    method.erased_deserialize_session(session_data.method_str(method_id))?,
                )
            };

            let name = action.erased_name();
            if let Some(action_name) = &action_name
                && *action_name != name
            {
                warn!("Action name mismatch `{}` != `{}`", action_name, name);
            }
            action_name = Some(name);

            let mut provider_forms = vec![];
            for (provider_id, provider) in method.erased_providers().await? {
                if !action.erased_condition(&*provider, &base_session, &*method_session)? {
                    continue;
                }

                let forms = action.erased_forms(provider).await?;
                for form in forms {
                    provider_forms.push(ActionProviderForm {
                        id: provider_id.clone(),
                        form,
                    });
                }
            }

            provider_forms.sort_by(|a, b| a.id.cmp(&b.id));

            method_forms.push(ActionMethodForm {
                id: method_id.clone(),
                provider_forms,
            });
        }

        Ok(ActionForms {
            id: action_id.to_owned(),
            name: action_name.unwrap_or(action_id.to_owned()),
            forms,
            method_forms,
        })
    }

    pub async fn call(
        &self,
        action_id: &str,
        session: Session,
        request: Request,
    ) -> Result<ResponseType, ShieldError> {
        let action =
            self.action_by_id(action_id)
                .ok_or(ShieldError::Action(ActionError::NotFound(
                    action_id.to_owned(),
                )))?;

        let base_session = {
            let session_data = session.data();
            let session_data = session_data
                .lock()
                .map_err(|err| SessionError::Lock(err.to_string()))?;

            session_data.base.clone()
        };

        let mut request = request;
        for hook in &self.hooks {
            request = hook.request(action_id, request).await?;
        }

        let mut response = action.call(&base_session, request).await?;

        for hook in &self.hooks {
            response = hook.response(action_id, response).await?;
        }

        for session_action in &response.session_actions {
            session_action.call(&session).await?;
        }

        Ok(response.r#type)
    }

    pub async fn call_method(
        &self,
        action_id: &str,
        method_id: &str,
        provider_id: Option<&str>,
        session: Session,
        request: Request,
    ) -> Result<ResponseType, ShieldError> {
        let method =
            self.method_by_id(method_id)
                .ok_or(ShieldError::Method(MethodError::NotFound(
                    method_id.to_owned(),
                )))?;

        let action = method
            .erased_action_by_id(action_id)
            .ok_or(ShieldError::Action(ActionError::NotFound(
                action_id.to_owned(),
            )))?;

        let provider =
            method
                .erased_provider_by_id(provider_id)
                .await?
                .ok_or(ShieldError::Provider(ProviderError::NotFound(
                    provider_id.map(ToOwned::to_owned),
                )))?;

        let (base_session, method_session) = {
            let session_data = session.data();
            let session_data = session_data
                .lock()
                .map_err(|err| SessionError::Lock(err.to_string()))?;

            (
                session_data.base.clone(),
                method.erased_deserialize_session(session_data.method_str(method_id))?,
            )
        };

        let mut request = request;
        for hook in &self.hooks {
            request = hook
                .method_request(action_id, method_id, provider_id, request)
                .await?;
        }

        let mut response = action
            .erased_call(provider, &base_session, &*method_session, request)
            .await?;

        for hook in &self.hooks {
            response = hook
                .method_response(action_id, method_id, provider_id, response)
                .await?;
        }

        for session_action in &response.session_actions {
            session_action.call(&session).await?;
        }

        Ok(response.r#type)
    }

    pub async fn user(&self, session: &Session) -> Result<Option<U>, ShieldError> {
        let authentication = {
            let session_data = session.data();
            let session_data = session_data
                .lock()
                .map_err(|err| SessionError::Lock(err.to_string()))?;

            session_data.base.authentication.clone()
        };

        match authentication {
            Some(authentication) => {
                if self
                    .provider_by_id(
                        &authentication.method_id,
                        authentication.provider_id.as_deref(),
                    )
                    .await?
                    .is_none()
                {
                    session.purge().await?;
                    return Ok(None);
                }

                let user = self.storage().user_by_id(&authentication.user_id).await?;

                if user.is_none() {
                    session.purge().await?;
                }

                Ok(user)
            }
            None => Ok(None),
        }
    }

    pub async fn user_connections<C: 'static>(
        &self,
        user: &U,
        method_id: &str,
        provider_id: Option<&str>,
    ) -> Result<Vec<C>, ShieldError> {
        let method =
            self.method_by_id(method_id)
                .ok_or(ShieldError::Method(MethodError::NotFound(
                    method_id.to_owned(),
                )))?;

        let connections = method
            .erased_user_connections(&user.id(), provider_id)
            .await?;

        Ok(connections
            .into_iter()
            .map(|connection| {
                *connection
                    .downcast::<C>()
                    .expect("Connection should be downcast")
            })
            .collect())
    }

    #[cfg(feature = "utoipa")]
    pub fn openapi(&self) -> OpenApi {
        use utoipa::openapi::Response;

        let mut paths = Paths::builder();

        for action in self.actions.values() {
            let action_id = action.id();

            // TODO: Query, request body, responses.

            paths = paths.path(
                format!("/{action_id}"),
                PathItem::builder()
                    .operation(
                        action.method().into(),
                        Operation::builder()
                            .operation_id(Some(action_id.to_case(Case::Camel)))
                            .summary(Some(action.openapi_summary()))
                            .description(Some(action.openapi_description()))
                            .tag("auth")
                            .parameters(Some(ActionPathParams::into_params(|| {
                                Some(ParameterIn::Path)
                            })))
                            .response(
                                "500",
                                Response::builder().description("Internal server error."),
                            ),
                    )
                    .build(),
            );
        }

        for method in self.methods.values() {
            for action in method.erased_actions() {
                let method_id = method.erased_id();
                let action_id = action.erased_id();

                // TODO: Query, request body, responses.

                paths = paths.path(
                    format!("/{action_id}/{method_id}/{{providerId}}"),
                    PathItem::builder()
                        .operation(
                            action.erased_method().into(),
                            Operation::builder()
                                .operation_id(Some(format!(
                                    "{}{}",
                                    action_id.to_case(Case::Camel),
                                    method_id.to_case(Case::UpperCamel)
                                )))
                                .summary(Some(action.erased_openapi_summary()))
                                .description(Some(action.erased_openapi_description()))
                                .tag("auth")
                                .parameters(Some(MethodActionPathParams::into_params(|| {
                                    Some(ParameterIn::Path)
                                })))
                                .response(
                                    "500",
                                    Response::builder().description("Internal server error."),
                                ),
                        )
                        .build(),
                );
            }
        }

        OpenApi::builder().paths(paths.build()).build()
    }
}

#[cfg(test)]
mod tests {
    use crate::{
        options::ShieldOptions,
        storage::tests::{TEST_STORAGE_ID, TestStorage},
    };

    use super::Shield;

    #[test]
    fn test_storage() {
        let shield = Shield::new(TestStorage::default(), vec![], ShieldOptions::default());

        assert_eq!(TEST_STORAGE_ID, shield.storage().id());
    }
}