Skip to main content

renox_oauth/
lib.rs

1//! Social login for Renox apps: "Continue with Google" and "Continue with
2//! GitHub" on the login and register pages, linked to the app's `users`.
3//!
4//! ```
5//! use renox::prelude::*;
6//! use renox_oauth::OAuth;
7//!
8//! # let _ =
9//! App::new()
10//!     .module(Auth::new().account()) // the account page lists linked logins
11//!     .module(OAuth::new().google().github()) // GOOGLE_CLIENT_ID, GITHUB_CLIENT_ID, … in .env
12//! # ;
13//! ```
14//!
15//! For company sign-in, [`Microsoft`] (one tenant), [`Google::hosted_domain`] and
16//! [`OAuth::allow_domains`] accept only the organisation's own accounts.
17//!
18//! The authorization code flow with PKCE (S256) and a single-use `state`
19//! bound to the session. A provider account logs in the user it is linked
20//! to; at a first login, it is linked to the account with the same
21//! **verified** address, or makes a new account (without a password) when
22//! registration is open. Users link and unlink providers from their account
23//! page. The guide is docs/oauth.md in the Renox repository.
24
25#![warn(missing_docs)]
26
27use std::fmt;
28use std::sync::Arc;
29
30use renox::db::Migration;
31use renox::prelude::*;
32use serde::Serialize;
33
34pub mod events;
35pub mod github;
36pub mod google;
37mod handlers;
38pub mod microsoft;
39mod model;
40pub mod provider;
41
42pub use events::{AccountLinked, AccountUnlinked, LoggedInWith, OAuthRefused};
43pub use github::GitHub;
44pub use google::Google;
45pub use microsoft::Microsoft;
46pub use model::OAuthAccount;
47pub use provider::{
48    BoxFuture, Credentials, Profile, Provider, Refused, Token, TokenRequest, exchange_code,
49};
50
51const MIGRATIONS: &[Migration] = &[Migration::new(
52    "00010101000800_create_oauth_accounts_table",
53    "",
54    Some(include_str!(
55        "../migrations/00010101000800_create_oauth_accounts_table.down.sql"
56    )),
57)
58.sqlite(
59    include_str!("../migrations/00010101000800_create_oauth_accounts_table.up.sql"),
60    None,
61)
62.postgres(
63    include_str!("../migrations/00010101000800_create_oauth_accounts_table.postgres.up.sql"),
64    None,
65)];
66
67/// The templates, compiled in. An app replaces one with a file of the same
68/// name under its views directory (`resources/views/oauth/section.html`).
69const VIEWS: &[(&str, &str)] = &[
70    (
71        "renox/auth/login_options.html",
72        include_str!("../views/login_options.html"),
73    ),
74    ("oauth/section.html", include_str!("../views/section.html")),
75];
76
77/// The social login module: add it next to `Auth` (with `.account()` for
78/// the page where users link and unlink providers).
79#[derive(Clone, Default)]
80pub struct OAuth {
81    providers: Vec<Arc<dyn Provider>>,
82    domains: Vec<String>,
83}
84
85impl OAuth {
86    /// The module, with no provider yet.
87    pub fn new() -> Self {
88        Self::default()
89    }
90
91    /// Adds Google, with `GOOGLE_CLIENT_ID` and `GOOGLE_CLIENT_SECRET` from
92    /// the configuration (off while they're missing).
93    pub fn google(self) -> Self {
94        self.provider(Google::from_config())
95    }
96
97    /// Adds GitHub, with `GITHUB_CLIENT_ID` and `GITHUB_CLIENT_SECRET` from
98    /// the configuration (off while they're missing).
99    pub fn github(self) -> Self {
100        self.provider(GitHub::from_config())
101    }
102
103    /// Adds Microsoft work and school accounts, with `MICROSOFT_CLIENT_ID`,
104    /// `MICROSOFT_CLIENT_SECRET` and `MICROSOFT_TENANT` from the
105    /// configuration (off while the first two are missing). For a tenant
106    /// given in code, use `.provider(Microsoft::from_config().tenant(..))`.
107    pub fn microsoft(self) -> Self {
108        self.provider(Microsoft::from_config())
109    }
110
111    /// Accepts only accounts whose **verified** email address is at one of
112    /// these domains (`example.com`; the domain itself, not its
113    /// subdomains), whatever the provider. Any other account, and any
114    /// without a verified address, is refused with a message on the login
115    /// page and an [`OAuthRefused`] event. Applies to logging in, linking
116    /// and confirming. Called again, it adds domains.
117    ///
118    /// ```
119    /// use renox_oauth::OAuth;
120    ///
121    /// let _ = OAuth::new().google().github().allow_domains(&["example.com"]);
122    /// ```
123    pub fn allow_domains(mut self, domains: &[&str]) -> Self {
124        for domain in domains {
125            let domain = domain.trim().trim_start_matches('@').to_ascii_lowercase();
126            if !domain.is_empty() && !self.domains.contains(&domain) {
127                self.domains.push(domain);
128            }
129        }
130        self
131    }
132
133    /// Adds a provider: [`Google::new`] with credentials given in code, or
134    /// one of your own ([`Provider`]). One of the same name is replaced.
135    /// Buttons show in the order providers are added.
136    pub fn provider(mut self, provider: impl Provider) -> Self {
137        self.providers.retain(|p| p.name() != provider.name());
138        self.providers.push(Arc::new(provider));
139        self
140    }
141}
142
143impl fmt::Debug for OAuth {
144    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
145        f.debug_list()
146            .entries(self.providers.iter().map(|p| p.name().to_owned()))
147            .finish()
148    }
149}
150
151/// The providers, shared by the routes, the account section and the views.
152#[derive(Clone)]
153pub(crate) struct Providers {
154    list: Arc<Vec<Arc<dyn Provider>>>,
155    domains: Arc<Vec<String>>,
156}
157
158impl Providers {
159    fn new(oauth: &OAuth) -> Self {
160        Self {
161            list: Arc::new(oauth.providers.clone()),
162            domains: Arc::new(oauth.domains.clone()),
163        }
164    }
165
166    /// Whether `email` is at one of the allowed domains (any, when none are set).
167    pub(crate) fn allows(&self, email: Option<&str>) -> bool {
168        self.domains.is_empty()
169            || email
170                .and_then(|email| email.rsplit_once('@'))
171                .is_some_and(|(_, domain)| {
172                    self.domains.iter().any(|d| d.eq_ignore_ascii_case(domain))
173                })
174    }
175
176    /// The allowed domains, for the message.
177    pub(crate) fn domains(&self) -> &[String] {
178        &self.domains
179    }
180
181    /// The provider named `name`, when its credentials are set.
182    pub(crate) fn enabled(&self, state: &AppState, name: &str) -> Option<Arc<dyn Provider>> {
183        self.list
184            .iter()
185            .find(|p| p.name() == name)
186            .filter(|p| p.credentials().resolve(&state.config).is_some())
187            .map(|p| p.with_config(&state.config).unwrap_or_else(|| p.clone()))
188    }
189
190    /// Every provider whose credentials are set, in order.
191    pub(crate) fn all_enabled(&self, state: &AppState) -> Vec<Arc<dyn Provider>> {
192        self.list
193            .iter()
194            .filter(|p| p.credentials().resolve(&state.config).is_some())
195            .cloned()
196            .collect()
197    }
198}
199
200/// A provider as the login pages' buttons see it (`oauth_providers`).
201#[derive(Serialize)]
202struct Button {
203    name: String,
204    label: String,
205    url: String,
206}
207
208/// A provider on the account page (`section.data.providers`).
209#[derive(Serialize)]
210struct Row {
211    name: String,
212    label: String,
213    /// Where linking starts; `None` for a provider no longer offered.
214    link_url: Option<String>,
215    linked: bool,
216    email: Option<String>,
217    since: Option<DateTime>,
218}
219
220/// The account page's section (`section.data`).
221#[derive(Serialize)]
222struct Section {
223    providers: Vec<Row>,
224    has_password: bool,
225    /// Whether unlinking leaves a way to log in.
226    can_unlink: bool,
227    /// "Forgot your password?", where a user without a password sets one.
228    set_password_url: Option<String>,
229}
230
231impl Module for OAuth {
232    fn name(&self) -> &'static str {
233        "oauth"
234    }
235
236    fn migrations(&self) -> &'static [Migration] {
237        MIGRATIONS
238    }
239
240    fn routes(&self) -> Routes {
241        handlers::routes(Providers::new(self))
242    }
243
244    fn register(&self, app: &mut Registry) {
245        let providers = Providers::new(self);
246        // The buttons on the login, register and confirm-password pages.
247        let shared = providers.clone();
248        app.share("oauth_providers", move |ctx: renox::view::ViewContext| {
249            let providers = shared.clone();
250            async move { buttons(&ctx, &providers).await }
251        });
252        let listed = providers.clone();
253        app.account_section("oauth/section.html", 50, move |user, state| {
254            let providers = listed.clone();
255            async move {
256                let section = section(&state, &providers, &user).await?;
257                Ok(renox::serde_json::to_value(section)?)
258            }
259        });
260        app.templates(|env| {
261            for (name, source) in VIEWS {
262                // The app's own file of that name wins.
263                if env.get_template(name).is_err() {
264                    renox::view::add_template(env, *name, *source)
265                        .expect("a built-in template compiles");
266                }
267            }
268        });
269        // Recorded in the activity log when the app has the `Audit` module.
270        app.listen(|e: AccountLinked, state| async move {
271            let entry = renox::audit::Entry::new("oauth.linked")
272                .user(e.user_id)
273                .data(renox::serde_json::json!({ "provider": e.provider }));
274            audit(&state, entry).await
275        })
276        .listen(|e: AccountUnlinked, state| async move {
277            let entry = renox::audit::Entry::new("oauth.unlinked")
278                .user(e.user_id)
279                .data(renox::serde_json::json!({ "provider": e.provider }));
280            audit(&state, entry).await
281        })
282        .listen(|e: OAuthRefused, state| async move {
283            let entry = renox::audit::Entry::new("oauth.refused").data(renox::serde_json::json!({
284                "provider": e.provider,
285                "reason": e.reason,
286                "email": e.email,
287            }));
288            audit(&state, entry).await
289        })
290        .listen(|e: LoggedInWith, state| async move {
291            let entry = renox::audit::Entry::new("oauth.login")
292                .user(e.user_id)
293                .data(renox::serde_json::json!({
294                    "provider": e.provider,
295                    "second_step": e.second_step,
296                }));
297            audit(&state, entry).await
298        });
299    }
300}
301
302/// The providers to offer on this page. On `/confirm-password`, only the
303/// ones the user linked (another one wouldn't prove who they are).
304async fn buttons(ctx: &renox::view::ViewContext, providers: &Providers) -> Result<Vec<Button>> {
305    let state = &ctx.state;
306    let mut enabled = providers.all_enabled(state);
307    if enabled.is_empty() {
308        return Ok(Vec::new());
309    }
310    let confirming = state
311        .url("password.confirm", &[])
312        .is_ok_and(|path| path == ctx.path);
313    let mut confirm = false;
314    if let Some(user) = ctx.user.as_ref().filter(|_| confirming) {
315        let linked = OAuthAccount::of_user(&state.db, user.id).await?;
316        enabled.retain(|p| linked.iter().any(|a| a.provider == p.name()));
317        confirm = true;
318    }
319    enabled
320        .iter()
321        .map(|p| {
322            let mut url = state.url("oauth.redirect", &[&p.name()])?;
323            if confirm {
324                url.push_str("?intent=confirm");
325            }
326            Ok(Button {
327                name: p.name().to_owned(),
328                label: p.label().to_owned(),
329                url,
330            })
331        })
332        .collect()
333}
334
335/// What the account page shows: each provider, linked or not.
336async fn section(state: &AppState, providers: &Providers, user: &User) -> Result<Section> {
337    let linked = OAuthAccount::of_user(&state.db, user.id).await?;
338    let mut rows = Vec::new();
339    for provider in providers.all_enabled(state) {
340        let account = linked.iter().find(|a| a.provider == provider.name());
341        rows.push(Row {
342            name: provider.name().to_owned(),
343            label: provider.label().to_owned(),
344            link_url: Some(state.url("oauth.redirect", &[&provider.name()])?),
345            linked: account.is_some(),
346            email: account.and_then(|a| a.email.clone()),
347            since: account.and_then(|a| a.created_at),
348        });
349    }
350    // Accounts at a provider the app no longer offers can still be unlinked.
351    for account in &linked {
352        if !rows.iter().any(|row| row.name == account.provider) {
353            let label = providers
354                .list
355                .iter()
356                .find(|p| p.name() == account.provider)
357                .map_or_else(|| account.provider.clone(), |p| p.label().to_owned());
358            rows.push(Row {
359                name: account.provider.clone(),
360                label,
361                link_url: None,
362                linked: true,
363                email: account.email.clone(),
364                since: account.created_at,
365            });
366        }
367    }
368    Ok(Section {
369        can_unlink: handlers::can_unlink(user, linked.len()),
370        has_password: user.has_password(),
371        set_password_url: state.url("password.request", &[]).ok(),
372        providers: rows,
373    })
374}
375
376/// Records `entry` when the app has the `Audit` module (its table exists).
377async fn audit(state: &AppState, entry: renox::audit::Entry) -> Result {
378    let has_log = renox::db::sql("SELECT COUNT(*) FROM audit_logs WHERE 1 = 0")
379        .scalar::<i64>(&state.db)
380        .await
381        .is_ok();
382    if has_log {
383        renox::audit::record(&state.db, entry).await?;
384    }
385    Ok(())
386}
387
388/// Compiles the Rust in docs/oauth.md (the guide) as doctests.
389#[cfg(doctest)]
390#[doc = include_str!("../../../docs/oauth.md")]
391pub struct Guide;