mirror of
https://github.com/Sea-Haven-Industries/google-user-sync.git
synced 2026-05-18 20:20:17 +00:00
Initial commit — Google Workspace to Front user sync
This commit is contained in:
parent
7547b37475
commit
299e6449b1
10 changed files with 557 additions and 0 deletions
11
.github/workflows/ci.yaml
vendored
Normal file
11
.github/workflows/ci.yaml
vendored
Normal file
|
|
@ -0,0 +1,11 @@
|
||||||
|
name: CI
|
||||||
|
on:
|
||||||
|
pull_request:
|
||||||
|
branches: [main]
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
ci:
|
||||||
|
uses: Sea-Haven-Industries/.github/.github/workflows/ci-typescript-cdk.yaml@main
|
||||||
|
with:
|
||||||
|
run-typecheck: false
|
||||||
|
run-cdk-synth: true
|
||||||
20
.github/workflows/deploy.yaml
vendored
Normal file
20
.github/workflows/deploy.yaml
vendored
Normal file
|
|
@ -0,0 +1,20 @@
|
||||||
|
name: Deploy
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [main]
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
id-token: write
|
||||||
|
contents: read
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: deploy
|
||||||
|
cancel-in-progress: false
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
deploy:
|
||||||
|
uses: Sea-Haven-Industries/.github/.github/workflows/cd-cdk.yaml@main
|
||||||
|
with:
|
||||||
|
cdk-dir: cdk
|
||||||
|
secrets:
|
||||||
|
deploy-role-arn: ${{ secrets.AWS_DEPLOY_ROLE_ARN }}
|
||||||
6
.gitignore
vendored
Normal file
6
.gitignore
vendored
Normal file
|
|
@ -0,0 +1,6 @@
|
||||||
|
node_modules/
|
||||||
|
cdk.out/
|
||||||
|
.env
|
||||||
|
__pycache__/
|
||||||
|
.aws-sam/
|
||||||
|
PLAN.md
|
||||||
94
README.md
Normal file
94
README.md
Normal file
|
|
@ -0,0 +1,94 @@
|
||||||
|
# google-user-sync
|
||||||
|
|
||||||
|
A scheduled Lambda that pulls user profile data (job title, phone) from Google Workspace Admin Directory API and syncs it to Front teammate custom fields via the Front Core API. Runs weekdays at 6:00 AM ET via EventBridge.
|
||||||
|
|
||||||
|
## Architecture
|
||||||
|
|
||||||
|
```
|
||||||
|
EventBridge (weekday cron, 6:00 AM ET)
|
||||||
|
|
|
||||||
|
v
|
||||||
|
Lambda (Node.js 22, arm64)
|
||||||
|
|
|
||||||
|
+-- Secrets Manager --> google-user-sync/google-service-account
|
||||||
|
+-- Secrets Manager --> google-user-sync/front-api-token
|
||||||
|
|
|
||||||
|
+-- GET Google Admin Directory API --> list users in target OUs
|
||||||
|
+-- PATCH Front API /teammates/alt:email:{email} --> update custom_fields
|
||||||
|
```
|
||||||
|
|
||||||
|
## AWS Resources
|
||||||
|
|
||||||
|
- **Stack:** `google-user-sync` (CDK, us-east-1)
|
||||||
|
- **Lambda:** `google-user-sync` — Node.js 22, arm64, 256 MB, 5 min timeout, 60-day log retention
|
||||||
|
- **EventBridge Rule:** `google-user-sync-daily` — weekdays at 11:00 UTC
|
||||||
|
- **Secrets Manager:** `google-user-sync/google-service-account`, `google-user-sync/front-api-token`
|
||||||
|
|
||||||
|
## Prerequisites
|
||||||
|
|
||||||
|
### 1. Create Custom Fields in Front
|
||||||
|
|
||||||
|
1. Gear icon > Company Settings > Custom Fields > Teammates tab
|
||||||
|
2. Create two fields:
|
||||||
|
- **Job Title** (String)
|
||||||
|
- **Phone** (String)
|
||||||
|
|
||||||
|
### 2. Generate a Front API Token
|
||||||
|
|
||||||
|
1. Gear icon > Company Settings > Developers > API tokens
|
||||||
|
2. Create token with **Shared resources** scope (teammate read/write)
|
||||||
|
|
||||||
|
### 3. Create a Google Cloud Service Account
|
||||||
|
|
||||||
|
1. Enable the **Admin SDK API** in Google Cloud Console
|
||||||
|
2. Create a service account named `front-directory-sync`
|
||||||
|
3. Create a JSON key and download it
|
||||||
|
4. Enable Domain-Wide Delegation and copy the Client ID
|
||||||
|
|
||||||
|
### 4. Authorize in Google Workspace Admin
|
||||||
|
|
||||||
|
1. Security > Access and Data Control > API Controls > Domain-Wide Delegation
|
||||||
|
2. Add the Client ID with scope: `https://www.googleapis.com/auth/admin.directory.user.readonly`
|
||||||
|
|
||||||
|
### 5. Populate Google User Profiles
|
||||||
|
|
||||||
|
Ensure each user has their **Job title** and **Phone** filled in under Directory > Users.
|
||||||
|
|
||||||
|
### 6. Store Secrets in AWS Secrets Manager
|
||||||
|
|
||||||
|
```bash
|
||||||
|
aws secretsmanager create-secret \
|
||||||
|
--name "google-user-sync/front-api-token" \
|
||||||
|
--secret-string "YOUR_FRONT_API_TOKEN" \
|
||||||
|
--region us-east-1
|
||||||
|
|
||||||
|
aws secretsmanager create-secret \
|
||||||
|
--name "google-user-sync/google-service-account" \
|
||||||
|
--secret-string file://path-to-service-account-key.json \
|
||||||
|
--region us-east-1
|
||||||
|
```
|
||||||
|
|
||||||
|
## Deployment
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd cdk
|
||||||
|
npm install
|
||||||
|
npx cdk deploy google-user-sync
|
||||||
|
```
|
||||||
|
|
||||||
|
## Verification
|
||||||
|
|
||||||
|
```bash
|
||||||
|
aws lambda invoke \
|
||||||
|
--function-name google-user-sync \
|
||||||
|
--region us-east-1 \
|
||||||
|
output.json && cat output.json
|
||||||
|
```
|
||||||
|
|
||||||
|
Check Front > Company Settings > Teammates > pick a user > Custom Fields to confirm Job Title and Phone are populated.
|
||||||
|
|
||||||
|
## Maintenance
|
||||||
|
|
||||||
|
- **New teammates:** Automatically picked up if they exist in both Google Workspace and Front with the same email.
|
||||||
|
- **Schedule changes:** Update the EventBridge rule in `cdk/lib/google-user-sync-stack.js`.
|
||||||
|
- **Additional fields:** Add as custom fields in Front, then update the field mapping in `lambda/index.js` (`buildCustomFields()`).
|
||||||
13
cdk/bin/app.js
Normal file
13
cdk/bin/app.js
Normal file
|
|
@ -0,0 +1,13 @@
|
||||||
|
#!/usr/bin/env node
|
||||||
|
const cdk = require("aws-cdk-lib");
|
||||||
|
const { GoogleUserSyncStack } = require("./lib/google-user-sync-stack");
|
||||||
|
|
||||||
|
const app = new cdk.App();
|
||||||
|
|
||||||
|
new GoogleUserSyncStack(app, "GoogleUserSyncStack", {
|
||||||
|
stackName: "google-user-sync",
|
||||||
|
env: {
|
||||||
|
account: "328440206208",
|
||||||
|
region: "us-east-1",
|
||||||
|
},
|
||||||
|
});
|
||||||
3
cdk/cdk.json
Normal file
3
cdk/cdk.json
Normal file
|
|
@ -0,0 +1,3 @@
|
||||||
|
{
|
||||||
|
"app": "node bin/app.js"
|
||||||
|
}
|
||||||
75
cdk/lib/google-user-sync-stack.js
Normal file
75
cdk/lib/google-user-sync-stack.js
Normal file
|
|
@ -0,0 +1,75 @@
|
||||||
|
const { Stack, Duration, RemovalPolicy, CfnOutput } = require("aws-cdk-lib");
|
||||||
|
const lambda = require("aws-cdk-lib/aws-lambda");
|
||||||
|
const events = require("aws-cdk-lib/aws-events");
|
||||||
|
const targets = require("aws-cdk-lib/aws-events-targets");
|
||||||
|
const secretsmanager = require("aws-cdk-lib/aws-secretsmanager");
|
||||||
|
const logs = require("aws-cdk-lib/aws-logs");
|
||||||
|
const path = require("path");
|
||||||
|
|
||||||
|
class GoogleUserSyncStack extends Stack {
|
||||||
|
constructor(scope, id, props) {
|
||||||
|
super(scope, id, props);
|
||||||
|
|
||||||
|
// -----------------------------------------------------------------
|
||||||
|
// Reference existing secrets (created manually per PLAN.md Step 6)
|
||||||
|
// -----------------------------------------------------------------
|
||||||
|
const googleSecret = secretsmanager.Secret.fromSecretNameV2(
|
||||||
|
this,
|
||||||
|
"GoogleServiceAccountSecret",
|
||||||
|
"google-user-sync/google-service-account"
|
||||||
|
);
|
||||||
|
|
||||||
|
const frontSecret = secretsmanager.Secret.fromSecretNameV2(
|
||||||
|
this,
|
||||||
|
"FrontApiTokenSecret",
|
||||||
|
"google-user-sync/front-api-token"
|
||||||
|
);
|
||||||
|
|
||||||
|
// -----------------------------------------------------------------
|
||||||
|
// Lambda function
|
||||||
|
// -----------------------------------------------------------------
|
||||||
|
const syncFn = new lambda.Function(this, "GoogleUserSyncFn", {
|
||||||
|
functionName: "google-user-sync",
|
||||||
|
runtime: lambda.Runtime.NODEJS_22_X,
|
||||||
|
architecture: lambda.Architecture.ARM_64,
|
||||||
|
handler: "index.handler",
|
||||||
|
code: lambda.Code.fromAsset(path.join(__dirname, "..", "lambda")),
|
||||||
|
timeout: Duration.minutes(5),
|
||||||
|
memorySize: 256,
|
||||||
|
environment: {
|
||||||
|
GOOGLE_SECRET_ARN: googleSecret.secretArn,
|
||||||
|
FRONT_SECRET_ARN: frontSecret.secretArn,
|
||||||
|
GOOGLE_ADMIN_EMAIL: "adam@seahavenind.com",
|
||||||
|
GOOGLE_DOMAIN: "seahavenind.com",
|
||||||
|
GOOGLE_OUS: "/Office/Scheduling,/Office/Operations",
|
||||||
|
},
|
||||||
|
logRetention: logs.RetentionDays.TWO_MONTHS,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Grant the Lambda read access to both secrets
|
||||||
|
googleSecret.grantRead(syncFn);
|
||||||
|
frontSecret.grantRead(syncFn);
|
||||||
|
|
||||||
|
// -----------------------------------------------------------------
|
||||||
|
// EventBridge scheduled rule — daily at 6:00 AM ET (11:00 UTC)
|
||||||
|
// -----------------------------------------------------------------
|
||||||
|
const rule = new events.Rule(this, "DailySyncRule", {
|
||||||
|
ruleName: "google-user-sync-daily",
|
||||||
|
schedule: events.Schedule.cron({
|
||||||
|
minute: "0",
|
||||||
|
hour: "11", // 11:00 UTC = 6:00 AM ET (EST+5) / 7:00 AM EDT
|
||||||
|
month: "*",
|
||||||
|
weekDay: "MON-FRI",
|
||||||
|
year: "*",
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
rule.addTarget(new targets.LambdaFunction(syncFn));
|
||||||
|
|
||||||
|
new CfnOutput(this, "SyncFunctionArn", {
|
||||||
|
value: syncFn.functionArn,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { GoogleUserSyncStack };
|
||||||
11
cdk/package.json
Normal file
11
cdk/package.json
Normal file
|
|
@ -0,0 +1,11 @@
|
||||||
|
{
|
||||||
|
"name": "google-user-sync-cdk",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"bin": {
|
||||||
|
"app": "bin/app.js"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"aws-cdk-lib": "^2.150.0",
|
||||||
|
"constructs": "^10.0.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
315
lambda/index.js
Normal file
315
lambda/index.js
Normal file
|
|
@ -0,0 +1,315 @@
|
||||||
|
/**
|
||||||
|
* google-user-sync Lambda
|
||||||
|
*
|
||||||
|
* Pulls user profiles from Google Workspace Admin Directory API
|
||||||
|
* and syncs job title + phone to Front teammate custom fields.
|
||||||
|
*
|
||||||
|
* Environment variables:
|
||||||
|
* GOOGLE_SECRET_ARN - Secrets Manager ARN for Google service account JSON key
|
||||||
|
* FRONT_SECRET_ARN - Secrets Manager ARN for Front API token
|
||||||
|
* GOOGLE_ADMIN_EMAIL - Email of a Google Workspace admin to impersonate
|
||||||
|
* GOOGLE_DOMAIN - Domain to list users for (e.g. seahaven.com)
|
||||||
|
* GOOGLE_OUS - Comma-separated org unit paths to sync (e.g. /Office/Scheduling,/Office/Operations)
|
||||||
|
* SLACK_WEBHOOK_URL - (Optional) Slack incoming webhook for sync summaries
|
||||||
|
*/
|
||||||
|
|
||||||
|
const {
|
||||||
|
SecretsManagerClient,
|
||||||
|
GetSecretValueCommand,
|
||||||
|
} = require("@aws-sdk/client-secrets-manager");
|
||||||
|
const crypto = require("crypto");
|
||||||
|
|
||||||
|
const sm = new SecretsManagerClient({ region: "us-east-1" });
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Google Auth (JWT → Access Token using service account)
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
function base64url(buf) {
|
||||||
|
return Buffer.from(buf)
|
||||||
|
.toString("base64")
|
||||||
|
.replace(/\+/g, "-")
|
||||||
|
.replace(/\//g, "_")
|
||||||
|
.replace(/=+$/, "");
|
||||||
|
}
|
||||||
|
|
||||||
|
async function getGoogleAccessToken(serviceAccountKey, adminEmail) {
|
||||||
|
const now = Math.floor(Date.now() / 1000);
|
||||||
|
const header = { alg: "RS256", typ: "JWT" };
|
||||||
|
const payload = {
|
||||||
|
iss: serviceAccountKey.client_email,
|
||||||
|
sub: adminEmail,
|
||||||
|
scope: "https://www.googleapis.com/auth/admin.directory.user.readonly",
|
||||||
|
aud: "https://oauth2.googleapis.com/token",
|
||||||
|
iat: now,
|
||||||
|
exp: now + 3600,
|
||||||
|
};
|
||||||
|
|
||||||
|
const segments = [
|
||||||
|
base64url(JSON.stringify(header)),
|
||||||
|
base64url(JSON.stringify(payload)),
|
||||||
|
];
|
||||||
|
const signingInput = segments.join(".");
|
||||||
|
|
||||||
|
const sign = crypto.createSign("RSA-SHA256");
|
||||||
|
sign.update(signingInput);
|
||||||
|
const signature = sign.sign(serviceAccountKey.private_key);
|
||||||
|
const jwt = signingInput + "." + base64url(signature);
|
||||||
|
|
||||||
|
const res = await fetch("https://oauth2.googleapis.com/token", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||||
|
body: new URLSearchParams({
|
||||||
|
grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer",
|
||||||
|
assertion: jwt,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!res.ok) {
|
||||||
|
const text = await res.text();
|
||||||
|
throw new Error(`Google token exchange failed (${res.status}): ${text}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = await res.json();
|
||||||
|
return data.access_token;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Google Admin Directory: list users for a specific OU
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
async function listGoogleUsersInOU(accessToken, domain, orgUnitPath) {
|
||||||
|
const users = [];
|
||||||
|
let pageToken = null;
|
||||||
|
|
||||||
|
do {
|
||||||
|
const params = new URLSearchParams({
|
||||||
|
domain,
|
||||||
|
maxResults: "500",
|
||||||
|
projection: "full",
|
||||||
|
orderBy: "email",
|
||||||
|
query: `orgUnitPath='${orgUnitPath}'`,
|
||||||
|
});
|
||||||
|
if (pageToken) params.set("pageToken", pageToken);
|
||||||
|
|
||||||
|
const res = await fetch(
|
||||||
|
`https://admin.googleapis.com/admin/directory/v1/users?${params}`,
|
||||||
|
{ headers: { Authorization: `Bearer ${accessToken}` } }
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!res.ok) {
|
||||||
|
const text = await res.text();
|
||||||
|
throw new Error(
|
||||||
|
`Google Directory API error for OU "${orgUnitPath}" (${res.status}): ${text}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = await res.json();
|
||||||
|
if (data.users) users.push(...data.users);
|
||||||
|
pageToken = data.nextPageToken || null;
|
||||||
|
} while (pageToken);
|
||||||
|
|
||||||
|
return users;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function listGoogleUsers(accessToken, domain, orgUnits) {
|
||||||
|
const allUsers = [];
|
||||||
|
const seen = new Set();
|
||||||
|
|
||||||
|
for (const ou of orgUnits) {
|
||||||
|
console.log(`Fetching users from OU: ${ou}`);
|
||||||
|
const users = await listGoogleUsersInOU(accessToken, domain, ou);
|
||||||
|
console.log(` Found ${users.length} users in ${ou}`);
|
||||||
|
|
||||||
|
for (const user of users) {
|
||||||
|
if (!seen.has(user.primaryEmail)) {
|
||||||
|
seen.add(user.primaryEmail);
|
||||||
|
allUsers.push(user);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return allUsers;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Extract fields from a Google user object
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
function extractUserFields(googleUser) {
|
||||||
|
const email = googleUser.primaryEmail;
|
||||||
|
|
||||||
|
// Job title lives in organizations[].title
|
||||||
|
let jobTitle = "";
|
||||||
|
if (googleUser.organizations && googleUser.organizations.length > 0) {
|
||||||
|
jobTitle = googleUser.organizations[0].title || "";
|
||||||
|
}
|
||||||
|
|
||||||
|
// Phone lives in phones[].value — prefer "work" type
|
||||||
|
let phone = "";
|
||||||
|
if (googleUser.phones && googleUser.phones.length > 0) {
|
||||||
|
const workPhone = googleUser.phones.find((p) => p.type === "work");
|
||||||
|
phone = workPhone
|
||||||
|
? workPhone.value
|
||||||
|
: googleUser.phones[0].value || "";
|
||||||
|
}
|
||||||
|
|
||||||
|
return { email, jobTitle, phone };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Front API: update teammate custom fields
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
async function updateFrontTeammate(frontToken, email, customFields) {
|
||||||
|
const url = `https://api2.frontapp.com/teammates/alt:email:${encodeURIComponent(email)}`;
|
||||||
|
|
||||||
|
const res = await fetch(url, {
|
||||||
|
method: "PATCH",
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${frontToken}`,
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
Accept: "application/json",
|
||||||
|
},
|
||||||
|
body: JSON.stringify({ custom_fields: customFields }),
|
||||||
|
});
|
||||||
|
|
||||||
|
// 204 = success, 404 = user not in Front (skip), anything else = error
|
||||||
|
if (res.status === 204) return { status: "updated" };
|
||||||
|
if (res.status === 404) return { status: "not_in_front" };
|
||||||
|
|
||||||
|
const text = await res.text();
|
||||||
|
return { status: "error", code: res.status, message: text };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Slack notification (optional)
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
async function notifySlack(webhookUrl, summary) {
|
||||||
|
if (!webhookUrl) return;
|
||||||
|
|
||||||
|
const text = [
|
||||||
|
`:arrows_counterclockwise: *Front ← Google Directory Sync Complete*`,
|
||||||
|
`• Updated: ${summary.updated}`,
|
||||||
|
`• Skipped (not in Front): ${summary.notInFront}`,
|
||||||
|
`• Skipped (no data): ${summary.noData}`,
|
||||||
|
`• Errors: ${summary.errors}`,
|
||||||
|
];
|
||||||
|
|
||||||
|
if (summary.errorDetails.length > 0) {
|
||||||
|
text.push("");
|
||||||
|
text.push("*Errors:*");
|
||||||
|
summary.errorDetails.slice(0, 5).forEach((e) => {
|
||||||
|
text.push(` - \`${e.email}\`: ${e.message}`);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
await fetch(webhookUrl, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ text: text.join("\n") }),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Handler
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
exports.handler = async (event) => {
|
||||||
|
console.log("Starting Front ← Google Directory sync");
|
||||||
|
|
||||||
|
// 1. Fetch secrets
|
||||||
|
const [googleSecretRes, frontSecretRes] = await Promise.all([
|
||||||
|
sm.send(
|
||||||
|
new GetSecretValueCommand({ SecretId: process.env.GOOGLE_SECRET_ARN })
|
||||||
|
),
|
||||||
|
sm.send(
|
||||||
|
new GetSecretValueCommand({ SecretId: process.env.FRONT_SECRET_ARN })
|
||||||
|
),
|
||||||
|
]);
|
||||||
|
|
||||||
|
const googleKey = JSON.parse(googleSecretRes.SecretString);
|
||||||
|
const frontToken = frontSecretRes.SecretString;
|
||||||
|
|
||||||
|
// 2. Get Google access token
|
||||||
|
const accessToken = await getGoogleAccessToken(
|
||||||
|
googleKey,
|
||||||
|
process.env.GOOGLE_ADMIN_EMAIL
|
||||||
|
);
|
||||||
|
console.log("Obtained Google access token");
|
||||||
|
|
||||||
|
// 3. List Google Workspace users from specified OUs
|
||||||
|
const orgUnits = process.env.GOOGLE_OUS
|
||||||
|
.split(",")
|
||||||
|
.map((ou) => ou.trim())
|
||||||
|
.filter(Boolean);
|
||||||
|
console.log(`Syncing OUs: ${orgUnits.join(", ")}`);
|
||||||
|
|
||||||
|
const googleUsers = await listGoogleUsers(
|
||||||
|
accessToken,
|
||||||
|
process.env.GOOGLE_DOMAIN,
|
||||||
|
orgUnits
|
||||||
|
);
|
||||||
|
console.log(`Found ${googleUsers.length} total users across ${orgUnits.length} OUs`);
|
||||||
|
|
||||||
|
// 4. Sync each user to Front
|
||||||
|
const summary = {
|
||||||
|
updated: 0,
|
||||||
|
notInFront: 0,
|
||||||
|
noData: 0,
|
||||||
|
errors: 0,
|
||||||
|
errorDetails: [],
|
||||||
|
};
|
||||||
|
|
||||||
|
for (const googleUser of googleUsers) {
|
||||||
|
const { email, jobTitle, phone } = extractUserFields(googleUser);
|
||||||
|
|
||||||
|
// Skip users with no title AND no phone — nothing to sync
|
||||||
|
if (!jobTitle && !phone) {
|
||||||
|
console.log(`Skipping ${email} — no title or phone in Google`);
|
||||||
|
summary.noData++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const customFields = {};
|
||||||
|
if (jobTitle) customFields["Job Title"] = jobTitle;
|
||||||
|
if (phone) customFields["Phone"] = phone;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await updateFrontTeammate(frontToken, email, customFields);
|
||||||
|
|
||||||
|
if (result.status === "updated") {
|
||||||
|
console.log(`Updated ${email}: ${JSON.stringify(customFields)}`);
|
||||||
|
summary.updated++;
|
||||||
|
} else if (result.status === "not_in_front") {
|
||||||
|
console.log(`Skipped ${email} — not a Front teammate`);
|
||||||
|
summary.notInFront++;
|
||||||
|
} else {
|
||||||
|
console.error(`Error updating ${email}: ${result.code} ${result.message}`);
|
||||||
|
summary.errors++;
|
||||||
|
summary.errorDetails.push({
|
||||||
|
email,
|
||||||
|
message: `${result.code}: ${result.message}`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.error(`Exception updating ${email}:`, err);
|
||||||
|
summary.errors++;
|
||||||
|
summary.errorDetails.push({ email, message: err.message });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Simple rate-limit courtesy — Front API has rate limits
|
||||||
|
await new Promise((r) => setTimeout(r, 200));
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log("Sync summary:", JSON.stringify(summary));
|
||||||
|
|
||||||
|
// 5. Notify Slack
|
||||||
|
await notifySlack(process.env.SLACK_WEBHOOK_URL, summary);
|
||||||
|
|
||||||
|
return {
|
||||||
|
statusCode: 200,
|
||||||
|
body: summary,
|
||||||
|
};
|
||||||
|
};
|
||||||
9
lambda/package.json
Normal file
9
lambda/package.json
Normal file
|
|
@ -0,0 +1,9 @@
|
||||||
|
{
|
||||||
|
"name": "google-user-sync",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"description": "Syncs Google Workspace user profiles to Front teammate custom fields",
|
||||||
|
"main": "index.js",
|
||||||
|
"dependencies": {
|
||||||
|
"@aws-sdk/client-secrets-manager": "^3.600.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
Loading…
Add table
Reference in a new issue