laravel-rust 0.1.0

Laravel for Rust: a full-stack Rust web framework, inspired by PHP Laravel
Documentation
use serde::Deserialize;
use serde_json::Value;

use super::drivers::{email, string};
use super::{CLIENT, Driver, Email, Error, Profile, Tokens};
use crate::config::Config;
use crate::http::client::PendingRequest;

/// The tenant of personal Microsoft accounts, whose email addresses Microsoft verifies.
const MICROSOFT_CONSUMERS: &str = "9188040d-6c67-4c5b-b112-36a304b66dad";

/// Google accounts, through OpenID Connect.
pub(super) struct Google;

impl Driver for Google {
    fn authorize_url(&self) -> String {
        "https://accounts.google.com/o/oauth2/v2/auth".to_owned()
    }

    fn token_url(&self) -> String {
        "https://oauth2.googleapis.com/token".to_owned()
    }

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

    async fn user(&self, tokens: &Tokens<'_>) -> Result<Profile, Error> {
        let claims = tokens.id_token()?;
        let issuer = string(&claims, "iss");
        if !matches!(
            issuer.as_deref(),
            Some("https://accounts.google.com" | "accounts.google.com")
        ) {
            return Err(tokens.untrusted("iss", issuer.as_deref()));
        }

        Ok(Profile {
            id: required(tokens, &claims, "sub")?,
            name: string(&claims, "name"),
            nickname: None,
            email: email(&claims),
            avatar: string(&claims, "picture"),
            raw: claims,
        })
    }
}

/// Microsoft work, school, and personal accounts, through OpenID Connect.
pub(super) struct Microsoft {
    tenant: String,
}

impl Microsoft {
    pub(super) fn new(config: &Config) -> Self {
        Self {
            tenant: config.social.microsoft_tenant.clone(),
        }
    }
}

impl Driver for Microsoft {
    fn authorize_url(&self) -> String {
        format!(
            "https://login.microsoftonline.com/{}/oauth2/v2.0/authorize",
            self.tenant
        )
    }

    fn token_url(&self) -> String {
        format!("https://login.microsoftonline.com/{}/oauth2/v2.0/token", self.tenant)
    }

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

    async fn user(&self, tokens: &Tokens<'_>) -> Result<Profile, Error> {
        let claims = tokens.id_token()?;
        let tenant = required(tokens, &claims, "tid")?;
        let issuer = string(&claims, "iss");
        if issuer.as_deref() != Some(&format!("https://login.microsoftonline.com/{tenant}/v2.0")) {
            return Err(tokens.untrusted("iss", issuer.as_deref()));
        }

        let verified = tenant == MICROSOFT_CONSUMERS
            || match claims.get("xms_edov") {
                Some(Value::Bool(verified)) => *verified,
                Some(Value::String(verified)) => verified == "1" || verified == "true",
                _ => false,
            };

        Ok(Profile {
            id: required(tokens, &claims, "oid")?,
            name: string(&claims, "name"),
            nickname: None,
            email: string(&claims, "email").map(|address| Email { address, verified }),
            avatar: None,
            raw: claims,
        })
    }
}

/// GitHub accounts, through OAuth, on github.com or a GitHub Enterprise Server.
pub(super) struct GitHub {
    /// The server's web address, such as `https://github.com`.
    web: String,
    /// The server's API address: `https://api.github.com`, or `/api/v3` on an Enterprise Server.
    api: String,
    user_agent: String,
}

impl GitHub {
    pub(super) fn new(config: &Config) -> Self {
        let web = config.social.github_url.trim_end_matches('/').to_owned();
        let api = if web == "https://github.com" {
            "https://api.github.com".to_owned()
        } else {
            format!("{web}/api/v3")
        };
        let user_agent = if config.app.name.is_empty() {
            "Laravel for Rust".to_owned()
        } else {
            config.app.name.clone()
        };

        Self { web, api, user_agent }
    }

    fn get(&self, tokens: &Tokens<'_>, path: &str) -> PendingRequest {
        CLIENT
            .get(format!("{}{path}", self.api))
            .token(tokens.access_token())
            .accept("application/vnd.github+json")
            .user_agent(&self.user_agent)
            .ensure_successful()
    }
}

impl Driver for GitHub {
    fn authorize_url(&self) -> String {
        format!("{}/login/oauth/authorize", self.web)
    }

    fn token_url(&self) -> String {
        format!("{}/login/oauth/access_token", self.web)
    }

    fn scopes(&self) -> &[&str] {
        &["read:user", "user:email"]
    }

    async fn user(&self, tokens: &Tokens<'_>) -> Result<Profile, Error> {
        let profile: Value = self
            .get(tokens, "/user")
            .send()
            .await
            .and_then(|profile| profile.json())
            .map_err(|error| Error::Provider(format!("couldn't fetch the GitHub profile: {error}")))?;
        let id = match profile.get("id") {
            Some(Value::Number(id)) => id.to_string(),
            Some(Value::String(id)) => id.clone(),
            _ => return Err(Error::Provider("GitHub's profile has no `id`".to_owned())),
        };

        #[derive(Deserialize)]
        struct GitHubEmail {
            email: String,
            primary: bool,
            verified: bool,
        }
        let emails: Option<Vec<GitHubEmail>> = match self.get(tokens, "/user/emails").send().await {
            Ok(emails) => emails.json().ok(),
            Err(_) => None,
        };
        let email = emails
            .and_then(|emails| emails.into_iter().find(|email| email.primary))
            .map(|email| Email {
                address: email.email,
                verified: email.verified,
            })
            .or_else(|| {
                string(&profile, "email").map(|address| Email {
                    address,
                    verified: false,
                })
            });

        Ok(Profile {
            id,
            name: string(&profile, "name"),
            nickname: string(&profile, "login"),
            email,
            avatar: string(&profile, "avatar_url"),
            raw: profile,
        })
    }
}

fn required(tokens: &Tokens<'_>, claims: &Value, name: &str) -> Result<String, Error> {
    string(claims, name).ok_or_else(|| Error::Provider(format!("{}'s ID token has no `{name}`", tokens.label)))
}