Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(auth): set user name from identity provider on signup (#5240)
Evan Hutnik9fc98808044d
diff --git a/crates/model/src/authentication/webhooks/mod.rs b/crates/model/src/authentication/webhooks/mod.rsindex 9a94d03c4e..90ac0cd8ca 100644--- a/crates/model/src/authentication/webhooks/mod.rs+++ b/crates/model/src/authentication/webhooks/mod.rs@@ -38,4 +38,10 @@ pub struct User {pub username: Option<String>,/// If the user's email is verifiedpub verified: bool,+ /// Given name, set by the identity provider reconcile lambda on SSO signup+ pub first_name: Option<String>,+ /// Family name, set by the identity provider reconcile lambda on SSO signup+ pub last_name: Option<String>,+ /// Display name, set by the identity provider reconcile lambda on SSO signup+ pub full_name: Option<String>,}diff --git a/infra/stacks/fusionauth-instance/templates/reconcile_secondary_idp_link.js b/infra/stacks/fusionauth-instance/templates/reconcile_secondary_idp_link.jsindex f1d86424b1..5e1b2c3d40 100644--- a/infra/stacks/fusionauth-instance/templates/reconcile_secondary_idp_link.js+++ b/infra/stacks/fusionauth-instance/templates/reconcile_secondary_idp_link.js@@ -6,6 +6,11 @@// Fails closed: missing jwt.email or user.email is treated the same as a// mismatch. Google always returns email when the openid+email scopes are// granted, so legitimate primary sign-ins always satisfy the check.+//+// Also maps Google's profile claims onto the user. Assigning a reconcile lambda+// replaces FusionAuth's default one, so without this the user is created with no+// name and the user.create webhook has nothing to seed the macro profile with.+// biome-ignore lint/correctness/noUnusedVariables: FusionAuth invokes this by name.function reconcile(user, registration, jwt, id_token, tokens) {var jwtEmail =jwt && typeof jwt.email === 'string' ? jwt.email.toLowerCase() : null;@@ -17,4 +22,25 @@ function reconcile(user, registration, jwt, id_token, tokens) {'This Google account is linked as a secondary inbox to another Macro account. Sign in with your primary email or contact support.');}++ // Claims live on the userinfo response; fall back to the id_token.+ function claim(name) {+ var value = jwt && jwt[name];+ if (typeof value !== 'string' || !value.trim()) {+ value = id_token && id_token[name];+ }+ return typeof value === 'string' && value.trim() ? value.trim() : null;+ }++ // Only fill what's missing — this runs on every login, and the user may have+ // since changed their name in Macro.+ if (!user.firstName) {+ user.firstName = claim('given_name');+ }+ if (!user.lastName) {+ user.lastName = claim('family_name');+ }+ if (!user.fullName) {+ user.fullName = claim('name');+ }}diff --git a/services/authentication_service/src/api/webhooks/user/create_user_webhook.rs b/services/authentication_service/src/api/webhooks/user/create_user_webhook.rsindex dcfc4e117b..562f6a86db 100644--- a/services/authentication_service/src/api/webhooks/user/create_user_webhook.rs+++ b/services/authentication_service/src/api/webhooks/user/create_user_webhook.rs@@ -27,7 +27,7 @@ use macro_user_id::{email::{Email, ReadEmailParts},user_id::MacroUserIdStr,};-use model::authentication::webhooks::FusionAuthUserWebhook;+use model::authentication::webhooks::{FusionAuthUserWebhook, User as FusionAuthWebhookUser};use model_entity::EntityType;use std::collections::HashSet;use teams::domain::team_repo::TeamService;@@ -38,6 +38,39 @@ const MACRO_SUPPORT_EMAILS: [&str; 3] = ["[email protected]", "[email protected]", "fn support_channel_name<T: AsRef<str>>(email: &Email<T>) -> String {format!("Macro Support x {}", email.local_part())}++/// Name the identity provider gave us, as (first, last).+///+/// Google SSO fills firstName/lastName via the IdP reconcile lambda; fall back to+/// splitting fullName at the first space for providers that only send a display+/// name. Passwordless signups have none of these and yield (None, None).+fn identity_provider_name(user: &FusionAuthWebhookUser) -> (Option<String>, Option<String>) {+ fn trimmed(value: &Option<String>) -> Option<String> {+ value+ .as_deref()+ .map(str::trim)+ .filter(|value| !value.is_empty())+ .map(str::to_string)+ }++ let first_name = trimmed(&user.first_name);+ let last_name = trimmed(&user.last_name);+ if first_name.is_some() || last_name.is_some() {+ return (first_name, last_name);+ }++ match trimmed(&user.full_name) {+ Some(full_name) => match full_name.split_once(' ') {+ Some((first, last)) => (+ Some(first.to_string()),+ Some(last.trim().to_string()).filter(|last| !last.is_empty()),+ ),+ None => (Some(full_name), None),+ },+ None => (None, None),+ }+}+/// FusionAuth create user webhook#[tracing::instrument(skip(ctx, req, _internal_authorization), fields(email=%req.event.user.email, fusionauth_user_id=%req.event.user.id, username=?req.event.user.username, event_type=%req.event.event_type, ip_address=%req.event.info.ip_address))]pub async fn handler(@@ -116,6 +149,7 @@ async fn create_user_webhook_complete(async fn create_user_webhook(ctx: &ApiContext, req: FusionAuthUserWebhook) -> anyhow::Result<()> {let ip_address = req.event.info.ip_address;let email = req.event.user.email.to_lowercase();+ let (first_name, last_name) = identity_provider_name(&req.event.user);let username = req.event.user.username.unwrap_or(email.clone());let fusionauth_user_id = req.event.user.id;@@ -185,12 +219,30 @@ async fn create_user_webhook(ctx: &ApiContext, req: FusionAuthUserWebhook) -> an// ("macro|{email}") the app identifies with. Fire-and-forget.tokio::spawn({let analytics_client = ctx.analytics_client.clone();+ let db = ctx.db.clone();+ let fusionauth_user_id = fusionauth_user_id.clone();let user_id = user_id.clone();let email = email.clone();let ip_address = ip_address.clone();let verified = req.event.user.verified;let has_organization = organization_id.is_some();async move {+ // Seed the profile with the name the identity provider gave us (Google+ // SSO). Keyed on the FusionAuth id, which is macro_user.id — `user_id`+ // here is the "macro|{email}" User profile id.+ if first_name.is_some() || last_name.is_some() {+ let _ = macro_db_client::user::update_user_name::update_user_name(+ &db,+ &fusionauth_user_id,+ first_name,+ last_name,+ )+ .await+ .inspect_err(+ |e| tracing::error!(error=?e, "unable to set user name from identity provider"),+ );+ }+let _ = analytics_client.track_posthog(&user_id,diff --git a/services/authentication_service/src/api/webhooks/user/create_user_webhook/test.rs b/services/authentication_service/src/api/webhooks/user/create_user_webhook/test.rsindex d833ee8870..6c3413f738 100644--- a/services/authentication_service/src/api/webhooks/user/create_user_webhook/test.rs+++ b/services/authentication_service/src/api/webhooks/user/create_user_webhook/test.rs@@ -1,6 +1,7 @@use macro_user_id::email::Email;+use model::authentication::webhooks::User as FusionAuthWebhookUser;-use super::support_channel_name;+use super::{identity_provider_name, support_channel_name};#[test]fn support_channel_name_uses_email_local_part() {@@ -11,3 +12,73 @@ fn support_channel_name_uses_email_local_part() {"Macro Support x new.user+trial");}++fn webhook_user(+ first_name: Option<&str>,+ last_name: Option<&str>,+ full_name: Option<&str>,+) -> FusionAuthWebhookUser {+ FusionAuthWebhookUser {+ id: "0f1e2d3c-4b5a-6978-8796-a5b4c3d2e1f0".to_string(),+ email: "[email protected]".to_string(),+ username: None,+ verified: true,+ first_name: first_name.map(str::to_string),+ last_name: last_name.map(str::to_string),+ full_name: full_name.map(str::to_string),+ }+}++#[test]+fn identity_provider_name_prefers_first_and_last_name() {+ let user = webhook_user(Some("Evan"), Some("Hutnik"), Some("Someone Else"));++ assert_eq!(+ identity_provider_name(&user),+ (Some("Evan".to_string()), Some("Hutnik".to_string()))+ );+}++#[test]+fn identity_provider_name_splits_full_name_at_first_space() {+ let user = webhook_user(None, None, Some("Ada Byron Lovelace"));++ assert_eq!(+ identity_provider_name(&user),+ (Some("Ada".to_string()), Some("Byron Lovelace".to_string()))+ );+}++#[test]+fn identity_provider_name_handles_single_word_full_name() {+ let user = webhook_user(None, None, Some("Prince"));++ assert_eq!(+ identity_provider_name(&user),+ (Some("Prince".to_string()), None)+ );+}++#[test]+fn identity_provider_name_ignores_blank_values() {+ let user = webhook_user(Some(" "), Some(""), Some(" "));++ assert_eq!(identity_provider_name(&user), (None, None));+}++#[test]+fn identity_provider_name_is_empty_for_passwordless_signup() {+ let user = webhook_user(None, None, None);++ assert_eq!(identity_provider_name(&user), (None, None));+}++#[test]+fn identity_provider_name_keeps_partial_name() {+ let user = webhook_user(Some("Evan"), None, None);++ assert_eq!(+ identity_provider_name(&user),+ (Some("Evan".to_string()), None)+ );+}