Skip to main content

fractal/login/
mod.rs

1use std::net::{Ipv4Addr, Ipv6Addr};
2
3use adw::{prelude::*, subclass::prelude::*};
4use as_variant::as_variant;
5use gettextrs::gettext;
6use gtk::{glib, glib::clone};
7use matrix_sdk::{
8    Client, ClientBuildError, Error,
9    authentication::oauth::{
10        ClientRegistrationData,
11        registration::{ApplicationType, ClientMetadata, Localized, OAuthGrantType},
12    },
13    config::RequestConfig,
14    utils::local_server::{LocalServerRedirectHandle, QueryString},
15};
16use ruma::{api::client::session::get_login_types::v3::LoginType, serde::Raw};
17use tracing::{error, warn};
18use url::Url;
19
20mod advanced_dialog;
21mod greeter;
22mod homeserver_page;
23mod in_browser_page;
24mod local_server;
25mod method_page;
26mod session_setup_view;
27
28use self::{
29    greeter::Greeter,
30    homeserver_page::{HomeserverData, LoginHomeserverPage},
31    in_browser_page::LoginInBrowserPage,
32    local_server::spawn_local_server,
33    method_page::{LoginMatrixData, LoginMatrixPasswordData, LoginMethodPage, LoginMethodPageData},
34    session_setup_view::SessionSetupView,
35};
36use crate::{
37    APP_HOMEPAGE_URL, APP_NAME, Application, RUNTIME, SETTINGS_KEY_CURRENT_SESSION, Window,
38    components::OfflineBanner, prelude::*, secret::Secret, session::Session, spawn, spawn_tokio,
39    toast, utils::AbortableHandle,
40};
41
42/// A page of the login stack.
43///
44/// The `Ord` implementation follows the order of the pages in the login flow,
45/// so it can be used to check its progress.
46#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
47enum LoginPage {
48    /// The greeter page.
49    Greeter,
50    /// The homeserver page.
51    Homeserver,
52    /// The page to select a login method.
53    Method,
54    /// The page to log in with the browser.
55    InBrowser,
56    /// The session setup stack.
57    SessionSetup,
58    /// The login is completed.
59    Completed,
60}
61
62impl LoginPage {
63    /// Get the tag for this page.
64    const fn tag(self) -> &'static str {
65        match self {
66            Self::Greeter => Greeter::TAG,
67            Self::Homeserver => LoginHomeserverPage::TAG,
68            Self::Method => LoginMethodPage::TAG,
69            Self::InBrowser => LoginInBrowserPage::TAG,
70            Self::SessionSetup => SessionSetupView::TAG,
71            Self::Completed => "completed",
72        }
73    }
74
75    /// Get the page matching the given tag.
76    ///
77    /// Panics if the tag does not match any of the variants.
78    fn from_tag(tag: &str) -> Self {
79        match tag {
80            Greeter::TAG => Self::Greeter,
81            LoginHomeserverPage::TAG => Self::Homeserver,
82            LoginMethodPage::TAG => Self::Method,
83            LoginInBrowserPage::TAG => Self::InBrowser,
84            SessionSetupView::TAG => Self::SessionSetup,
85            "completed" => Self::Completed,
86            _ => panic!("Unknown LoginPage: {tag}"),
87        }
88    }
89}
90
91mod imp {
92    use std::cell::RefCell;
93
94    use glib::subclass::InitializingObject;
95
96    use super::*;
97
98    #[derive(Debug, Default, gtk::CompositeTemplate, glib::Properties)]
99    #[template(resource = "/org/gnome/Fractal/ui/login/mod.ui")]
100    #[properties(wrapper_type = super::Login)]
101    pub struct Login {
102        #[template_child]
103        navigation: TemplateChild<adw::NavigationView>,
104        #[template_child]
105        pub(super) greeter: TemplateChild<Greeter>,
106        #[template_child]
107        homeserver_page: TemplateChild<LoginHomeserverPage>,
108        #[template_child]
109        method_page: TemplateChild<LoginMethodPage>,
110        #[template_child]
111        in_browser_page: TemplateChild<LoginInBrowserPage>,
112        #[template_child]
113        done_button: TemplateChild<gtk::Button>,
114        /// The data to use to reach the homeserver.
115        homeserver_data: RefCell<Option<HomeserverData>>,
116        /// The Matrix client used to log in.
117        client: RefCell<Option<Client>>,
118        /// A handle to the local server to wait for the redirect in the
119        /// browser.
120        local_server_handle: RefCell<Option<LocalServerRedirectHandle>>,
121        /// The data to use to log in with the browser.
122        in_browser_data: RefCell<Option<LoginInBrowserData>>,
123        /// The session that was just logged in.
124        session: RefCell<Option<Session>>,
125        /// An abort handle for the ongoing action.
126        abort_handle: AbortableHandle,
127    }
128
129    #[glib::object_subclass]
130    impl ObjectSubclass for Login {
131        const NAME: &'static str = "Login";
132        type Type = super::Login;
133        type ParentType = adw::Bin;
134
135        fn class_init(klass: &mut Self::Class) {
136            OfflineBanner::ensure_type();
137
138            Self::bind_template(klass);
139            Self::bind_template_callbacks(klass);
140
141            klass.set_css_name("login");
142            klass.set_accessible_role(gtk::AccessibleRole::Group);
143        }
144
145        fn instance_init(obj: &InitializingObject<Self>) {
146            obj.init_template();
147        }
148    }
149
150    #[glib::derived_properties]
151    impl ObjectImpl for Login {
152        fn constructed(&self) {
153            self.parent_constructed();
154
155            self.navigation.connect_popped(clone!(
156                #[weak(rename_to = imp)]
157                self,
158                move |_, _| {
159                    imp.navigation_popped();
160                }
161            ));
162
163            self.homeserver_page.connect_homeserver_data(clone!(
164                #[weak(rename_to = imp)]
165                self,
166                move |data| {
167                    spawn!(async move {
168                        imp.check_homeserver_data(data).await;
169                        imp.homeserver_page.set_is_loading(false);
170                    });
171                }
172            ));
173
174            self.method_page.connect_login_data(clone!(
175                #[weak(rename_to = imp)]
176                self,
177                move |data| {
178                    spawn!(async move {
179                        imp.log_in_with_matrix(data).await;
180                        imp.method_page.set_is_loading(false);
181                    });
182                }
183            ));
184
185            self.in_browser_page.connect_launch_url(clone!(
186                #[weak(rename_to = imp)]
187                self,
188                move |()| {
189                    spawn!(async move {
190                        if imp.launch_in_browser_url().await.is_err() {
191                            imp.navigation.pop();
192                        }
193                    });
194                }
195            ));
196        }
197
198        fn dispose(&self) {
199            self.drop_client();
200            self.drop_session();
201        }
202    }
203
204    impl WidgetImpl for Login {
205        fn grab_focus(&self) -> bool {
206            match self.visible_page() {
207                LoginPage::Greeter => self.greeter.grab_focus(),
208                LoginPage::Homeserver => self.homeserver_page.grab_focus(),
209                LoginPage::Method => self.method_page.grab_focus(),
210                LoginPage::InBrowser => self.in_browser_page.grab_focus(),
211                LoginPage::SessionSetup => {
212                    if let Some(session_setup) = self.session_setup() {
213                        session_setup.grab_focus()
214                    } else {
215                        false
216                    }
217                }
218                LoginPage::Completed => self.done_button.grab_focus(),
219            }
220        }
221    }
222
223    impl BinImpl for Login {}
224    impl AccessibleImpl for Login {}
225
226    #[gtk::template_callbacks]
227    impl Login {
228        /// The visible page of the view.
229        fn visible_page(&self) -> LoginPage {
230            LoginPage::from_tag(
231                &self
232                    .navigation
233                    .visible_page()
234                    .expect("Login navigation view should always have a visible page")
235                    .tag()
236                    .expect("Login navigation page should always have a tag"),
237            )
238        }
239
240        /// Get the session setup view, if any.
241        fn session_setup(&self) -> Option<SessionSetupView> {
242            self.navigation
243                .find_page(LoginPage::SessionSetup.tag())
244                .and_downcast()
245        }
246
247        /// Handle when the user went back in the login flow.
248        fn navigation_popped(&self) {
249            // Abort the ongoing task, if any.
250            self.abort_handle.abort();
251
252            let visible_page = self.visible_page();
253
254            if visible_page <= LoginPage::InBrowser {
255                // Drop the session because it is bound to the account.
256                self.drop_session();
257            }
258
259            if visible_page <= LoginPage::Method {
260                // Drop the in-browser data because we need to recompute it for retries.
261                self.local_server_handle.take();
262                self.in_browser_data.take();
263            }
264
265            if visible_page <= LoginPage::Homeserver {
266                // Drop the client because it is bound to the homeserver.
267                self.drop_client();
268                // Clear the user credentials for security.
269                self.method_page.reset();
270            }
271        }
272
273        /// Try to build a client with the current homeserver.
274        ///
275        /// Returns `Ok(None)` if the task was aborted.
276        async fn build_client(&self) -> Result<Option<Client>, ClientBuildError> {
277            let Some(homeserver_data) = self.homeserver_data.borrow().clone() else {
278                return Err(ClientBuildError::MissingHomeserver);
279            };
280
281            let handle = spawn_tokio!(async move {
282                let mut builder =
283                    Client::builder().request_config(RequestConfig::new().retry_limit(2));
284                let mut check_homeserver_manually = false;
285
286                match homeserver_data {
287                    HomeserverData::ServerName(server_name) => {
288                        builder = builder.server_name_or_homeserver_url(server_name);
289                    }
290                    HomeserverData::Url(url) => {
291                        builder = builder.respect_login_well_known(false).homeserver_url(url);
292                        check_homeserver_manually = true;
293                    }
294                }
295
296                let client = builder.build().await?;
297
298                if check_homeserver_manually {
299                    // Call the `GET /versions` endpoint to make sure that the URL belongs to a
300                    // Matrix homeserver.
301                    client.server_versions().await?;
302                }
303
304                Ok(client)
305            });
306
307            let Some(result) = self.abort_handle.await_task(handle).await else {
308                // The task was aborted.
309                return Ok(None);
310            };
311
312            match result {
313                Ok(client) => {
314                    self.client.replace(Some(client.clone()));
315                    Ok(Some(client))
316                }
317                Err(error) => {
318                    warn!("Could not discover homeserver: {error}");
319                    Err(error)
320                }
321            }
322        }
323
324        /// The Matrix client.
325        pub(super) async fn client(&self) -> Option<Client> {
326            if let Some(client) = self.client.borrow().clone() {
327                return Some(client);
328            }
329
330            // If the client was dropped, try to recreate it.
331            self.build_client().await.ok().flatten()
332        }
333
334        /// Drop the Matrix client.
335        fn drop_client(&self) {
336            if let Some(client) = self.client.take() {
337                // The `Client` needs to access a tokio runtime when it is dropped.
338                let _guard = RUNTIME.enter();
339                drop(client);
340            }
341        }
342
343        /// Drop the session and clean up its data from the system.
344        fn drop_session(&self) {
345            if let Some(session) = self.session.take() {
346                spawn!(async move {
347                    let _ = session.log_out().await;
348                });
349            }
350        }
351
352        /// Spawn a local server for listening to redirects.
353        ///
354        /// Returns `Ok(None)` if the task was aborted.
355        async fn spawn_local_server(&self) -> Result<Option<(Url, LocalServerRedirectHandle)>, ()> {
356            let handle = spawn_tokio!(async move { spawn_local_server().await });
357
358            let Some(result) = self.abort_handle.await_task(handle).await else {
359                // The task was aborted.
360                return Ok(None);
361            };
362
363            result.map(Some)
364        }
365
366        /// Check if the homeserver data that was entered by the user allows us
367        /// to log in.
368        async fn check_homeserver_data(&self, homeserver_data: HomeserverData) {
369            self.homeserver_data.replace(Some(homeserver_data));
370
371            let client = match self.build_client().await {
372                Ok(Some(client)) => client,
373                Ok(None) => {
374                    // The task was aborted.
375                    return;
376                }
377                Err(error) => {
378                    toast!(self.obj(), error.to_user_facing());
379                    return;
380                }
381            };
382
383            if self.discover_login_api(client).await.is_err() {
384                toast!(self.obj(), gettext("Could not set up login"));
385            }
386        }
387
388        /// Discover the login API supported by the homeserver.
389        async fn discover_login_api(&self, client: Client) -> Result<(), ()> {
390            // First, check if the server supports the OAuth 2.0 API.
391            let oauth = client.oauth();
392            let handle = spawn_tokio!(async move { oauth.server_metadata().await });
393
394            let Some(result) = self.abort_handle.await_task(handle).await else {
395                // The task was aborted.
396                return Ok(());
397            };
398
399            match result {
400                Ok(_) => {
401                    // Prefer the OAuth 2.0 API.
402                    self.init_oauth_login(client).await
403                }
404                Err(error) => {
405                    if error.is_not_supported() {
406                        // Fallback to the Matrix native API.
407                        self.init_matrix_login(client).await
408                    } else {
409                        warn!("Could not get authorization server metadata: {error}");
410                        Err(())
411                    }
412                }
413            }
414        }
415
416        /// Prepare to log in via the OAuth 2.0 API.
417        async fn init_oauth_login(&self, client: Client) -> Result<(), ()> {
418            let Some((redirect_uri, local_server_handle)) = self.spawn_local_server().await? else {
419                // The task was aborted.
420                return Ok(());
421            };
422
423            let oauth = client.oauth();
424            let handle = spawn_tokio!(async move {
425                oauth
426                    .login(redirect_uri, None, Some(client_registration_data()), None)
427                    .build()
428                    .await
429            });
430
431            let Some(result) = self.abort_handle.await_task(handle).await else {
432                // The task was aborted.
433                return Ok(());
434            };
435
436            let authorization_data = match result {
437                Ok(authorization_data) => authorization_data,
438                Err(error) => {
439                    warn!("Could not construct OAuth 2.0 authorization URL: {error}");
440                    return Err(());
441                }
442            };
443
444            self.local_server_handle.replace(Some(local_server_handle));
445            self.in_browser_data
446                .replace(Some(LoginInBrowserData::OAuth(authorization_data.url)));
447            self.navigation.push_by_tag(LoginPage::InBrowser.tag());
448
449            Ok(())
450        }
451
452        /// Prepare to log in via the Matrix native API.
453        async fn init_matrix_login(&self, client: Client) -> Result<(), ()> {
454            let matrix_auth = client.matrix_auth();
455            let handle = spawn_tokio!(async move { matrix_auth.get_login_types().await });
456
457            let Some(result) = self.abort_handle.await_task(handle).await else {
458                // The task was aborted.
459                return Ok(());
460            };
461
462            let login_types = match result {
463                Ok(response) => response.flows,
464                Err(error) => {
465                    warn!("Could not get available Matrix login types: {error}");
466                    return Err(());
467                }
468            };
469
470            let supports_password = login_types
471                .iter()
472                .any(|login_type| matches!(login_type, LoginType::Password(_)));
473            let supports_sso = login_types
474                .iter()
475                .any(|login_type| matches!(login_type, LoginType::Sso(_)));
476
477            if supports_password {
478                let domain_name = self
479                    .homeserver_data
480                    .borrow()
481                    .as_ref()
482                    .and_then(|data| as_variant!(data, HomeserverData::ServerName))
483                    .cloned();
484
485                let data = LoginMethodPageData {
486                    homeserver_url: &client.homeserver(),
487                    domain_name: domain_name.as_deref(),
488                    supports_sso,
489                };
490
491                self.show_method_page(data);
492                Ok(())
493            } else {
494                self.init_matrix_sso_login(client).await
495            }
496        }
497
498        /// Prepare to log in via the Matrix SSO API.
499        async fn init_matrix_sso_login(&self, client: Client) -> Result<(), ()> {
500            let Some((redirect_uri, local_server_handle)) = self.spawn_local_server().await? else {
501                // The task was aborted.
502                return Ok(());
503            };
504
505            let matrix_auth = client.matrix_auth();
506            let handle = spawn_tokio!(async move {
507                matrix_auth
508                    .get_sso_login_url(redirect_uri.as_str(), None)
509                    .await
510            });
511
512            let Some(result) = self.abort_handle.await_task(handle).await else {
513                // The task was aborted.
514                return Ok(());
515            };
516
517            match result {
518                Ok(url) => {
519                    self.local_server_handle.replace(Some(local_server_handle));
520                    self.in_browser_data
521                        .replace(Some(LoginInBrowserData::MatrixSso(url)));
522                    self.navigation.push_by_tag(LoginPage::InBrowser.tag());
523                    Ok(())
524                }
525                Err(error) => {
526                    warn!("Could not build Matrix SSO URL: {error}");
527                    Err(())
528                }
529            }
530        }
531
532        /// Show the page to chose a login method with the given data.
533        fn show_method_page(&self, data: LoginMethodPageData<'_>) {
534            self.method_page.update(data);
535            self.navigation.push_by_tag(LoginPage::Method.tag());
536        }
537
538        /// Log in with the given Matrix native flow.
539        async fn log_in_with_matrix(&self, data: LoginMatrixData) {
540            let Some(client) = self.client().await else {
541                toast!(self.obj(), gettext("Could not set up login"));
542                return;
543            };
544
545            match data {
546                LoginMatrixData::Password(password_data) => {
547                    self.log_in_with_matrix_password(client, password_data)
548                        .await;
549                }
550                LoginMatrixData::Sso => {
551                    if self.init_matrix_sso_login(client).await.is_err() {
552                        toast!(self.obj(), gettext("Could not set up login"));
553                    }
554                }
555            }
556        }
557
558        /// Log in with the Matrix native password flow.
559        async fn log_in_with_matrix_password(
560            &self,
561            client: Client,
562            password_data: LoginMatrixPasswordData,
563        ) {
564            let matrix_auth = client.matrix_auth();
565            let handle = spawn_tokio!(async move {
566                matrix_auth
567                    .login_username(&password_data.username, &password_data.password)
568                    .initial_device_display_name(APP_NAME)
569                    .send()
570                    .await
571            });
572
573            let Some(result) = self.abort_handle.await_task(handle).await else {
574                // The task was aborted.
575                return;
576            };
577
578            match result {
579                Ok(_) => {
580                    let _ = self.create_session(client).await;
581                }
582                Err(error) => {
583                    warn!("Could not log in: {error}");
584                    toast!(self.obj(), error.to_user_facing());
585                }
586            }
587        }
588
589        /// Open the current URL to log in with the browser.
590        async fn launch_in_browser_url(&self) -> Result<(), ()> {
591            let Some(data) = self.in_browser_data.borrow().clone() else {
592                error!("Could not launch URI: missing in-browser data");
593                toast!(self.obj(), gettext("Could not open URL"));
594                return Err(());
595            };
596
597            if let Err(error) = gtk::UriLauncher::new(data.url())
598                .launch_future(self.obj().root().and_downcast_ref::<gtk::Window>())
599                .await
600            {
601                error!("Could not launch URI: {error}");
602                toast!(self.obj(), gettext("Could not open URL"));
603                return Err(());
604            }
605
606            let Some(local_server_handle) = self.local_server_handle.take() else {
607                // If we don't have the server handle, we are already waiting for the redirect.
608                return Ok(());
609            };
610
611            let handle = spawn_tokio!(async move { local_server_handle.await });
612
613            let Some(result) = self.abort_handle.await_task(handle).await else {
614                // The task was aborted.
615                return Ok(());
616            };
617
618            // This should show a notification for the user to go back to this app.
619            if let Some(window) = self.obj().root().and_downcast::<gtk::Window>() {
620                window.present();
621            }
622
623            let Some(query_string) = result else {
624                warn!("Could not log in: missing query string in redirect URI");
625                toast!(self.obj(), gettext("An unexpected error occurred."));
626                return Err(());
627            };
628
629            match &data {
630                LoginInBrowserData::OAuth(_) => self.finish_oauth_login(query_string).await,
631                LoginInBrowserData::MatrixSso(_) => {
632                    self.finish_matrix_sso_login(query_string).await
633                }
634            }
635        }
636
637        /// Finish the OAuth 2.0 login process.
638        async fn finish_oauth_login(&self, query_string: QueryString) -> Result<(), ()> {
639            let Some(client) = self.client().await else {
640                toast!(self.obj(), gettext("Could not set up login"));
641                return Err(());
642            };
643
644            let oauth = client.oauth();
645            let handle = spawn_tokio!(async move { oauth.finish_login(query_string.into()).await });
646
647            let Some(result) = self.abort_handle.await_task(handle).await else {
648                // The task was aborted.
649                return Ok(());
650            };
651
652            match result {
653                Ok(()) => self.create_session(client).await,
654                Err(error) => {
655                    warn!("Could not log in via OAuth 2.0: {error}");
656                    toast!(self.obj(), error.to_user_facing());
657                    Err(())
658                }
659            }
660        }
661
662        /// Finish the Matrix SSO login process.
663        async fn finish_matrix_sso_login(&self, query_string: QueryString) -> Result<(), ()> {
664            let Some(client) = self.client().await else {
665                toast!(self.obj(), gettext("Could not set up login"));
666                return Err(());
667            };
668
669            let matrix_auth = client.matrix_auth();
670            let handle = spawn_tokio!(async move {
671                matrix_auth
672                    .login_with_sso_callback(query_string.into())
673                    .map_err(|error| Error::UnknownError(error.into()))?
674                    .initial_device_display_name(APP_NAME)
675                    .await
676            });
677
678            let Some(result) = self.abort_handle.await_task(handle).await else {
679                // The task was aborted.
680                return Ok(());
681            };
682
683            match result {
684                Ok(_) => self.create_session(client).await,
685                Err(error) => {
686                    warn!("Could not log in via SSO: {error}");
687                    toast!(self.obj(), error.to_user_facing());
688                    Err(())
689                }
690            }
691        }
692
693        /// Create the session after a successful login.
694        pub(super) async fn create_session(&self, client: Client) -> Result<(), ()> {
695            match Session::create(&client).await {
696                Ok(session) => {
697                    self.init_session(session).await;
698                    Ok(())
699                }
700                Err(error) => {
701                    warn!("Could not create session: {error}");
702                    toast!(self.obj(), error.to_user_facing());
703                    Err(())
704                }
705            }
706        }
707
708        /// Initialize the given session.
709        async fn init_session(&self, session: Session) {
710            let setup_view = SessionSetupView::new(&session);
711            setup_view.connect_completed(clone!(
712                #[weak(rename_to = imp)]
713                self,
714                move |_| {
715                    imp.navigation.push_by_tag(LoginPage::Completed.tag());
716                }
717            ));
718            self.navigation.push(&setup_view);
719
720            self.drop_client();
721            self.session.replace(Some(session.clone()));
722
723            // Save ID of logging in session to GSettings
724            let settings = Application::default().settings();
725            if let Err(err) =
726                settings.set_string(SETTINGS_KEY_CURRENT_SESSION, session.session_id())
727            {
728                warn!("Could not save current session: {err}");
729            }
730
731            let session_info = session.info().clone();
732
733            if Secret::store_session(session_info).await.is_err() {
734                toast!(self.obj(), gettext("Could not store session"));
735            }
736
737            session.prepare().await;
738        }
739
740        /// Finish the login process and show the session.
741        #[template_callback]
742        fn finish_login(&self) {
743            let Some(window) = self.obj().root().and_downcast::<Window>() else {
744                return;
745            };
746
747            if let Some(session) = self.session.take() {
748                window.add_session(session);
749            }
750
751            self.reset();
752        }
753
754        /// Connect to the signal to go back from this view.
755        pub(super) fn connect_go_back<F>(&self, callback: F)
756        where
757            F: Fn() + 'static,
758        {
759            self.greeter.connect_go_back(clone!(
760                #[weak(rename_to = imp)]
761                self,
762                move || {
763                    callback();
764                    imp.reset();
765                }
766            ));
767        }
768
769        /// Reset the login view.
770        fn reset(&self) {
771            // Reset homeserver data and page.
772            self.homeserver_data.take();
773            self.homeserver_page.reset();
774
775            // Reinitialize UI.
776            // This should clean more data with the resulting call to
777            // `navigation_popped()`.
778            self.navigation.pop_to_tag(LoginPage::Greeter.tag());
779        }
780    }
781}
782
783glib::wrapper! {
784    /// A widget managing the login flow.
785    pub struct Login(ObjectSubclass<imp::Login>)
786        @extends gtk::Widget, adw::Bin,
787        @implements gtk::Accessible, gtk::Buildable, gtk::ConstraintTarget;
788}
789
790impl Login {
791    pub fn new() -> Self {
792        glib::Object::new()
793    }
794
795    /// Set whether the user can go back from this view.
796    pub(super) fn set_can_go_back(&self, can_go_back: bool) {
797        self.imp().greeter.set_can_go_back(can_go_back);
798    }
799
800    /// Connect to the signal to go back from this view.
801    pub(super) fn connect_go_back<F>(&self, callback: F)
802    where
803        F: Fn() + 'static,
804    {
805        self.imp().connect_go_back(callback);
806    }
807}
808
809/// Data for logging in via the browser.
810#[derive(Debug, Clone)]
811enum LoginInBrowserData {
812    /// Log in via the OAuth 2.0 API with the given URL.
813    OAuth(Url),
814
815    /// Log in via the Matrix native SSO API with the given URL.
816    MatrixSso(String),
817}
818
819impl LoginInBrowserData {
820    /// Get the URL to open in the browser.
821    fn url(&self) -> &str {
822        match self {
823            Self::OAuth(url) => url.as_str(),
824            Self::MatrixSso(url) => url,
825        }
826    }
827}
828
829/// Client registration data for the OAuth 2.0 API.
830fn client_registration_data() -> ClientRegistrationData {
831    // Register the IPv4 and IPv6 localhost APIs as we use a local server for the
832    // redirection.
833    let ipv4_localhost_uri = Url::parse(&format!("http://{}/", Ipv4Addr::LOCALHOST))
834        .expect("IPv4 localhost address should be a valid URL");
835    let ipv6_localhost_uri = Url::parse(&format!("http://[{}]/", Ipv6Addr::LOCALHOST))
836        .expect("IPv6 localhost address should be a valid URL");
837
838    let client_uri =
839        Url::parse(APP_HOMEPAGE_URL).expect("application homepage URL should be a valid URL");
840
841    let mut client_metadata = ClientMetadata::new(
842        ApplicationType::Native,
843        vec![OAuthGrantType::AuthorizationCode {
844            redirect_uris: vec![ipv4_localhost_uri, ipv6_localhost_uri],
845        }],
846        Localized::new(client_uri, None),
847    );
848    client_metadata.client_name = Some(Localized::new(APP_NAME.to_owned(), None));
849
850    Raw::new(&client_metadata)
851        .expect("client metadata should serialize to JSON successfully")
852        .into()
853}
854
855#[cfg(test)]
856mod tests {
857    use super::Login;
858    use crate::utils::tests::load_gresources;
859
860    #[gtk::test]
861    fn construct() {
862        // Check that the GObject is constructed successfully, i.e. the template file is
863        // valid.
864        load_gresources();
865        Login::new();
866    }
867}