1mod branding;
11mod captcha;
12mod ext;
13mod features;
14
15use std::{
16 collections::BTreeMap,
17 fmt::Formatter,
18 net::{IpAddr, Ipv4Addr},
19};
20
21use chrono::{DateTime, Duration, Utc};
22use http::{Method, Uri, Version};
23use mas_data_model::{
24 AuthorizationGrant, BrowserSession, Client, CompatSsoLogin, CompatSsoLoginState,
25 DeviceCodeGrant, MatrixUser, UlidExt as _, UpstreamOAuthLink, UpstreamOAuthProvider,
26 UpstreamOAuthProviderClaimsImports, UpstreamOAuthProviderDiscoveryMode,
27 UpstreamOAuthProviderOnBackchannelLogout, UpstreamOAuthProviderPkceMode,
28 UpstreamOAuthProviderTokenAuthMethod, User, UserEmailAuthentication,
29 UserEmailAuthenticationCode, UserRecoverySession, UserRegistration, UserRegistrationToken,
30};
31use mas_i18n::DataLocale;
32use mas_iana::jose::JsonWebSignatureAlg;
33use mas_policy::{Violation, ViolationVariant};
34use mas_router::{Account, GraphQL, Login, PostAuthAction, UrlBuilder};
35use oauth2_types::{
36 requests::ResponseMode,
37 scope::{OPENID, Scope},
38};
39use rand::{
40 RngExt, SeedableRng,
41 distr::{Alphanumeric, SampleString},
42};
43use rand_chacha::ChaCha8Rng;
44use serde::{Deserialize, Serialize, ser::SerializeStruct};
45use ulid::Ulid;
46use url::Url;
47
48pub use self::{
49 branding::SiteBranding, captcha::WithCaptcha, ext::SiteConfigExt, features::SiteFeatures,
50};
51use crate::{FieldError, FormField, FormState};
52
53pub trait TemplateContext: Serialize {
55 fn with_session(self, current_session: BrowserSession) -> WithSession<Self>
57 where
58 Self: Sized,
59 {
60 WithSession {
61 current_session,
62 inner: self,
63 }
64 }
65
66 fn maybe_with_session(
68 self,
69 current_session: Option<BrowserSession>,
70 ) -> WithOptionalSession<Self>
71 where
72 Self: Sized,
73 {
74 WithOptionalSession {
75 current_session,
76 inner: self,
77 }
78 }
79
80 fn with_csrf<C>(self, csrf_token: C) -> WithCsrf<Self>
82 where
83 Self: Sized,
84 C: ToString,
85 {
86 WithCsrf {
88 csrf_token: csrf_token.to_string(),
89 inner: self,
90 }
91 }
92
93 fn with_language(self, lang: DataLocale) -> WithLanguage<Self>
95 where
96 Self: Sized,
97 {
98 WithLanguage {
99 lang: lang.to_string(),
100 inner: self,
101 }
102 }
103
104 fn with_captcha(self, captcha: Option<mas_data_model::CaptchaConfig>) -> WithCaptcha<Self>
106 where
107 Self: Sized,
108 {
109 WithCaptcha::new(captcha, self)
110 }
111
112 fn sample<R: RngExt>(
117 now: chrono::DateTime<Utc>,
118 rng: &mut R,
119 locales: &[DataLocale],
120 ) -> BTreeMap<SampleIdentifier, Self>
121 where
122 Self: Sized;
123}
124
125#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
126pub struct SampleIdentifier {
127 pub components: Vec<(&'static str, String)>,
128}
129
130impl SampleIdentifier {
131 pub fn from_index(index: usize) -> Self {
132 Self {
133 components: Vec::default(),
134 }
135 .with_appended("index", format!("{index}"))
136 }
137
138 pub fn with_appended(&self, kind: &'static str, locale: String) -> Self {
139 let mut new = self.clone();
140 new.components.push((kind, locale));
141 new
142 }
143}
144
145pub(crate) fn sample_list<T: TemplateContext>(samples: Vec<T>) -> BTreeMap<SampleIdentifier, T> {
146 samples
147 .into_iter()
148 .enumerate()
149 .map(|(index, sample)| (SampleIdentifier::from_index(index), sample))
150 .collect()
151}
152
153impl TemplateContext for () {
154 fn sample<R: RngExt>(
155 _now: chrono::DateTime<Utc>,
156 _rng: &mut R,
157 _locales: &[DataLocale],
158 ) -> BTreeMap<SampleIdentifier, Self>
159 where
160 Self: Sized,
161 {
162 BTreeMap::new()
163 }
164}
165
166#[derive(Serialize, Debug)]
168pub struct WithLanguage<T> {
169 lang: String,
170
171 #[serde(flatten)]
172 inner: T,
173}
174
175impl<T> WithLanguage<T> {
176 pub fn language(&self) -> &str {
178 &self.lang
179 }
180}
181
182impl<T> std::ops::Deref for WithLanguage<T> {
183 type Target = T;
184
185 fn deref(&self) -> &Self::Target {
186 &self.inner
187 }
188}
189
190impl<T: TemplateContext> TemplateContext for WithLanguage<T> {
191 fn sample<R: RngExt>(
192 now: chrono::DateTime<Utc>,
193 rng: &mut R,
194 locales: &[DataLocale],
195 ) -> BTreeMap<SampleIdentifier, Self>
196 where
197 Self: Sized,
198 {
199 let rng = ChaCha8Rng::from_rng(&mut *rng);
201 locales
202 .iter()
203 .flat_map(|locale| {
204 T::sample(now, &mut rng.clone(), locales)
205 .into_iter()
206 .map(|(sample_id, sample)| {
207 (
208 sample_id.with_appended("locale", locale.to_string()),
209 WithLanguage {
210 lang: locale.to_string(),
211 inner: sample,
212 },
213 )
214 })
215 })
216 .collect()
217 }
218}
219
220#[derive(Serialize, Debug)]
222pub struct WithCsrf<T> {
223 csrf_token: String,
224
225 #[serde(flatten)]
226 inner: T,
227}
228
229impl<T: TemplateContext> TemplateContext for WithCsrf<T> {
230 fn sample<R: RngExt>(
231 now: chrono::DateTime<Utc>,
232 rng: &mut R,
233 locales: &[DataLocale],
234 ) -> BTreeMap<SampleIdentifier, Self>
235 where
236 Self: Sized,
237 {
238 T::sample(now, rng, locales)
239 .into_iter()
240 .map(|(k, inner)| {
241 (
242 k,
243 WithCsrf {
244 csrf_token: "fake_csrf_token".into(),
245 inner,
246 },
247 )
248 })
249 .collect()
250 }
251}
252
253#[derive(Serialize, Debug)]
255pub struct WithSession<T> {
256 current_session: BrowserSession,
257
258 #[serde(flatten)]
259 inner: T,
260}
261
262impl<T: TemplateContext> TemplateContext for WithSession<T> {
263 fn sample<R: RngExt>(
264 now: chrono::DateTime<Utc>,
265 rng: &mut R,
266 locales: &[DataLocale],
267 ) -> BTreeMap<SampleIdentifier, Self>
268 where
269 Self: Sized,
270 {
271 BrowserSession::samples(now, rng)
272 .into_iter()
273 .enumerate()
274 .flat_map(|(session_index, session)| {
275 T::sample(now, rng, locales)
276 .into_iter()
277 .map(move |(k, inner)| {
278 (
279 k.with_appended("browser-session", session_index.to_string()),
280 WithSession {
281 current_session: session.clone(),
282 inner,
283 },
284 )
285 })
286 })
287 .collect()
288 }
289}
290
291#[derive(Serialize)]
293pub struct WithOptionalSession<T> {
294 current_session: Option<BrowserSession>,
295
296 #[serde(flatten)]
297 inner: T,
298}
299
300impl<T: TemplateContext> TemplateContext for WithOptionalSession<T> {
301 fn sample<R: RngExt>(
302 now: chrono::DateTime<Utc>,
303 rng: &mut R,
304 locales: &[DataLocale],
305 ) -> BTreeMap<SampleIdentifier, Self>
306 where
307 Self: Sized,
308 {
309 BrowserSession::samples(now, rng)
310 .into_iter()
311 .map(Some) .chain(std::iter::once(None)) .enumerate()
314 .flat_map(|(session_index, session)| {
315 T::sample(now, rng, locales)
316 .into_iter()
317 .map(move |(k, inner)| {
318 (
319 if session.is_some() {
320 k.with_appended("browser-session", session_index.to_string())
321 } else {
322 k
323 },
324 WithOptionalSession {
325 current_session: session.clone(),
326 inner,
327 },
328 )
329 })
330 })
331 .collect()
332 }
333}
334
335pub struct EmptyContext;
337
338impl Serialize for EmptyContext {
339 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
340 where
341 S: serde::Serializer,
342 {
343 let mut s = serializer.serialize_struct("EmptyContext", 0)?;
344 s.serialize_field("__UNUSED", &())?;
347 s.end()
348 }
349}
350
351impl TemplateContext for EmptyContext {
352 fn sample<R: RngExt>(
353 _now: chrono::DateTime<Utc>,
354 _rng: &mut R,
355 _locales: &[DataLocale],
356 ) -> BTreeMap<SampleIdentifier, Self>
357 where
358 Self: Sized,
359 {
360 sample_list(vec![EmptyContext])
361 }
362}
363
364#[derive(Serialize)]
366pub struct IndexContext {
367 discovery_url: Url,
368}
369
370impl IndexContext {
371 #[must_use]
374 pub fn new(discovery_url: Url) -> Self {
375 Self { discovery_url }
376 }
377}
378
379impl TemplateContext for IndexContext {
380 fn sample<R: RngExt>(
381 _now: chrono::DateTime<Utc>,
382 _rng: &mut R,
383 _locales: &[DataLocale],
384 ) -> BTreeMap<SampleIdentifier, Self>
385 where
386 Self: Sized,
387 {
388 sample_list(vec![Self {
389 discovery_url: "https://example.com/.well-known/openid-configuration"
390 .parse()
391 .unwrap(),
392 }])
393 }
394}
395
396#[derive(Serialize)]
398#[serde(rename_all = "camelCase")]
399pub struct AppConfig {
400 root: String,
401 graphql_endpoint: String,
402}
403
404#[derive(Serialize)]
406pub struct AppContext {
407 app_config: AppConfig,
408}
409
410impl AppContext {
411 #[must_use]
413 pub fn from_url_builder(url_builder: &UrlBuilder) -> Self {
414 let root = url_builder.relative_url_for(&Account::default());
415 let graphql_endpoint = url_builder.relative_url_for(&GraphQL);
416 Self {
417 app_config: AppConfig {
418 root,
419 graphql_endpoint,
420 },
421 }
422 }
423}
424
425impl TemplateContext for AppContext {
426 fn sample<R: RngExt>(
427 _now: chrono::DateTime<Utc>,
428 _rng: &mut R,
429 _locales: &[DataLocale],
430 ) -> BTreeMap<SampleIdentifier, Self>
431 where
432 Self: Sized,
433 {
434 let url_builder = UrlBuilder::new("https://example.com/".parse().unwrap(), None, None);
435 sample_list(vec![Self::from_url_builder(&url_builder)])
436 }
437}
438
439#[derive(Serialize)]
441pub struct ApiDocContext {
442 openapi_url: Url,
443 callback_url: Url,
444}
445
446impl ApiDocContext {
447 #[must_use]
450 pub fn from_url_builder(url_builder: &UrlBuilder) -> Self {
451 Self {
452 openapi_url: url_builder.absolute_url_for(&mas_router::ApiSpec),
453 callback_url: url_builder.absolute_url_for(&mas_router::ApiDocCallback),
454 }
455 }
456}
457
458impl TemplateContext for ApiDocContext {
459 fn sample<R: RngExt>(
460 _now: chrono::DateTime<Utc>,
461 _rng: &mut R,
462 _locales: &[DataLocale],
463 ) -> BTreeMap<SampleIdentifier, Self>
464 where
465 Self: Sized,
466 {
467 let url_builder = UrlBuilder::new("https://example.com/".parse().unwrap(), None, None);
468 sample_list(vec![Self::from_url_builder(&url_builder)])
469 }
470}
471
472#[derive(Serialize, Deserialize, Debug, Clone, Copy, Hash, PartialEq, Eq)]
474#[serde(rename_all = "snake_case")]
475pub enum LoginFormField {
476 Username,
478
479 Password,
481}
482
483impl FormField for LoginFormField {
484 fn keep(&self) -> bool {
485 match self {
486 Self::Username => true,
487 Self::Password => false,
488 }
489 }
490}
491
492#[derive(Serialize)]
494#[serde(tag = "kind", rename_all = "snake_case")]
495pub enum PostAuthContextInner {
496 ContinueAuthorizationGrant {
498 grant: Box<AuthorizationGrant>,
500 },
501
502 ContinueDeviceCodeGrant {
504 grant: Box<DeviceCodeGrant>,
506 },
507
508 ContinueCompatSsoLogin {
511 login: Box<CompatSsoLogin>,
513 },
514
515 ChangePassword,
517
518 LinkUpstream {
520 provider: Box<UpstreamOAuthProvider>,
522
523 link: Box<UpstreamOAuthLink>,
525 },
526
527 ManageAccount,
529
530 ContinueRoomInvite,
532}
533
534#[derive(Serialize)]
536pub struct PostAuthContext {
537 pub params: PostAuthAction,
539
540 #[serde(flatten)]
542 pub ctx: PostAuthContextInner,
543}
544
545#[derive(Serialize, Default)]
547pub struct LoginContext {
548 form: FormState<LoginFormField>,
549 next: Option<PostAuthContext>,
550 providers: Vec<UpstreamOAuthProvider>,
551}
552
553impl TemplateContext for LoginContext {
554 fn sample<R: RngExt>(
555 _now: chrono::DateTime<Utc>,
556 _rng: &mut R,
557 _locales: &[DataLocale],
558 ) -> BTreeMap<SampleIdentifier, Self>
559 where
560 Self: Sized,
561 {
562 sample_list(vec![
564 LoginContext {
565 form: FormState::default(),
566 next: None,
567 providers: Vec::new(),
568 },
569 LoginContext {
570 form: FormState::default(),
571 next: None,
572 providers: Vec::new(),
573 },
574 LoginContext {
575 form: FormState::default()
576 .with_error_on_field(LoginFormField::Username, FieldError::Required)
577 .with_error_on_field(
578 LoginFormField::Password,
579 FieldError::Policy {
580 code: None,
581 message: "password too short".to_owned(),
582 },
583 ),
584 next: None,
585 providers: Vec::new(),
586 },
587 LoginContext {
588 form: FormState::default()
589 .with_error_on_field(LoginFormField::Username, FieldError::Exists),
590 next: None,
591 providers: Vec::new(),
592 },
593 ])
594 }
595}
596
597impl LoginContext {
598 #[must_use]
600 pub fn with_form_state(self, form: FormState<LoginFormField>) -> Self {
601 Self { form, ..self }
602 }
603
604 pub fn form_state_mut(&mut self) -> &mut FormState<LoginFormField> {
606 &mut self.form
607 }
608
609 #[must_use]
611 pub fn with_upstream_providers(self, providers: Vec<UpstreamOAuthProvider>) -> Self {
612 Self { providers, ..self }
613 }
614
615 #[must_use]
617 pub fn with_post_action(self, context: PostAuthContext) -> Self {
618 Self {
619 next: Some(context),
620 ..self
621 }
622 }
623}
624
625#[derive(Serialize, Deserialize, Debug, Clone, Copy, Hash, PartialEq, Eq)]
627#[serde(rename_all = "snake_case")]
628pub enum RegisterFormField {
629 Username,
631
632 Email,
634
635 Password,
637
638 PasswordConfirm,
640
641 AcceptTerms,
643
644 Token,
646}
647
648impl FormField for RegisterFormField {
649 fn keep(&self) -> bool {
650 match self {
651 Self::Username | Self::Email | Self::AcceptTerms | Self::Token => true,
652 Self::Password | Self::PasswordConfirm => false,
653 }
654 }
655}
656
657#[derive(Serialize)]
659struct RegisterPageProvider {
660 name: String,
661 brand: Option<String>,
662 id: String,
664}
665
666impl RegisterPageProvider {
667 fn new(provider: UpstreamOAuthProvider) -> Self {
668 let name = provider
669 .human_name
670 .or_else(|| {
671 provider
672 .issuer
673 .as_deref()
674 .map(|issuer| crate::functions::simplify_url(issuer, true))
675 })
676 .filter(|name| !name.is_empty())
677 .unwrap_or_else(|| provider.id.to_string());
678
679 Self {
680 name,
681 brand: provider.brand_name,
682 id: provider.id.to_string(),
683 }
684 }
685}
686
687#[derive(Serialize)]
689struct InvitePinnedIdentity {
690 username: Option<String>,
691 email: Option<String>,
692 passwordless: bool,
693}
694
695#[derive(Serialize)]
697pub struct InviteContext {
698 valid: bool,
699
700 #[serde(flatten)]
701 pinned: Option<InvitePinnedIdentity>,
702}
703
704impl InviteContext {
705 #[must_use]
708 pub fn new(token: Option<&UserRegistrationToken>) -> Self {
709 Self {
710 valid: token.is_some(),
711 pinned: token.map(|token| InvitePinnedIdentity {
712 username: token.username.clone(),
713 email: token.email.clone(),
714 passwordless: token.passwordless,
715 }),
716 }
717 }
718}
719
720#[derive(Serialize)]
722pub struct RegisterContext {
723 providers: Vec<RegisterPageProvider>,
724 login_link: String,
725 form: FormState<RegisterFormField>,
726 graphql_endpoint: String,
727 invite: Option<InviteContext>,
728}
729
730impl TemplateContext for RegisterContext {
731 fn sample<R: RngExt>(
732 _now: chrono::DateTime<Utc>,
733 _rng: &mut R,
734 _locales: &[DataLocale],
735 ) -> BTreeMap<SampleIdentifier, Self>
736 where
737 Self: Sized,
738 {
739 let url_builder = UrlBuilder::new("https://example.com/".parse().unwrap(), None, None);
740 sample_list(vec![RegisterContext::new(&url_builder, Vec::new(), None)])
742 }
743}
744
745impl RegisterContext {
746 #[must_use]
749 pub fn new(
750 url_builder: &UrlBuilder,
751 providers: Vec<UpstreamOAuthProvider>,
752 post_auth_action: Option<&PostAuthAction>,
753 ) -> Self {
754 Self {
755 providers: providers
756 .into_iter()
757 .map(RegisterPageProvider::new)
758 .collect(),
759 login_link: url_builder.relative_url_for(&Login::from(post_auth_action.cloned())),
760 form: FormState::default(),
761 graphql_endpoint: url_builder.relative_url_for(&GraphQL),
762 invite: None,
763 }
764 }
765
766 #[must_use]
768 pub fn with_form_state(self, form: FormState<RegisterFormField>) -> Self {
769 Self { form, ..self }
770 }
771
772 #[must_use]
774 pub fn with_invite(self, invite: InviteContext) -> Self {
775 Self {
776 invite: Some(invite),
777 ..self
778 }
779 }
780}
781
782#[derive(Serialize)]
784pub struct ConsentContext {
785 grant: AuthorizationGrant,
786 client: Client,
787 action: PostAuthAction,
788 matrix_user: MatrixUser,
789}
790
791impl TemplateContext for ConsentContext {
792 fn sample<R: RngExt>(
793 now: chrono::DateTime<Utc>,
794 rng: &mut R,
795 _locales: &[DataLocale],
796 ) -> BTreeMap<SampleIdentifier, Self>
797 where
798 Self: Sized,
799 {
800 sample_list(
801 Client::samples(now, rng)
802 .into_iter()
803 .flat_map(|client| {
804 [
805 (None, ResponseMode::Query),
806 (None, ResponseMode::Fragment),
807 (None, ResponseMode::FormPost),
808 (Some("some-state".to_owned()), ResponseMode::Query),
809 (Some("some-state".to_owned()), ResponseMode::Fragment),
810 (Some("some-state".to_owned()), ResponseMode::FormPost),
811 ]
812 .map(|(state, response_mode)| {
813 let mut grant = AuthorizationGrant::sample(now, rng);
814 let action = PostAuthAction::continue_grant(grant.id);
815 grant.client_id = client.id;
817 grant.state = state;
818 grant.response_mode = response_mode;
819 Self {
820 grant,
821 client: client.clone(),
822 action,
823 matrix_user: MatrixUser {
824 mxid: "@alice:example.com".to_owned(),
825 display_name: Some("Alice".to_owned()),
826 },
827 }
828 })
829 })
830 .collect(),
831 )
832 }
833}
834
835impl ConsentContext {
836 #[must_use]
838 pub fn new(grant: AuthorizationGrant, client: Client, matrix_user: MatrixUser) -> Self {
839 let action = PostAuthAction::continue_grant(grant.id);
840 Self {
841 grant,
842 client,
843 action,
844 matrix_user,
845 }
846 }
847}
848
849#[derive(Serialize, Debug)]
850#[serde(tag = "grant_type")]
851enum PolicyViolationGrant {
852 #[serde(rename = "authorization_code")]
853 Authorization(AuthorizationGrant),
854 #[serde(rename = "urn:ietf:params:oauth:grant-type:device_code")]
855 DeviceCode(DeviceCodeGrant),
856}
857
858#[derive(Serialize, Debug)]
860pub struct PolicyViolationContext {
861 grant: PolicyViolationGrant,
862 client: Client,
863 action: PostAuthAction,
864 violations: Vec<Violation>,
865}
866
867impl TemplateContext for PolicyViolationContext {
868 fn sample<R: RngExt>(
869 now: chrono::DateTime<Utc>,
870 rng: &mut R,
871 _locales: &[DataLocale],
872 ) -> BTreeMap<SampleIdentifier, Self>
873 where
874 Self: Sized,
875 {
876 sample_list(
877 Client::samples(now, rng)
878 .into_iter()
879 .flat_map(|client| {
880 let mut grant = AuthorizationGrant::sample(now, rng);
881 grant.client_id = client.id;
883
884 let authorization_grant = PolicyViolationContext::for_authorization_grant(
885 grant.clone(),
886 client.clone(),
887 Vec::new(),
888 );
889
890 let authorization_grant_invalid_scope =
891 PolicyViolationContext::for_authorization_grant(
892 grant.clone(),
893 client.clone(),
894 vec![Violation {
895 msg: "scope 'foo' not allowed".to_owned(),
896 redirect_uri: None,
897 field: None,
898 variant: None,
899 }],
900 );
901 let authorization_grant_admin_scope =
902 PolicyViolationContext::for_authorization_grant(
903 grant.clone(),
904 client.clone(),
905 vec![Violation {
906 msg: "scope 'urn:mas:admin' requires admin privileges".to_owned(),
907 redirect_uri: None,
908 field: None,
909 variant: Some(ViolationVariant::AdminScopeNotAllowed),
910 }],
911 );
912
913 let authorization_grant_client_not_allowed =
914 PolicyViolationContext::for_authorization_grant(
915 grant,
916 client.clone(),
917 vec![Violation {
918 msg: "This client is not allowed to login".to_owned(),
919 redirect_uri: None,
920 field: None,
921 variant: Some(ViolationVariant::ClientNotAllowed),
922 }],
923 );
924
925 let device_code_grant = PolicyViolationContext::for_device_code_grant(
926 DeviceCodeGrant {
927 id: Ulid::from_datetime_with_rng(now, rng),
928 state: mas_data_model::DeviceCodeGrantState::Pending,
929 client_id: client.id,
930 scope: [OPENID].into_iter().collect(),
931 user_code: mas_data_model::generate_user_code(rng),
932 device_code: Alphanumeric.sample_string(rng, 32),
933 created_at: now - Duration::try_minutes(5).unwrap(),
934 expires_at: now + Duration::try_minutes(25).unwrap(),
935 ip_address: None,
936 user_agent: None,
937 locale: None,
938 },
939 client.clone(),
940 Vec::new(),
941 );
942
943 let device_code_grant_invalid_scope =
944 PolicyViolationContext::for_device_code_grant(
945 DeviceCodeGrant {
946 id: Ulid::from_datetime_with_rng(now, rng),
947 state: mas_data_model::DeviceCodeGrantState::Pending,
948 client_id: client.id,
949 scope: [OPENID].into_iter().collect(),
950 user_code: mas_data_model::generate_user_code(rng),
951 device_code: Alphanumeric.sample_string(rng, 32),
952 created_at: now - Duration::try_minutes(5).unwrap(),
953 expires_at: now + Duration::try_minutes(25).unwrap(),
954 ip_address: None,
955 user_agent: None,
956 locale: None,
957 },
958 client,
959 vec![Violation {
960 msg: "user has too many active sessions".to_owned(),
961 redirect_uri: None,
962 field: None,
963 variant: Some(ViolationVariant::TooManySessions {
964 need_to_remove: 1,
965 }),
966 }],
967 );
968
969 [
970 authorization_grant,
971 authorization_grant_invalid_scope,
972 authorization_grant_admin_scope,
973 authorization_grant_client_not_allowed,
974 device_code_grant,
975 device_code_grant_invalid_scope,
976 ]
977 })
978 .collect(),
979 )
980 }
981}
982
983impl PolicyViolationContext {
984 #[must_use]
987 pub const fn for_authorization_grant(
988 grant: AuthorizationGrant,
989 client: Client,
990 violations: Vec<Violation>,
991 ) -> Self {
992 let action = PostAuthAction::continue_grant(grant.id);
993 Self {
994 grant: PolicyViolationGrant::Authorization(grant),
995 client,
996 action,
997 violations,
998 }
999 }
1000
1001 #[must_use]
1004 pub const fn for_device_code_grant(
1005 grant: DeviceCodeGrant,
1006 client: Client,
1007 violations: Vec<Violation>,
1008 ) -> Self {
1009 let action = PostAuthAction::continue_device_code_grant(grant.id);
1010 Self {
1011 grant: PolicyViolationGrant::DeviceCode(grant),
1012 client,
1013 action,
1014 violations,
1015 }
1016 }
1017}
1018
1019#[derive(Serialize)]
1021pub struct CompatLoginPolicyViolationContext {
1022 violations: Vec<Violation>,
1023}
1024
1025impl TemplateContext for CompatLoginPolicyViolationContext {
1026 fn sample<R: RngExt>(
1027 _now: chrono::DateTime<Utc>,
1028 _rng: &mut R,
1029 _locales: &[DataLocale],
1030 ) -> BTreeMap<SampleIdentifier, Self>
1031 where
1032 Self: Sized,
1033 {
1034 sample_list(vec![
1035 CompatLoginPolicyViolationContext { violations: vec![] },
1036 CompatLoginPolicyViolationContext {
1037 violations: vec![Violation {
1038 msg: "scope 'foo' not allowed".to_owned(),
1039 redirect_uri: None,
1040 field: None,
1041 variant: None,
1042 }],
1043 },
1044 CompatLoginPolicyViolationContext {
1045 violations: vec![Violation {
1046 msg: "user has too many active sessions".to_owned(),
1047 redirect_uri: None,
1048 field: None,
1049 variant: Some(ViolationVariant::TooManySessions { need_to_remove: 1 }),
1050 }],
1051 },
1052 CompatLoginPolicyViolationContext {
1053 violations: vec![Violation {
1054 msg: "This client is not allowed to login".to_owned(),
1055 redirect_uri: None,
1056 field: None,
1057 variant: Some(ViolationVariant::ClientNotAllowed),
1058 }],
1059 },
1060 CompatLoginPolicyViolationContext {
1061 violations: vec![
1062 Violation {
1063 msg: "scope 'foo' not allowed".to_owned(),
1064 redirect_uri: None,
1065 field: None,
1066 variant: None,
1067 },
1068 Violation {
1069 msg: "user has too many active sessions".to_owned(),
1070 redirect_uri: None,
1071 field: None,
1072 variant: Some(ViolationVariant::TooManySessions { need_to_remove: 1 }),
1073 },
1074 ],
1075 },
1076 ])
1077 }
1078}
1079
1080impl CompatLoginPolicyViolationContext {
1081 #[must_use]
1084 pub const fn for_violations(violations: Vec<Violation>) -> Self {
1085 Self { violations }
1086 }
1087}
1088
1089#[derive(Serialize)]
1091pub struct CompatSsoContext {
1092 login: CompatSsoLogin,
1093 action: PostAuthAction,
1094 matrix_user: MatrixUser,
1095}
1096
1097impl TemplateContext for CompatSsoContext {
1098 fn sample<R: RngExt>(
1099 now: chrono::DateTime<Utc>,
1100 rng: &mut R,
1101 _locales: &[DataLocale],
1102 ) -> BTreeMap<SampleIdentifier, Self>
1103 where
1104 Self: Sized,
1105 {
1106 let id = Ulid::from_datetime_with_rng(now, rng);
1107 sample_list(vec![CompatSsoContext::new(
1108 CompatSsoLogin {
1109 id,
1110 redirect_uri: Url::parse("https://app.element.io/").unwrap(),
1111 login_token: "abcdefghijklmnopqrstuvwxyz012345".into(),
1112 created_at: now,
1113 state: CompatSsoLoginState::Pending,
1114 },
1115 MatrixUser {
1116 mxid: "@alice:example.com".to_owned(),
1117 display_name: Some("Alice".to_owned()),
1118 },
1119 )])
1120 }
1121}
1122
1123impl CompatSsoContext {
1124 #[must_use]
1126 pub fn new(login: CompatSsoLogin, matrix_user: MatrixUser) -> Self
1127where {
1128 let action = PostAuthAction::continue_compat_sso_login(login.id);
1129 Self {
1130 login,
1131 action,
1132 matrix_user,
1133 }
1134 }
1135}
1136
1137#[derive(Serialize)]
1139pub struct EmailRecoveryContext {
1140 user: User,
1141 session: UserRecoverySession,
1142 recovery_link: Url,
1143}
1144
1145impl EmailRecoveryContext {
1146 #[must_use]
1148 pub fn new(user: User, session: UserRecoverySession, recovery_link: Url) -> Self {
1149 Self {
1150 user,
1151 session,
1152 recovery_link,
1153 }
1154 }
1155
1156 #[must_use]
1158 pub fn user(&self) -> &User {
1159 &self.user
1160 }
1161
1162 #[must_use]
1164 pub fn session(&self) -> &UserRecoverySession {
1165 &self.session
1166 }
1167}
1168
1169impl TemplateContext for EmailRecoveryContext {
1170 fn sample<R: RngExt>(
1171 now: chrono::DateTime<Utc>,
1172 rng: &mut R,
1173 _locales: &[DataLocale],
1174 ) -> BTreeMap<SampleIdentifier, Self>
1175 where
1176 Self: Sized,
1177 {
1178 sample_list(User::samples(now, rng).into_iter().map(|user| {
1179 let session = UserRecoverySession {
1180 id: Ulid::from_datetime_with_rng(now, rng),
1181 email: "hello@example.com".to_owned(),
1182 user_agent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) AppleWebKit/536.30.1 (KHTML, like Gecko) Version/6.0.5 Safari/536.30.1".to_owned(),
1183 ip_address: Some(IpAddr::from([192_u8, 0, 2, 1])),
1184 locale: "en".to_owned(),
1185 created_at: now,
1186 consumed_at: None,
1187 };
1188
1189 let link = "https://example.com/recovery/complete?ticket=abcdefghijklmnopqrstuvwxyz0123456789".parse().unwrap();
1190
1191 Self::new(user, session, link)
1192 }).collect())
1193 }
1194}
1195
1196#[derive(Serialize)]
1198pub struct EmailVerificationContext {
1199 #[serde(skip_serializing_if = "Option::is_none")]
1200 browser_session: Option<BrowserSession>,
1201 #[serde(skip_serializing_if = "Option::is_none")]
1202 user_registration: Option<UserRegistration>,
1203 authentication_code: UserEmailAuthenticationCode,
1204}
1205
1206impl EmailVerificationContext {
1207 #[must_use]
1209 pub fn new(
1210 authentication_code: UserEmailAuthenticationCode,
1211 browser_session: Option<BrowserSession>,
1212 user_registration: Option<UserRegistration>,
1213 ) -> Self {
1214 Self {
1215 browser_session,
1216 user_registration,
1217 authentication_code,
1218 }
1219 }
1220
1221 #[must_use]
1223 pub fn user(&self) -> Option<&User> {
1224 self.browser_session.as_ref().map(|s| &s.user)
1225 }
1226
1227 #[must_use]
1229 pub fn code(&self) -> &str {
1230 &self.authentication_code.code
1231 }
1232}
1233
1234impl TemplateContext for EmailVerificationContext {
1235 fn sample<R: RngExt>(
1236 now: chrono::DateTime<Utc>,
1237 rng: &mut R,
1238 _locales: &[DataLocale],
1239 ) -> BTreeMap<SampleIdentifier, Self>
1240 where
1241 Self: Sized,
1242 {
1243 sample_list(
1244 BrowserSession::samples(now, rng)
1245 .into_iter()
1246 .map(|browser_session| {
1247 let authentication_code = UserEmailAuthenticationCode {
1248 id: Ulid::from_datetime_with_rng(now, rng),
1249 user_email_authentication_id: Ulid::from_datetime_with_rng(now, rng),
1250 code: "123456".to_owned(),
1251 created_at: now - Duration::try_minutes(5).unwrap(),
1252 expires_at: now + Duration::try_minutes(25).unwrap(),
1253 };
1254
1255 Self {
1256 browser_session: Some(browser_session),
1257 user_registration: None,
1258 authentication_code,
1259 }
1260 })
1261 .collect(),
1262 )
1263 }
1264}
1265
1266#[derive(Serialize, Deserialize, Debug, Clone, Copy, Hash, PartialEq, Eq)]
1268#[serde(rename_all = "snake_case")]
1269pub enum RegisterStepsVerifyEmailFormField {
1270 Code,
1272}
1273
1274impl FormField for RegisterStepsVerifyEmailFormField {
1275 fn keep(&self) -> bool {
1276 match self {
1277 Self::Code => true,
1278 }
1279 }
1280}
1281
1282#[derive(Serialize)]
1284pub struct RegisterStepsVerifyEmailContext {
1285 form: FormState<RegisterStepsVerifyEmailFormField>,
1286 authentication: UserEmailAuthentication,
1287}
1288
1289impl RegisterStepsVerifyEmailContext {
1290 #[must_use]
1292 pub fn new(authentication: UserEmailAuthentication) -> Self {
1293 Self {
1294 form: FormState::default(),
1295 authentication,
1296 }
1297 }
1298
1299 #[must_use]
1301 pub fn with_form_state(self, form: FormState<RegisterStepsVerifyEmailFormField>) -> Self {
1302 Self { form, ..self }
1303 }
1304}
1305
1306impl TemplateContext for RegisterStepsVerifyEmailContext {
1307 fn sample<R: RngExt>(
1308 now: chrono::DateTime<Utc>,
1309 rng: &mut R,
1310 _locales: &[DataLocale],
1311 ) -> BTreeMap<SampleIdentifier, Self>
1312 where
1313 Self: Sized,
1314 {
1315 let authentication = UserEmailAuthentication {
1316 id: Ulid::from_datetime_with_rng(now, rng),
1317 user_session_id: None,
1318 user_registration_id: None,
1319 email: "foobar@example.com".to_owned(),
1320 created_at: now,
1321 completed_at: None,
1322 };
1323
1324 sample_list(vec![Self {
1325 form: FormState::default(),
1326 authentication,
1327 }])
1328 }
1329}
1330
1331#[derive(Serialize)]
1333pub struct RegisterStepsEmailInUseContext {
1334 email: String,
1335 action: Option<PostAuthAction>,
1336}
1337
1338impl RegisterStepsEmailInUseContext {
1339 #[must_use]
1341 pub fn new(email: String, action: Option<PostAuthAction>) -> Self {
1342 Self { email, action }
1343 }
1344}
1345
1346impl TemplateContext for RegisterStepsEmailInUseContext {
1347 fn sample<R: RngExt>(
1348 _now: chrono::DateTime<Utc>,
1349 _rng: &mut R,
1350 _locales: &[DataLocale],
1351 ) -> BTreeMap<SampleIdentifier, Self>
1352 where
1353 Self: Sized,
1354 {
1355 let email = "hello@example.com".to_owned();
1356 let action = PostAuthAction::continue_grant(Ulid::nil());
1357 sample_list(vec![Self::new(email, Some(action))])
1358 }
1359}
1360
1361#[derive(Serialize, Deserialize, Debug, Clone, Copy, Hash, PartialEq, Eq)]
1363#[serde(rename_all = "snake_case")]
1364pub enum RegisterStepsDisplayNameFormField {
1365 DisplayName,
1367}
1368
1369impl FormField for RegisterStepsDisplayNameFormField {
1370 fn keep(&self) -> bool {
1371 match self {
1372 Self::DisplayName => true,
1373 }
1374 }
1375}
1376
1377#[derive(Serialize, Default)]
1379pub struct RegisterStepsDisplayNameContext {
1380 form: FormState<RegisterStepsDisplayNameFormField>,
1381}
1382
1383impl RegisterStepsDisplayNameContext {
1384 #[must_use]
1386 pub fn new() -> Self {
1387 Self::default()
1388 }
1389
1390 #[must_use]
1392 pub fn with_form_state(
1393 mut self,
1394 form_state: FormState<RegisterStepsDisplayNameFormField>,
1395 ) -> Self {
1396 self.form = form_state;
1397 self
1398 }
1399}
1400
1401impl TemplateContext for RegisterStepsDisplayNameContext {
1402 fn sample<R: RngExt>(
1403 _now: chrono::DateTime<chrono::Utc>,
1404 _rng: &mut R,
1405 _locales: &[DataLocale],
1406 ) -> BTreeMap<SampleIdentifier, Self>
1407 where
1408 Self: Sized,
1409 {
1410 sample_list(vec![Self {
1411 form: FormState::default(),
1412 }])
1413 }
1414}
1415
1416#[derive(Serialize, Deserialize, Debug, Clone, Copy, Hash, PartialEq, Eq)]
1418#[serde(rename_all = "snake_case")]
1419pub enum RegisterStepsRegistrationTokenFormField {
1420 Token,
1422}
1423
1424impl FormField for RegisterStepsRegistrationTokenFormField {
1425 fn keep(&self) -> bool {
1426 match self {
1427 Self::Token => true,
1428 }
1429 }
1430}
1431
1432#[derive(Serialize, Default)]
1434pub struct RegisterStepsRegistrationTokenContext {
1435 form: FormState<RegisterStepsRegistrationTokenFormField>,
1436}
1437
1438impl RegisterStepsRegistrationTokenContext {
1439 #[must_use]
1441 pub fn new() -> Self {
1442 Self::default()
1443 }
1444
1445 #[must_use]
1447 pub fn with_form_state(
1448 mut self,
1449 form_state: FormState<RegisterStepsRegistrationTokenFormField>,
1450 ) -> Self {
1451 self.form = form_state;
1452 self
1453 }
1454}
1455
1456impl TemplateContext for RegisterStepsRegistrationTokenContext {
1457 fn sample<R: RngExt>(
1458 _now: chrono::DateTime<chrono::Utc>,
1459 _rng: &mut R,
1460 _locales: &[DataLocale],
1461 ) -> BTreeMap<SampleIdentifier, Self>
1462 where
1463 Self: Sized,
1464 {
1465 sample_list(vec![Self {
1466 form: FormState::default(),
1467 }])
1468 }
1469}
1470
1471#[derive(Serialize, Deserialize, Debug, Clone, Copy, Hash, PartialEq, Eq)]
1473#[serde(rename_all = "snake_case")]
1474pub enum RecoveryStartFormField {
1475 Email,
1477}
1478
1479impl FormField for RecoveryStartFormField {
1480 fn keep(&self) -> bool {
1481 match self {
1482 Self::Email => true,
1483 }
1484 }
1485}
1486
1487#[derive(Serialize, Default)]
1489pub struct RecoveryStartContext {
1490 form: FormState<RecoveryStartFormField>,
1491}
1492
1493impl RecoveryStartContext {
1494 #[must_use]
1496 pub fn new() -> Self {
1497 Self::default()
1498 }
1499
1500 #[must_use]
1502 pub fn with_form_state(self, form: FormState<RecoveryStartFormField>) -> Self {
1503 Self { form }
1504 }
1505}
1506
1507impl TemplateContext for RecoveryStartContext {
1508 fn sample<R: RngExt>(
1509 _now: chrono::DateTime<Utc>,
1510 _rng: &mut R,
1511 _locales: &[DataLocale],
1512 ) -> BTreeMap<SampleIdentifier, Self>
1513 where
1514 Self: Sized,
1515 {
1516 sample_list(vec![
1517 Self::new(),
1518 Self::new().with_form_state(
1519 FormState::default()
1520 .with_error_on_field(RecoveryStartFormField::Email, FieldError::Required),
1521 ),
1522 Self::new().with_form_state(
1523 FormState::default()
1524 .with_error_on_field(RecoveryStartFormField::Email, FieldError::Invalid),
1525 ),
1526 ])
1527 }
1528}
1529
1530#[derive(Serialize)]
1532pub struct RecoveryProgressContext {
1533 session: UserRecoverySession,
1534 resend_failed_due_to_rate_limit: bool,
1536}
1537
1538impl RecoveryProgressContext {
1539 #[must_use]
1541 pub fn new(session: UserRecoverySession, resend_failed_due_to_rate_limit: bool) -> Self {
1542 Self {
1543 session,
1544 resend_failed_due_to_rate_limit,
1545 }
1546 }
1547}
1548
1549impl TemplateContext for RecoveryProgressContext {
1550 fn sample<R: RngExt>(
1551 now: chrono::DateTime<Utc>,
1552 rng: &mut R,
1553 _locales: &[DataLocale],
1554 ) -> BTreeMap<SampleIdentifier, Self>
1555 where
1556 Self: Sized,
1557 {
1558 let session = UserRecoverySession {
1559 id: Ulid::from_datetime_with_rng(now, rng),
1560 email: "name@mail.com".to_owned(),
1561 user_agent: "Mozilla/5.0".to_owned(),
1562 ip_address: None,
1563 locale: "en".to_owned(),
1564 created_at: now,
1565 consumed_at: None,
1566 };
1567
1568 sample_list(vec![
1569 Self {
1570 session: session.clone(),
1571 resend_failed_due_to_rate_limit: false,
1572 },
1573 Self {
1574 session,
1575 resend_failed_due_to_rate_limit: true,
1576 },
1577 ])
1578 }
1579}
1580
1581#[derive(Serialize)]
1583pub struct RecoveryExpiredContext {
1584 session: UserRecoverySession,
1585}
1586
1587impl RecoveryExpiredContext {
1588 #[must_use]
1590 pub fn new(session: UserRecoverySession) -> Self {
1591 Self { session }
1592 }
1593}
1594
1595impl TemplateContext for RecoveryExpiredContext {
1596 fn sample<R: RngExt>(
1597 now: chrono::DateTime<Utc>,
1598 rng: &mut R,
1599 _locales: &[DataLocale],
1600 ) -> BTreeMap<SampleIdentifier, Self>
1601 where
1602 Self: Sized,
1603 {
1604 let session = UserRecoverySession {
1605 id: Ulid::from_datetime_with_rng(now, rng),
1606 email: "name@mail.com".to_owned(),
1607 user_agent: "Mozilla/5.0".to_owned(),
1608 ip_address: None,
1609 locale: "en".to_owned(),
1610 created_at: now,
1611 consumed_at: None,
1612 };
1613
1614 sample_list(vec![Self { session }])
1615 }
1616}
1617#[derive(Serialize, Deserialize, Debug, Clone, Copy, Hash, PartialEq, Eq)]
1619#[serde(rename_all = "snake_case")]
1620pub enum RecoveryFinishFormField {
1621 NewPassword,
1623
1624 NewPasswordConfirm,
1626}
1627
1628impl FormField for RecoveryFinishFormField {
1629 fn keep(&self) -> bool {
1630 false
1631 }
1632}
1633
1634#[derive(Serialize)]
1636pub struct RecoveryFinishContext {
1637 user: User,
1638 form: FormState<RecoveryFinishFormField>,
1639}
1640
1641impl RecoveryFinishContext {
1642 #[must_use]
1644 pub fn new(user: User) -> Self {
1645 Self {
1646 user,
1647 form: FormState::default(),
1648 }
1649 }
1650
1651 #[must_use]
1653 pub fn with_form_state(mut self, form: FormState<RecoveryFinishFormField>) -> Self {
1654 self.form = form;
1655 self
1656 }
1657}
1658
1659impl TemplateContext for RecoveryFinishContext {
1660 fn sample<R: RngExt>(
1661 now: chrono::DateTime<Utc>,
1662 rng: &mut R,
1663 _locales: &[DataLocale],
1664 ) -> BTreeMap<SampleIdentifier, Self>
1665 where
1666 Self: Sized,
1667 {
1668 sample_list(
1669 User::samples(now, rng)
1670 .into_iter()
1671 .flat_map(|user| {
1672 vec![
1673 Self::new(user.clone()),
1674 Self::new(user.clone()).with_form_state(
1675 FormState::default().with_error_on_field(
1676 RecoveryFinishFormField::NewPassword,
1677 FieldError::Invalid,
1678 ),
1679 ),
1680 Self::new(user.clone()).with_form_state(
1681 FormState::default().with_error_on_field(
1682 RecoveryFinishFormField::NewPasswordConfirm,
1683 FieldError::Invalid,
1684 ),
1685 ),
1686 ]
1687 })
1688 .collect(),
1689 )
1690 }
1691}
1692
1693#[derive(Serialize)]
1696pub struct UpstreamExistingLinkContext {
1697 linked_user: User,
1698}
1699
1700impl UpstreamExistingLinkContext {
1701 #[must_use]
1703 pub fn new(linked_user: User) -> Self {
1704 Self { linked_user }
1705 }
1706}
1707
1708impl TemplateContext for UpstreamExistingLinkContext {
1709 fn sample<R: RngExt>(
1710 now: chrono::DateTime<Utc>,
1711 rng: &mut R,
1712 _locales: &[DataLocale],
1713 ) -> BTreeMap<SampleIdentifier, Self>
1714 where
1715 Self: Sized,
1716 {
1717 sample_list(
1718 User::samples(now, rng)
1719 .into_iter()
1720 .map(|linked_user| Self { linked_user })
1721 .collect(),
1722 )
1723 }
1724}
1725
1726#[derive(Serialize)]
1729pub struct UpstreamSuggestLink {
1730 post_logout_action: PostAuthAction,
1731}
1732
1733impl UpstreamSuggestLink {
1734 #[must_use]
1736 pub fn new(link: &UpstreamOAuthLink) -> Self {
1737 Self::for_link_id(link.id)
1738 }
1739
1740 fn for_link_id(id: Ulid) -> Self {
1741 let post_logout_action = PostAuthAction::link_upstream(id);
1742 Self { post_logout_action }
1743 }
1744}
1745
1746impl TemplateContext for UpstreamSuggestLink {
1747 fn sample<R: RngExt>(
1748 now: chrono::DateTime<Utc>,
1749 rng: &mut R,
1750 _locales: &[DataLocale],
1751 ) -> BTreeMap<SampleIdentifier, Self>
1752 where
1753 Self: Sized,
1754 {
1755 let id = Ulid::from_datetime_with_rng(now, rng);
1756 sample_list(vec![Self::for_link_id(id)])
1757 }
1758}
1759
1760#[derive(Serialize, Deserialize, Debug, Clone, Copy, Hash, PartialEq, Eq)]
1762#[serde(rename_all = "snake_case")]
1763pub enum UpstreamRegisterFormField {
1764 Username,
1766
1767 AcceptTerms,
1769}
1770
1771impl FormField for UpstreamRegisterFormField {
1772 fn keep(&self) -> bool {
1773 match self {
1774 Self::Username | Self::AcceptTerms => true,
1775 }
1776 }
1777}
1778
1779#[derive(Serialize)]
1782pub struct UpstreamRegister {
1783 upstream_oauth_link: UpstreamOAuthLink,
1784 upstream_oauth_provider: UpstreamOAuthProvider,
1785 imported_localpart: Option<String>,
1786 force_localpart: bool,
1787 imported_display_name: Option<String>,
1788 force_display_name: bool,
1789 imported_email: Option<String>,
1790 force_email: bool,
1791 form_state: FormState<UpstreamRegisterFormField>,
1792}
1793
1794impl UpstreamRegister {
1795 #[must_use]
1798 pub fn new(
1799 upstream_oauth_link: UpstreamOAuthLink,
1800 upstream_oauth_provider: UpstreamOAuthProvider,
1801 ) -> Self {
1802 Self {
1803 upstream_oauth_link,
1804 upstream_oauth_provider,
1805 imported_localpart: None,
1806 force_localpart: false,
1807 imported_display_name: None,
1808 force_display_name: false,
1809 imported_email: None,
1810 force_email: false,
1811 form_state: FormState::default(),
1812 }
1813 }
1814
1815 pub fn set_localpart(&mut self, localpart: String, force: bool) {
1817 self.imported_localpart = Some(localpart);
1818 self.force_localpart = force;
1819 }
1820
1821 #[must_use]
1823 pub fn with_localpart(self, localpart: String, force: bool) -> Self {
1824 Self {
1825 imported_localpart: Some(localpart),
1826 force_localpart: force,
1827 ..self
1828 }
1829 }
1830
1831 pub fn set_display_name(&mut self, display_name: String, force: bool) {
1833 self.imported_display_name = Some(display_name);
1834 self.force_display_name = force;
1835 }
1836
1837 #[must_use]
1839 pub fn with_display_name(self, display_name: String, force: bool) -> Self {
1840 Self {
1841 imported_display_name: Some(display_name),
1842 force_display_name: force,
1843 ..self
1844 }
1845 }
1846
1847 pub fn set_email(&mut self, email: String, force: bool) {
1849 self.imported_email = Some(email);
1850 self.force_email = force;
1851 }
1852
1853 #[must_use]
1855 pub fn with_email(self, email: String, force: bool) -> Self {
1856 Self {
1857 imported_email: Some(email),
1858 force_email: force,
1859 ..self
1860 }
1861 }
1862
1863 pub fn set_form_state(&mut self, form_state: FormState<UpstreamRegisterFormField>) {
1865 self.form_state = form_state;
1866 }
1867
1868 #[must_use]
1870 pub fn with_form_state(self, form_state: FormState<UpstreamRegisterFormField>) -> Self {
1871 Self { form_state, ..self }
1872 }
1873}
1874
1875impl TemplateContext for UpstreamRegister {
1876 fn sample<R: RngExt>(
1877 now: chrono::DateTime<Utc>,
1878 _rng: &mut R,
1879 _locales: &[DataLocale],
1880 ) -> BTreeMap<SampleIdentifier, Self>
1881 where
1882 Self: Sized,
1883 {
1884 sample_list(vec![Self::new(
1885 UpstreamOAuthLink {
1886 id: Ulid::nil(),
1887 provider_id: Ulid::nil(),
1888 user_id: None,
1889 subject: "subject".to_owned(),
1890 human_account_name: Some("@john".to_owned()),
1891 created_at: now,
1892 },
1893 UpstreamOAuthProvider {
1894 id: Ulid::nil(),
1895 issuer: Some("https://example.com/".to_owned()),
1896 human_name: Some("Example Ltd.".to_owned()),
1897 brand_name: None,
1898 scope: Scope::from_iter([OPENID]),
1899 token_endpoint_auth_method: UpstreamOAuthProviderTokenAuthMethod::ClientSecretBasic,
1900 token_endpoint_signing_alg: None,
1901 id_token_signed_response_alg: JsonWebSignatureAlg::Rs256,
1902 client_id: "client-id".to_owned(),
1903 encrypted_client_secret: None,
1904 claims_imports: UpstreamOAuthProviderClaimsImports::default(),
1905 authorization_endpoint_override: None,
1906 token_endpoint_override: None,
1907 jwks_uri_override: None,
1908 userinfo_endpoint_override: None,
1909 fetch_userinfo: false,
1910 userinfo_signed_response_alg: None,
1911 discovery_mode: UpstreamOAuthProviderDiscoveryMode::Oidc,
1912 pkce_mode: UpstreamOAuthProviderPkceMode::Auto,
1913 response_mode: None,
1914 additional_authorization_parameters: Vec::new(),
1915 forward_login_hint: false,
1916 created_at: now,
1917 disabled_at: None,
1918 on_backchannel_logout: UpstreamOAuthProviderOnBackchannelLogout::DoNothing,
1919 registration_token_required: false,
1920 },
1921 )])
1922 }
1923}
1924
1925#[derive(Serialize, Deserialize, Debug, Clone, Copy, Hash, PartialEq, Eq)]
1927#[serde(rename_all = "snake_case")]
1928pub enum DeviceLinkFormField {
1929 Code,
1931}
1932
1933impl FormField for DeviceLinkFormField {
1934 fn keep(&self) -> bool {
1935 match self {
1936 Self::Code => true,
1937 }
1938 }
1939}
1940
1941#[derive(Serialize, Default, Debug)]
1943pub struct DeviceLinkContext {
1944 form_state: FormState<DeviceLinkFormField>,
1945}
1946
1947impl DeviceLinkContext {
1948 #[must_use]
1950 pub fn new() -> Self {
1951 Self::default()
1952 }
1953
1954 #[must_use]
1956 pub fn with_form_state(mut self, form_state: FormState<DeviceLinkFormField>) -> Self {
1957 self.form_state = form_state;
1958 self
1959 }
1960}
1961
1962impl TemplateContext for DeviceLinkContext {
1963 fn sample<R: RngExt>(
1964 _now: chrono::DateTime<Utc>,
1965 _rng: &mut R,
1966 _locales: &[DataLocale],
1967 ) -> BTreeMap<SampleIdentifier, Self>
1968 where
1969 Self: Sized,
1970 {
1971 sample_list(vec![
1972 Self::new(),
1973 Self::new().with_form_state(
1974 FormState::default()
1975 .with_error_on_field(DeviceLinkFormField::Code, FieldError::Required),
1976 ),
1977 ])
1978 }
1979}
1980
1981#[derive(Serialize, Debug)]
1983pub struct DeviceConsentContext {
1984 grant: DeviceCodeGrant,
1985 client: Client,
1986 matrix_user: MatrixUser,
1987}
1988
1989impl DeviceConsentContext {
1990 #[must_use]
1992 pub fn new(grant: DeviceCodeGrant, client: Client, matrix_user: MatrixUser) -> Self {
1993 Self {
1994 grant,
1995 client,
1996 matrix_user,
1997 }
1998 }
1999}
2000
2001impl TemplateContext for DeviceConsentContext {
2002 fn sample<R: RngExt>(
2003 now: chrono::DateTime<Utc>,
2004 rng: &mut R,
2005 _locales: &[DataLocale],
2006 ) -> BTreeMap<SampleIdentifier, Self>
2007 where
2008 Self: Sized,
2009 {
2010 sample_list(Client::samples(now, rng)
2011 .into_iter()
2012 .map(|client| {
2013 let grant = DeviceCodeGrant {
2014 id: Ulid::from_datetime_with_rng(now, rng),
2015 state: mas_data_model::DeviceCodeGrantState::Pending,
2016 client_id: client.id,
2017 scope: [OPENID].into_iter().collect(),
2018 user_code: mas_data_model::generate_user_code(rng),
2019 device_code: Alphanumeric.sample_string(rng, 32),
2020 created_at: now - Duration::try_minutes(5).unwrap(),
2021 expires_at: now + Duration::try_minutes(25).unwrap(),
2022 ip_address: Some(IpAddr::V4(Ipv4Addr::LOCALHOST)),
2023 user_agent: Some("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.0.0 Safari/537.36".to_owned()),
2024 locale: None,
2025 };
2026 Self {
2027 grant,
2028 client,
2029 matrix_user: MatrixUser {
2030 mxid: "@alice:example.com".to_owned(),
2031 display_name: Some("Alice".to_owned()),
2032 }
2033 }
2034 })
2035 .collect())
2036 }
2037}
2038
2039#[derive(Serialize)]
2042pub struct AccountInactiveContext {
2043 user: User,
2044
2045 #[serde(skip_serializing_if = "Option::is_none")]
2048 post_logout_action: Option<PostAuthAction>,
2049}
2050
2051impl AccountInactiveContext {
2052 #[must_use]
2054 pub fn new(user: User) -> Self {
2055 Self {
2056 user,
2057 post_logout_action: None,
2058 }
2059 }
2060
2061 #[must_use]
2063 pub fn with_post_auth_action(mut self, action: Option<PostAuthAction>) -> Self {
2064 self.post_logout_action = action;
2065 self
2066 }
2067}
2068
2069impl TemplateContext for AccountInactiveContext {
2070 fn sample<R: RngExt>(
2071 now: chrono::DateTime<Utc>,
2072 rng: &mut R,
2073 _locales: &[DataLocale],
2074 ) -> BTreeMap<SampleIdentifier, Self>
2075 where
2076 Self: Sized,
2077 {
2078 let action = PostAuthAction::continue_grant(Ulid::from_datetime_with_rng(now, rng));
2079 sample_list(
2080 User::samples(now, rng)
2081 .into_iter()
2082 .flat_map(|user| {
2083 [
2086 AccountInactiveContext::new(user.clone()),
2087 AccountInactiveContext::new(user)
2088 .with_post_auth_action(Some(action.clone())),
2089 ]
2090 })
2091 .collect(),
2092 )
2093 }
2094}
2095
2096#[derive(Serialize)]
2098pub struct DeviceNameContext {
2099 client: Client,
2100 raw_user_agent: String,
2101}
2102
2103impl DeviceNameContext {
2104 #[must_use]
2106 pub fn new(client: Client, user_agent: Option<String>) -> Self {
2107 Self {
2108 client,
2109 raw_user_agent: user_agent.unwrap_or_default(),
2110 }
2111 }
2112}
2113
2114impl TemplateContext for DeviceNameContext {
2115 fn sample<R: RngExt>(
2116 now: chrono::DateTime<Utc>,
2117 rng: &mut R,
2118 _locales: &[DataLocale],
2119 ) -> BTreeMap<SampleIdentifier, Self>
2120 where
2121 Self: Sized,
2122 {
2123 sample_list(Client::samples(now, rng)
2124 .into_iter()
2125 .map(|client| DeviceNameContext {
2126 client,
2127 raw_user_agent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.0.0 Safari/537.36".to_owned(),
2128 })
2129 .collect())
2130 }
2131}
2132
2133#[derive(Serialize)]
2135pub struct FormPostContext<T> {
2136 redirect_uri: Option<Url>,
2137 params: T,
2138}
2139
2140impl<T: TemplateContext> TemplateContext for FormPostContext<T> {
2141 fn sample<R: RngExt>(
2142 now: chrono::DateTime<Utc>,
2143 rng: &mut R,
2144 locales: &[DataLocale],
2145 ) -> BTreeMap<SampleIdentifier, Self>
2146 where
2147 Self: Sized,
2148 {
2149 let sample_params = T::sample(now, rng, locales);
2150 sample_params
2151 .into_iter()
2152 .map(|(k, params)| {
2153 (
2154 k,
2155 FormPostContext {
2156 redirect_uri: "https://example.com/callback".parse().ok(),
2157 params,
2158 },
2159 )
2160 })
2161 .collect()
2162 }
2163}
2164
2165impl<T> FormPostContext<T> {
2166 pub fn new_for_url(redirect_uri: Url, params: T) -> Self {
2169 Self {
2170 redirect_uri: Some(redirect_uri),
2171 params,
2172 }
2173 }
2174
2175 pub fn new_for_current_url(params: T) -> Self {
2178 Self {
2179 redirect_uri: None,
2180 params,
2181 }
2182 }
2183
2184 pub fn with_language(self, lang: &DataLocale) -> WithLanguage<Self> {
2189 WithLanguage {
2190 lang: lang.to_string(),
2191 inner: self,
2192 }
2193 }
2194}
2195
2196#[derive(Default, Serialize, Debug, Clone)]
2198pub struct ErrorContext {
2199 code: Option<&'static str>,
2200 description: Option<String>,
2201 details: Option<String>,
2202 lang: Option<String>,
2203}
2204
2205impl std::fmt::Display for ErrorContext {
2206 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
2207 if let Some(code) = &self.code {
2208 writeln!(f, "code: {code}")?;
2209 }
2210 if let Some(description) = &self.description {
2211 writeln!(f, "{description}")?;
2212 }
2213
2214 if let Some(details) = &self.details {
2215 writeln!(f, "details: {details}")?;
2216 }
2217
2218 Ok(())
2219 }
2220}
2221
2222impl TemplateContext for ErrorContext {
2223 fn sample<R: RngExt>(
2224 _now: chrono::DateTime<Utc>,
2225 _rng: &mut R,
2226 _locales: &[DataLocale],
2227 ) -> BTreeMap<SampleIdentifier, Self>
2228 where
2229 Self: Sized,
2230 {
2231 sample_list(vec![
2232 Self::new()
2233 .with_code("sample_error")
2234 .with_description("A fancy description".into())
2235 .with_details("Something happened".into()),
2236 Self::new().with_code("another_error"),
2237 Self::new(),
2238 ])
2239 }
2240}
2241
2242impl ErrorContext {
2243 #[must_use]
2245 pub fn new() -> Self {
2246 Self::default()
2247 }
2248
2249 #[must_use]
2251 pub fn with_code(mut self, code: &'static str) -> Self {
2252 self.code = Some(code);
2253 self
2254 }
2255
2256 #[must_use]
2258 pub fn with_description(mut self, description: String) -> Self {
2259 self.description = Some(description);
2260 self
2261 }
2262
2263 #[must_use]
2265 pub fn with_details(mut self, details: String) -> Self {
2266 self.details = Some(details);
2267 self
2268 }
2269
2270 #[must_use]
2272 pub fn with_language(mut self, lang: &DataLocale) -> Self {
2273 self.lang = Some(lang.to_string());
2274 self
2275 }
2276
2277 #[must_use]
2279 pub fn code(&self) -> Option<&'static str> {
2280 self.code
2281 }
2282
2283 #[must_use]
2285 pub fn description(&self) -> Option<&str> {
2286 self.description.as_deref()
2287 }
2288
2289 #[must_use]
2291 pub fn details(&self) -> Option<&str> {
2292 self.details.as_deref()
2293 }
2294}
2295
2296#[derive(Serialize)]
2298pub struct NotFoundContext {
2299 method: String,
2300 version: String,
2301 uri: String,
2302}
2303
2304impl NotFoundContext {
2305 #[must_use]
2307 pub fn new(method: &Method, version: Version, uri: &Uri) -> Self {
2308 Self {
2309 method: method.to_string(),
2310 version: format!("{version:?}"),
2311 uri: uri.to_string(),
2312 }
2313 }
2314}
2315
2316impl TemplateContext for NotFoundContext {
2317 fn sample<R: RngExt>(
2318 _now: DateTime<Utc>,
2319 _rng: &mut R,
2320 _locales: &[DataLocale],
2321 ) -> BTreeMap<SampleIdentifier, Self>
2322 where
2323 Self: Sized,
2324 {
2325 sample_list(vec![
2326 Self::new(&Method::GET, Version::HTTP_11, &"/".parse().unwrap()),
2327 Self::new(&Method::POST, Version::HTTP_2, &"/foo/bar".parse().unwrap()),
2328 Self::new(
2329 &Method::PUT,
2330 Version::HTTP_10,
2331 &"/foo?bar=baz".parse().unwrap(),
2332 ),
2333 ])
2334 }
2335}