yew_oauth2/components/
use_authentication.rs

1//! The [`UseAuthentication`] component
2
3use super::missing_context;
4use crate::{
5    context::{Authentication, OAuth2Context},
6    hook::use_auth_state,
7};
8use std::rc::Rc;
9use yew::prelude::*;
10
11/// A trait which component's properties must implement in order to receive the
12/// context.
13pub trait UseAuthenticationProperties: Clone {
14    fn set_authentication(&mut self, auth: Authentication);
15}
16
17/// Properties for the [`UseAuthentication`] component
18#[derive(Clone, Debug, Properties)]
19pub struct UseAuthenticationComponentProperties<C>
20where
21    C: BaseComponent,
22    C::Properties: UseAuthenticationProperties,
23{
24    pub children: ChildrenWithProps<C>,
25}
26
27impl<C> PartialEq for UseAuthenticationComponentProperties<C>
28where
29    C: BaseComponent,
30    C::Properties: UseAuthenticationProperties,
31{
32    fn eq(&self, other: &Self) -> bool {
33        self.children == other.children
34    }
35}
36
37/// A component which injects the authentication into the properties of component.
38///
39/// The component's properties must implement the trait [`UseAuthenticationProperties`].
40///
41/// ## Example
42///
43/// ```rust
44/// use yew_oauth2::prelude::*;
45/// use yew::prelude::*;
46///
47/// #[derive(Clone, Debug, PartialEq, Properties)]
48/// pub struct Props {
49///    #[prop_or_default]
50///    pub auth: Option<Authentication>,
51/// }
52///
53/// impl UseAuthenticationProperties for Props {
54///    fn set_authentication(&mut self, auth: Authentication) {
55///        self.auth = Some(auth);
56///    }
57/// }
58///
59/// #[function_component(ViewUseAuth)]
60/// pub fn view_use_auth(props: &Props) -> Html {
61///     html!(
62///         <>
63///             <h2> { "Use authentication example"} </h2>
64///             <code><pre>{ format!("Auth: {:?}", props.auth) }</pre></code>
65///         </>
66///     )
67/// }
68/// ```
69#[function_component(UseAuthentication)]
70pub fn use_authentication<C>(props: &UseAuthenticationComponentProperties<C>) -> Html
71where
72    C: BaseComponent,
73    C::Properties: UseAuthenticationProperties,
74{
75    let auth = use_auth_state();
76
77    html!(
78        if let Some(auth) = auth {
79            if let OAuth2Context::Authenticated(auth) = auth {
80                { for props.children.iter().map(|mut c|{
81                    let props = Rc::make_mut(&mut c.props);
82                    props.set_authentication(auth.clone());
83                    c
84                }) }
85            }
86        } else {
87            { missing_context() }
88        }
89    )
90}