renox-oauth 1.2.0

Social login (Sign in with Google, GitHub, …) linked to the users of a Renox app.
Documentation
//! Sign in with Google (OpenID Connect): the `openid email profile` scopes,
//! the profile from Google's userinfo endpoint. [`Google::hosted_domain`]
//! limits sign-in to one Google Workspace domain.

use renox::http::Http;
use renox::prelude::*;
use serde::Deserialize;

use crate::provider::{Refused, get_json};
use crate::{BoxFuture, Credentials, Profile, Provider, Token};

/// Google's userinfo endpoint (OpenID Connect).
pub const USERINFO: &str = "https://openidconnect.googleapis.com/v1/userinfo";

/// Google. Make the client in Google Cloud's console (APIs & Services →
/// Credentials → OAuth client ID, a web application) with the redirect URI
/// `APP_URL/auth/google/callback`.
#[derive(Debug, Clone)]
pub struct Google {
    credentials: Credentials,
    hosted_domain: Option<String>,
}

impl Google {
    /// With `GOOGLE_CLIENT_ID` and `GOOGLE_CLIENT_SECRET` from the configuration.
    pub fn from_config() -> Self {
        Self {
            credentials: Credentials::from_config("GOOGLE"),
            hosted_domain: None,
        }
    }

    /// With these credentials.
    pub fn new(client_id: impl Into<String>, client_secret: impl Into<String>) -> Self {
        Self {
            credentials: Credentials::new(client_id, client_secret),
            hosted_domain: None,
        }
    }

    /// Only accounts of this Google Workspace domain (`example.com`) sign in.
    /// The `hd` parameter is sent so Google offers only that domain's
    /// accounts, but it is just a hint (anyone can edit the URL): the
    /// callback checks the `hd` claim of the userinfo answer, and an account
    /// without one (a gmail.com account) is refused.
    ///
    /// ```
    /// use renox_oauth::{Google, OAuth};
    ///
    /// let _ = OAuth::new().provider(Google::from_config().hosted_domain("example.com"));
    /// ```
    pub fn hosted_domain(mut self, domain: impl Into<String>) -> Self {
        let domain: String = domain.into();
        self.hosted_domain = Some(domain.trim().trim_start_matches('@').to_ascii_lowercase());
        self
    }
}

#[derive(Deserialize)]
struct UserInfo {
    sub: String,
    email: Option<String>,
    #[serde(default)]
    email_verified: bool,
    name: Option<String>,
    picture: Option<String>,
    /// The Workspace domain, for accounts of one.
    hd: Option<String>,
}

impl Provider for Google {
    fn name(&self) -> &str {
        "google"
    }

    fn label(&self) -> &str {
        "Google"
    }

    fn credentials(&self) -> &Credentials {
        &self.credentials
    }

    fn authorize_endpoint(&self) -> &str {
        "https://accounts.google.com/o/oauth2/v2/auth"
    }

    fn token_endpoint(&self) -> &str {
        "https://oauth2.googleapis.com/token"
    }

    fn scopes(&self) -> &[&str] {
        &["openid", "email", "profile"]
    }

    fn authorize_params(&self) -> Vec<(&str, &str)> {
        // Lets people with several Google accounts pick one.
        let mut params = vec![("prompt", "select_account")];
        if let Some(domain) = &self.hosted_domain {
            params.push(("hd", domain.as_str()));
        }
        params
    }

    fn profile<'a>(&'a self, http: &'a Http, token: &'a Token) -> BoxFuture<'a, Result<Profile>> {
        Box::pin(async move {
            let info: UserInfo = get_json(http, USERINFO, token, "application/json").await?;
            if let Some(domain) = &self.hosted_domain {
                // `hd` in the URL is only a hint: this is the check.
                let hd = info.hd.as_deref().unwrap_or_default();
                if !hd.eq_ignore_ascii_case(domain) {
                    return Err(Refused::new(
                        "hosted_domain",
                        format!("Only Google accounts of {domain} can sign in here."),
                    )
                    .into());
                }
            }
            let mut profile = Profile::new(info.sub);
            if let Some(email) = info.email {
                profile = profile.email(email, info.email_verified);
            }
            Ok(profile.name(info.name).avatar(info.picture))
        })
    }
}