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): add in ability to generate gmail account link (#3490)
Will Hutchinson578bd468657a
diff --git a/js/app/packages/service-clients/service-auth/generated/client.ts b/js/app/packages/service-clients/service-auth/generated/client.tsindex e586878630..ab6c1873f7 100644--- a/js/app/packages/service-clients/service-auth/generated/client.ts+++ b/js/app/packages/service-clients/service-auth/generated/client.ts@@ -24,6 +24,8 @@ import type {GetUserLinkExistsParams,InitGithubLinkParams,InitGithubLinkResponse,+ InitGmailLinkParams,+ InitGmailLinkResponse,InviteToTeamRequest,MacroApiTokenParams,MacroApiTokenResponse,@@ -646,6 +648,85 @@ export const deleteGithubLink = async (} as deleteGithubLinkResponse;};+/**+ * @summary Initiates a Gmail link for a user+ */+export type initGmailLinkResponse200 = {+ data: InitGmailLinkResponse;+ status: 200;+};++export type initGmailLinkResponse400 = {+ data: ErrorResponse;+ status: 400;+};++export type initGmailLinkResponse401 = {+ data: ErrorResponse;+ status: 401;+};++export type initGmailLinkResponse429 = {+ data: ErrorResponse;+ status: 429;+};++export type initGmailLinkResponse500 = {+ data: ErrorResponse;+ status: 500;+};++export type initGmailLinkResponseSuccess = initGmailLinkResponse200 & {+ headers: Headers;+};+export type initGmailLinkResponseError = (+ | initGmailLinkResponse400+ | initGmailLinkResponse401+ | initGmailLinkResponse429+ | initGmailLinkResponse500+) & {+ headers: Headers;+};++export type initGmailLinkResponse =+ | initGmailLinkResponseSuccess+ | initGmailLinkResponseError;++export const getInitGmailLinkUrl = (params: InitGmailLinkParams) => {+ const normalizedParams = new URLSearchParams();++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : value.toString());+ }+ });++ const stringifiedParams = normalizedParams.toString();++ return stringifiedParams.length > 0+ ? `/link/gmail?${stringifiedParams}`+ : `/link/gmail`;+};++export const initGmailLink = async (+ params: InitGmailLinkParams,+ options?: RequestInit+): Promise<initGmailLinkResponse> => {+ const res = await fetch(getInitGmailLinkUrl(params), {+ ...options,+ method: 'POST',+ });++ const body = [204, 205, 304].includes(res.status) ? null : await res.text();++ const data: initGmailLinkResponse['data'] = body ? JSON.parse(body) : {};+ return {+ data,+ status: res.status,+ headers: res.headers,+ } as initGmailLinkResponse;+};+/*** @summary Completes the apple login flow*/diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/index.ts b/js/app/packages/service-clients/service-auth/generated/schemas/index.tsindex 4d1c342bcc..ec5cac7b20 100644--- a/js/app/packages/service-clients/service-auth/generated/schemas/index.ts+++ b/js/app/packages/service-clients/service-auth/generated/schemas/index.ts@@ -34,6 +34,8 @@ export * from './getUserInfoOrganizationId';export * from './getUserLinkExistsParams';export * from './initGithubLinkParams';export * from './initGithubLinkResponse';+export * from './initGmailLinkParams';+export * from './initGmailLinkResponse';export * from './inviteEntry';export * from './inviteToTeamRequest';export * from './macroApiTokenParams';diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/initGmailLinkParams.ts b/js/app/packages/service-clients/service-auth/generated/schemas/initGmailLinkParams.tsnew file mode 100644index 0000000000..f2276675fd--- /dev/null+++ b/js/app/packages/service-clients/service-auth/generated/schemas/initGmailLinkParams.ts@@ -0,0 +1,13 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * authentication_service+ * OpenAPI spec version: 0.1.0+ */++export type InitGmailLinkParams = {+ /**+ * **OPTIONAL**. The original url to redirect to.+ */+ original_url: string;+};diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/initGmailLinkResponse.ts b/js/app/packages/service-clients/service-auth/generated/schemas/initGmailLinkResponse.tsnew file mode 100644index 0000000000..a21f7c9e69--- /dev/null+++ b/js/app/packages/service-clients/service-auth/generated/schemas/initGmailLinkResponse.ts@@ -0,0 +1,13 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * authentication_service+ * OpenAPI spec version: 0.1.0+ */++export interface InitGmailLinkResponse {+ /** The OAuth authorization URL to redirect the user to */+ authorization_url: string;+ /** The link ID for tracking the OAuth flow */+ link_id: string;+}diff --git a/js/app/packages/service-clients/service-auth/openapi.json b/js/app/packages/service-clients/service-auth/openapi.jsonindex fae4733dc2..1deda772d0 100644--- a/js/app/packages/service-clients/service-auth/openapi.json+++ b/js/app/packages/service-clients/service-auth/openapi.json@@ -482,6 +482,76 @@}}},+ "/link/gmail": {+ "post": {+ "tags": ["link::gmail"],+ "summary": "Initiates a Gmail link for a user",+ "operationId": "init_gmail_link",+ "parameters": [+ {+ "name": "original_url",+ "in": "query",+ "description": "**OPTIONAL**. The original url to redirect to.",+ "required": true,+ "schema": {+ "type": "string"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/InitGmailLinkResponse"+ }+ }+ }+ },+ "400": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "401": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "429": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },"/login/apple": {"post": {"tags": ["login::apple"],@@ -3408,6 +3478,21 @@}}},+ "InitGmailLinkResponse": {+ "type": "object",+ "required": ["authorization_url", "link_id"],+ "properties": {+ "authorization_url": {+ "type": "string",+ "description": "The OAuth authorization URL to redirect the user to"+ },+ "link_id": {+ "type": "string",+ "format": "uuid",+ "description": "The link ID for tracking the OAuth flow"+ }+ }+ },"InviteEntry": {"type": "object","description": "A single invite entry with email and tier",diff --git a/rust/cloud-storage/authentication_service/src/api/link/gmail.rs b/rust/cloud-storage/authentication_service/src/api/link/gmail.rsnew file mode 100644index 0000000000..be75b73ddc--- /dev/null+++ b/rust/cloud-storage/authentication_service/src/api/link/gmail.rs@@ -0,0 +1,143 @@+use anyhow::Context;+use axum::{+ Json,+ extract::{Query, State},+ http::StatusCode,+ response::{IntoResponse, Response},+};+use macro_middleware::tracking::ClientIp;+use model::response::ErrorResponse;+use model_user::axum_extractor::MacroUserExtractor;+use serde_utils::urlencode::UrlEncoded;+use url::Url;++use crate::api::{context::ApiContext, oauth2::OAuthState};++const GOOGLE_AUTHORIZATION_URL: &str = "https://accounts.google.com/o/oauth2/v2/auth";+const GMAIL_IDENTITY_PROVIDER_NAME: &str = "google_gmail";+const GMAIL_SCOPES: &str = "openid profile email https://www.googleapis.com/auth/gmail.modify https://www.googleapis.com/auth/contacts.readonly https://www.googleapis.com/auth/contacts.other.readonly https://www.googleapis.com/auth/gmail.settings.basic";++#[derive(serde::Deserialize, serde::Serialize, Debug, utoipa::ToSchema)]+pub struct InitGmailLinkResponse {+ /// The OAuth authorization URL to redirect the user to+ pub authorization_url: String,+ /// The link ID for tracking the OAuth flow+ pub link_id: uuid::Uuid,+}++/// Error type for init Gmail operations+#[derive(thiserror::Error, Debug)]+pub enum InitGmailLinkError {+ /// Too many in-progress links+ #[error("too many in progress links")]+ TooManyInProgressLinks,+ /// Internal error+ #[error("internal error occurred")]+ InternalError(#[from] anyhow::Error),+ /// The identity provider was not found+ #[error("identity provider not found")]+ IdentityProviderNotFound,+}++impl IntoResponse for InitGmailLinkError {+ fn into_response(self) -> Response {+ let message = self.to_string();+ let status_code: StatusCode = match &self {+ InitGmailLinkError::TooManyInProgressLinks => StatusCode::TOO_MANY_REQUESTS,+ InitGmailLinkError::InternalError(_) | InitGmailLinkError::IdentityProviderNotFound => {+ StatusCode::INTERNAL_SERVER_ERROR+ }+ };++ (+ status_code,+ Json(ErrorResponse {+ message: message.into(),+ }),+ )+ .into_response()+ }+}++#[derive(Debug, serde::Deserialize)]+pub(crate) struct InitGmailLinkQueryParams {+ /// Once the frontend is update to NOT 2x urlencode this then this should be changed to+ /// `Option<Url>`+ original_url: Option<UrlEncoded<Url>>,+}++/// Initiates a Gmail link for a user+#[utoipa::path(+ post,+ operation_id = "init_gmail_link",+ path = "/link/gmail",+ params(+ ("original_url" = String, Query, description = "**OPTIONAL**. The original url to redirect to.")+ ),+ responses(+ (status = 200, body=InitGmailLinkResponse),+ (status = 400, body=ErrorResponse),+ (status = 429, body=ErrorResponse),+ (status = 401, body=ErrorResponse),+ (status = 500, body=ErrorResponse),+ )+ )]+#[tracing::instrument(skip(ctx, ip_context, user_context), fields(client_ip=%ip_context, user_id=%user_context.user_context.user_id, fusion_user_id=%user_context.user_context.fusion_user_id), err)]+pub async fn init_gmail_link_handler(+ State(ctx): State<ApiContext>,+ query: Query<InitGmailLinkQueryParams>,+ ip_context: ClientIp,+ user_context: MacroUserExtractor,+) -> Result<Json<InitGmailLinkResponse>, InitGmailLinkError> {+ let Query(InitGmailLinkQueryParams { original_url }) = query;++ let count =+ macro_db_client::in_progress_user_link::count_existing_in_progress_user_links_for_user(+ &ctx.db,+ &user_context.user_context.fusion_user_id,+ )+ .await?;++ if count >= 5 {+ return Err(InitGmailLinkError::TooManyInProgressLinks);+ }++ let link_id = macro_db_client::in_progress_user_link::create_in_progress_user_link(+ &ctx.db,+ &user_context.user_context.fusion_user_id,+ )+ .await?;++ let gmail_idp_id = ctx+ .auth_client+ .get_identity_provider_id_by_name(GMAIL_IDENTITY_PROVIDER_NAME)+ .await+ .map_err(|_| InitGmailLinkError::IdentityProviderNotFound)?;++ let state = OAuthState {+ identity_provider_id: gmail_idp_id,+ link_id: Some(link_id),+ original_url: original_url.map(|x| x.0.to_string()),+ is_mobile: None,+ };++ let redirect_uri = crate::api::oauth2::format_redirect_uri("google");+ let state_str = serde_json::to_string(&state).context("failed to serialize OAuth state")?;++ let mut authorization_url =+ Url::parse(GOOGLE_AUTHORIZATION_URL).context("invalid Google authorization URL")?;+ authorization_url+ .query_pairs_mut()+ .append_pair("client_id", ctx.auth_client.google_client_id())+ .append_pair("redirect_uri", &redirect_uri)+ .append_pair("response_type", "code")+ .append_pair("scope", GMAIL_SCOPES)+ .append_pair("state", &state_str)+ .append_pair("access_type", "offline")+ .append_pair("prompt", "consent");++ Ok(Json(InitGmailLinkResponse {+ authorization_url: authorization_url.to_string(),+ link_id,+ }))+}diff --git a/rust/cloud-storage/authentication_service/src/api/link/mod.rs b/rust/cloud-storage/authentication_service/src/api/link/mod.rsindex a267d38b55..a04f9831af 100644--- a/rust/cloud-storage/authentication_service/src/api/link/mod.rs+++ b/rust/cloud-storage/authentication_service/src/api/link/mod.rs@@ -5,6 +5,7 @@ use axum::{};pub(in crate::api) mod create_in_progress_link;pub(in crate::api) mod github;+pub(in crate::api) mod gmail;/// The link router/// We ensure the user is logged in with the `macro_middleware::auth::decode_jwt::handler`.@@ -13,4 +14,5 @@ pub fn router(_state: ApiContext) -> Router<ApiContext> {.route("/", post(create_in_progress_link::handler)).route("/github", post(github::init_github_link_handler)).route("/github", delete(github::delete_github_link_handler))+ .route("/gmail", post(gmail::init_gmail_link_handler))}diff --git a/rust/cloud-storage/authentication_service/src/api/swagger.rs b/rust/cloud-storage/authentication_service/src/api/swagger.rsindex c72c76897b..e9e9ea1400 100644--- a/rust/cloud-storage/authentication_service/src/api/swagger.rs+++ b/rust/cloud-storage/authentication_service/src/api/swagger.rs@@ -16,6 +16,7 @@ use crate::api::email::resend_fusionauth_verify_user_email::ResendFusionauthVeriuse crate::api::jwt::macro_api_token::MacroApiTokenResponse;use crate::api::link::create_in_progress_link::CreateInProgressLinkResponse;use crate::api::link::github::InitGithubLinkResponse;+use crate::api::link::gmail::InitGmailLinkResponse;use crate::api::merge::create_merge_request::CreateAccountMergeRequest;use crate::api::user::create_user::CreateUserRequest;use crate::api::user::get_legacy_user_permissions::GetLegacyUserPermissionsResponse;@@ -71,6 +72,7 @@ use model::user::{link::create_in_progress_link::handler,link::github::init_github_link_handler,link::github::delete_github_link_handler,+ link::gmail::init_gmail_link_handler,/// /oauthoauth::oauth_redirect::handler,@@ -165,6 +167,7 @@ use model::user::{GenerateEmailLinkRequest,CreateInProgressLinkResponse,InitGithubLinkResponse,+ InitGmailLinkResponse,UserQuota,UserOrganizationResponse,GetLegacyUserPermissionsResponse,diff --git a/rust/cloud-storage/fusionauth/src/lib.rs b/rust/cloud-storage/fusionauth/src/lib.rsindex d433558be4..5d48fc303d 100644--- a/rust/cloud-storage/fusionauth/src/lib.rs+++ b/rust/cloud-storage/fusionauth/src/lib.rs@@ -138,6 +138,11 @@ impl FusionAuthClient {}}+ /// Returns the Google OAuth client ID.+ pub fn google_client_id(&self) -> &str {+ &self.google_client_id+ }+/// Constructs the oauth2 authorize url for the given idp/// If login_hint is provided, it will be used as the login_hint parameter. This is used to/// ensure users are correctly redirected for domain specific SSO