use renox::http::Http;
use renox::prelude::*;
use serde::Deserialize;
use crate::provider::{Refused, get_json};
use crate::{BoxFuture, Credentials, Profile, Provider, Token};
pub const USERINFO: &str = "https://openidconnect.googleapis.com/v1/userinfo";
#[derive(Debug, Clone)]
pub struct Google {
credentials: Credentials,
hosted_domain: Option<String>,
}
impl Google {
pub fn from_config() -> Self {
Self {
credentials: Credentials::from_config("GOOGLE"),
hosted_domain: None,
}
}
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,
}
}
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>,
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)> {
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 {
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))
})
}
}