Files
parcer/server/src/routes/auth.ts

863 lines
24 KiB
TypeScript
Raw Normal View History

2024-11-13 00:05:01 +05:30
import { Router, Request, Response } from "express";
2025-01-26 14:22:36 +05:30
import Airtable from "airtable";
2024-11-13 00:05:01 +05:30
import User from "../models/User";
import Robot from "../models/Robot";
import jwt from "jsonwebtoken";
import { hashPassword, comparePassword } from "../utils/auth";
import { requireSignIn } from "../middlewares/auth";
import { genAPIKey } from "../utils/api";
import { google } from "googleapis";
import { capture } from "../utils/analytics";
2025-01-26 14:22:36 +05:30
declare module "express-session" {
interface SessionData {
code_verifier: string;
robotId: string;
}
}
2024-09-23 23:57:12 +05:30
export const router = Router();
2024-09-23 23:54:19 +05:30
2024-09-24 17:39:50 +05:30
interface AuthenticatedRequest extends Request {
2024-11-13 00:05:01 +05:30
user?: { id: string };
2024-09-24 17:39:50 +05:30
}
2024-11-13 00:05:01 +05:30
router.post("/register", async (req, res) => {
try {
const { email, password } = req.body;
if (!email) return res.status(400).send("Email is required");
if (!password || password.length < 6)
return res
.status(400)
.send("Password is required and must be at least 6 characters");
let userExist = await User.findOne({ raw: true, where: { email } });
if (userExist) return res.status(400).send("User already exists");
const hashedPassword = await hashPassword(password);
let user: any;
2024-09-23 23:55:41 +05:30
try {
2024-11-13 00:05:01 +05:30
user = await User.create({ email, password: hashedPassword });
2024-09-24 19:07:02 +05:30
} catch (error: any) {
2024-11-13 00:05:01 +05:30
console.log(`Could not create user - ${error}`);
return res.status(500).send(`Could not create user - ${error.message}`);
2024-09-23 23:55:41 +05:30
}
2024-09-23 23:55:53 +05:30
2024-11-13 00:05:01 +05:30
if (!process.env.JWT_SECRET) {
console.log("JWT_SECRET is not defined in the environment");
return res.status(500).send("Internal Server Error");
2024-09-23 23:55:53 +05:30
}
2024-11-13 00:05:01 +05:30
2024-11-18 19:44:30 +05:30
const token = jwt.sign({ id: user.id }, process.env.JWT_SECRET as string);
2024-11-13 00:05:01 +05:30
user.password = undefined as unknown as string;
res.cookie("token", token, {
httpOnly: true,
});
capture("maxun-oss-user-registered", {
email: user.email,
userId: user.id,
registeredAt: new Date().toISOString(),
});
2024-12-23 23:15:53 +05:30
console.log(`User registered`);
2024-11-13 00:05:01 +05:30
res.json(user);
} catch (error: any) {
console.log(`Could not register user - ${error}`);
res.status(500).send(`Could not register user - ${error.message}`);
}
2024-09-26 17:48:56 +05:30
});
2024-11-13 00:05:01 +05:30
router.post("/login", async (req, res) => {
try {
const { email, password } = req.body;
if (!email || !password)
return res.status(400).send("Email and password are required");
if (password.length < 6)
return res.status(400).send("Password must be at least 6 characters");
2024-10-28 21:10:02 +05:30
2024-11-13 00:05:01 +05:30
let user = await User.findOne({ raw: true, where: { email } });
if (!user) return res.status(400).send("User does not exist");
2024-10-28 21:10:02 +05:30
2024-11-13 00:05:01 +05:30
const match = await comparePassword(password, user.password);
if (!match) return res.status(400).send("Invalid email or password");
2024-10-28 21:10:02 +05:30
2024-11-18 19:44:30 +05:30
const token = jwt.sign({ id: user?.id }, process.env.JWT_SECRET as string);
2024-11-13 00:05:01 +05:30
// return user and token to client, exclude hashed password
if (user) {
user.password = undefined as unknown as string;
2024-10-28 21:10:02 +05:30
}
2024-11-13 00:05:01 +05:30
res.cookie("token", token, {
httpOnly: true,
});
capture("maxun-oss-user-login", {
email: user.email,
userId: user.id,
loggedInAt: new Date().toISOString(),
});
res.json(user);
} catch (error: any) {
res.status(400).send(`Could not login user - ${error.message}`);
console.log(`Could not login user - ${error}`);
}
});
router.get("/logout", async (req, res) => {
try {
res.clearCookie("token");
return res.json({ message: "Logout successful" });
} catch (error: any) {
res.status(500).send(`Could not logout user - ${error.message}`);
}
2024-10-28 21:10:02 +05:30
});
2024-11-13 00:05:01 +05:30
router.get(
"/current-user",
requireSignIn,
async (req: Request, res) => {
2025-01-29 15:22:15 +05:30
const authenticatedReq = req as AuthenticatedRequest;
2024-09-26 17:48:56 +05:30
try {
if (!authenticatedReq.user) {
2024-11-13 00:05:01 +05:30
return res.status(401).json({ ok: false, error: "Unauthorized" });
}
2025-01-29 15:24:19 +05:30
const user = await User.findByPk(authenticatedReq.user.id, {
2024-11-13 00:05:01 +05:30
attributes: { exclude: ["password"] },
});
if (!user) {
return res.status(404).json({ ok: false, error: "User not found" });
} else {
return res.status(200).json({ ok: true, user: user });
}
} catch (error: any) {
console.error("Error in current-user route:", error);
return res
.status(500)
.json({
ok: false,
error: `Could not fetch current user: ${error.message}`,
2024-09-26 17:48:56 +05:30
});
2024-11-13 00:05:01 +05:30
}
}
);
2024-09-26 17:48:56 +05:30
2024-11-13 00:05:01 +05:30
router.get(
"/user/:id",
requireSignIn,
async (req: Request, res) => {
2024-11-13 00:05:01 +05:30
try {
const { id } = req.params;
if (!id) {
return res.status(400).json({ message: "User ID is required" });
}
const user = await User.findByPk(id, {
attributes: { exclude: ["password"] },
});
if (!user) {
return res.status(404).json({ message: "User not found" });
}
return res
.status(200)
.json({ message: "User fetched successfully", user });
} catch (error: any) {
return res
.status(500)
.json({ message: "Error fetching user", error: error.message });
}
}
);
2024-10-28 04:12:21 +05:30
2024-11-13 00:05:01 +05:30
router.post(
"/generate-api-key",
requireSignIn,
async (req: Request, res) => {
2025-01-29 15:22:15 +05:30
const authenticatedReq = req as AuthenticatedRequest;
2024-11-13 00:05:01 +05:30
try {
if (!authenticatedReq.user) {
2024-11-13 00:05:01 +05:30
return res.status(401).json({ ok: false, error: "Unauthorized" });
}
2025-01-29 15:24:19 +05:30
const user = await User.findByPk(authenticatedReq.user.id, {
2024-11-13 00:05:01 +05:30
attributes: { exclude: ["password"] },
});
if (!user) {
return res.status(404).json({ message: "User not found" });
}
if (user.api_key) {
return res.status(400).json({ message: "API key already exists" });
}
const apiKey = genAPIKey();
await user.update({ api_key: apiKey });
capture("maxun-oss-api-key-created", {
user_id: user.id,
created_at: new Date().toISOString(),
});
return res.status(200).json({
message: "API key generated successfully",
api_key: apiKey,
});
2024-09-26 17:48:56 +05:30
} catch (error) {
2024-11-13 00:05:01 +05:30
return res
.status(500)
.json({ message: "Error generating API key", error });
2024-09-26 17:48:56 +05:30
}
2024-11-13 00:05:01 +05:30
}
);
2024-10-03 02:28:46 +05:30
2024-11-13 00:05:01 +05:30
router.get(
"/api-key",
requireSignIn,
async (req: Request, res) => {
2025-01-29 15:22:15 +05:30
const authenticatedReq = req as AuthenticatedRequest;
2024-10-03 02:28:46 +05:30
try {
if (!authenticatedReq.user) {
2024-11-13 00:05:01 +05:30
return res.status(401).json({ ok: false, error: "Unauthorized" });
}
2025-01-29 15:24:19 +05:30
const user = await User.findByPk(authenticatedReq.user.id, {
2024-11-13 00:05:01 +05:30
raw: true,
attributes: ["api_key"],
});
if (!user) {
return res.status(404).json({ message: "User not found" });
}
return res.status(200).json({
message: "API key fetched successfully",
api_key: user.api_key || null,
});
2024-10-03 02:28:46 +05:30
} catch (error) {
2024-11-13 00:05:01 +05:30
return res.status(500).json({ message: "Error fetching API key", error });
2024-10-03 02:28:46 +05:30
}
2024-11-13 00:05:01 +05:30
}
);
2024-10-24 22:26:12 +05:30
2024-11-13 00:05:01 +05:30
router.delete(
"/delete-api-key",
requireSignIn,
async (req: Request, res) => {
2025-01-29 15:22:15 +05:30
const authenticatedReq = req as AuthenticatedRequest;
if (!authenticatedReq.user) {
2024-11-13 00:05:01 +05:30
return res.status(401).send({ error: "Unauthorized" });
2024-10-24 22:26:12 +05:30
}
2024-10-03 04:05:15 +05:30
try {
2025-01-29 15:24:19 +05:30
const user = await User.findByPk(authenticatedReq.user.id, { raw: true });
2024-10-03 04:42:24 +05:30
2024-11-13 00:05:01 +05:30
if (!user) {
return res.status(404).json({ message: "User not found" });
}
2024-10-03 04:42:24 +05:30
2024-11-13 00:05:01 +05:30
if (!user.api_key) {
return res.status(404).json({ message: "API Key not found" });
}
2024-10-03 04:42:24 +05:30
2025-01-29 15:24:19 +05:30
await User.update({ api_key: null }, { where: { id: authenticatedReq.user.id } });
2024-10-03 04:42:24 +05:30
2024-11-13 00:05:01 +05:30
capture("maxun-oss-api-key-deleted", {
user_id: user.id,
deleted_at: new Date().toISOString(),
});
2024-10-28 04:12:21 +05:30
2024-11-13 00:05:01 +05:30
return res.status(200).json({ message: "API Key deleted successfully" });
2024-10-03 04:42:08 +05:30
} catch (error: any) {
2024-11-13 00:05:01 +05:30
return res
.status(500)
.json({ message: "Error deleting API key", error: error.message });
2024-10-03 04:05:15 +05:30
}
2024-11-13 00:05:01 +05:30
}
);
2024-10-16 19:22:34 +05:30
const oauth2Client = new google.auth.OAuth2(
2024-11-13 00:05:01 +05:30
process.env.GOOGLE_CLIENT_ID,
process.env.GOOGLE_CLIENT_SECRET,
process.env.GOOGLE_REDIRECT_URI
2024-10-16 19:22:34 +05:30
);
// Step 1: Redirect to Google for authentication
2024-11-13 00:05:01 +05:30
router.get("/google", (req, res) => {
const { robotId } = req.query;
if (!robotId) {
return res.status(400).json({ message: "Robot ID is required" });
}
const scopes = [
"https://www.googleapis.com/auth/spreadsheets",
"https://www.googleapis.com/auth/userinfo.email",
"https://www.googleapis.com/auth/drive.readonly",
];
const url = oauth2Client.generateAuthUrl({
access_type: "offline",
prompt: "consent", // Ensures you get a refresh token on first login
scope: scopes,
state: robotId.toString(),
});
res.redirect(url);
});
2024-10-16 19:22:34 +05:30
// Step 2: Handle Google OAuth callback
2024-11-13 00:05:01 +05:30
router.get(
"/google/callback",
requireSignIn,
async (req: Request, res) => {
2025-01-29 15:22:15 +05:30
const authenticatedReq = req as AuthenticatedRequest;
2024-10-17 13:28:06 +05:30
const { code, state } = req.query;
try {
2024-11-13 00:05:01 +05:30
if (!state) {
return res.status(400).json({ message: "Robot ID is required" });
}
const robotId = state;
// Get access and refresh tokens
if (typeof code !== "string") {
return res.status(400).json({ message: "Invalid code" });
}
const { tokens } = await oauth2Client.getToken(code);
oauth2Client.setCredentials(tokens);
// Get user profile from Google
const oauth2 = google.oauth2({ version: "v2", auth: oauth2Client });
const {
data: { email },
} = await oauth2.userinfo.get();
if (!email) {
return res.status(400).json({ message: "Email not found" });
}
if (!authenticatedReq.user) {
2024-11-13 00:05:01 +05:30
return res.status(401).send({ error: "Unauthorized" });
}
// Get the currently authenticated user (from `requireSignIn`)
2025-01-29 15:24:19 +05:30
let user = await User.findOne({ where: { id: authenticatedReq.user.id } });
2024-11-13 00:05:01 +05:30
if (!user) {
return res.status(400).json({ message: "User not found" });
}
let robot = await Robot.findOne({
where: { "recording_meta.id": robotId },
});
if (!robot) {
return res.status(400).json({ message: "Robot not found" });
}
robot = await robot.update({
google_sheet_email: email,
google_access_token: tokens.access_token,
google_refresh_token: tokens.refresh_token,
});
capture("maxun-oss-google-sheet-integration-created", {
user_id: user.id,
robot_id: robot.recording_meta.id,
created_at: new Date().toISOString(),
});
// List user's Google Sheets from their Google Drive
const drive = google.drive({ version: "v3", auth: oauth2Client });
const response = await drive.files.list({
q: "mimeType='application/vnd.google-apps.spreadsheet'", // List only Google Sheets files
fields: "files(id, name)", // Retrieve the ID and name of each file
});
const files = response.data.files || [];
if (files.length === 0) {
return res.status(404).json({ message: "No spreadsheets found." });
}
// Generate JWT token for session
const jwtToken = jwt.sign(
{ id: user.id },
2024-11-18 19:44:30 +05:30
process.env.JWT_SECRET as string
2024-11-13 00:05:01 +05:30
);
res.cookie("token", jwtToken, { httpOnly: true });
// res.json({
// message: 'Google authentication successful',
// google_sheet_email: robot.google_sheet_email,
// jwtToken,
// files
// });
res.cookie("robot_auth_status", "success", {
httpOnly: false,
maxAge: 60000,
}); // 1-minute expiration
2025-01-25 12:43:06 +05:30
// res.cookie("robot_auth_message", "Robot successfully authenticated", {
// httpOnly: false,
// maxAge: 60000,
// });
res.cookie('robot_auth_robotId', robotId, {
2024-11-13 00:05:01 +05:30
httpOnly: false,
maxAge: 60000,
});
2025-01-25 12:43:06 +05:30
const baseUrl = process.env.PUBLIC_URL || "http://localhost:5173";
const redirectUrl = `${baseUrl}/robots/`;
res.redirect(redirectUrl);
2024-10-16 20:25:02 +05:30
} catch (error: any) {
2024-11-13 00:05:01 +05:30
res.status(500).json({ message: `Google OAuth error: ${error.message}` });
2024-10-16 19:22:34 +05:30
}
2024-11-13 00:05:01 +05:30
}
);
2024-10-16 21:14:58 +05:30
// Step 3: Get data from Google Sheets
2024-11-13 00:05:01 +05:30
router.post(
"/gsheets/data",
requireSignIn,
async (req: Request, res) => {
2025-01-29 15:22:15 +05:30
const authenticatedReq = req as AuthenticatedRequest;
2024-10-16 23:52:03 +05:30
const { spreadsheetId, robotId } = req.body;
if (!authenticatedReq.user) {
2024-11-13 00:05:01 +05:30
return res.status(401).send({ error: "Unauthorized" });
2024-10-28 03:05:45 +05:30
}
2025-01-29 15:24:19 +05:30
const user = await User.findByPk(authenticatedReq.user.id, { raw: true });
2024-10-16 20:15:10 +05:30
if (!user) {
2024-11-13 00:05:01 +05:30
return res.status(400).json({ message: "User not found" });
}
2024-11-13 00:05:01 +05:30
const robot = await Robot.findOne({
where: { "recording_meta.id": robotId },
raw: true,
});
2024-10-16 23:52:03 +05:30
if (!robot) {
2024-11-13 00:05:01 +05:30
return res.status(400).json({ message: "Robot not found" });
2024-10-16 23:52:03 +05:30
}
// Set Google OAuth credentials
oauth2Client.setCredentials({
2024-11-13 00:05:01 +05:30
access_token: robot.google_access_token,
refresh_token: robot.google_refresh_token,
});
2024-11-13 00:05:01 +05:30
const sheets = google.sheets({ version: "v4", auth: oauth2Client });
try {
2024-11-13 00:05:01 +05:30
// Fetch data from the spreadsheet (you can let the user choose a specific range too)
const sheetData = await sheets.spreadsheets.values.get({
spreadsheetId,
range: "Sheet1!A1:D5", // Default range, could be dynamic based on user input
});
res.json(sheetData.data);
2024-10-16 20:25:02 +05:30
} catch (error: any) {
2024-11-13 00:05:01 +05:30
res
.status(500)
.json({ message: `Error accessing Google Sheets: ${error.message}` });
}
2024-11-13 00:05:01 +05:30
}
);
2024-10-17 16:13:29 +05:30
// Step 4: Get user's Google Sheets files (new route)
2024-11-13 00:05:01 +05:30
router.get("/gsheets/files", requireSignIn, async (req, res) => {
try {
const robotId = req.query.robotId;
const robot = await Robot.findOne({
where: { "recording_meta.id": robotId },
raw: true,
});
2024-10-17 16:13:29 +05:30
2024-11-13 00:05:01 +05:30
if (!robot) {
return res.status(400).json({ message: "Robot not found" });
}
2024-10-17 16:13:29 +05:30
2024-11-13 00:05:01 +05:30
oauth2Client.setCredentials({
access_token: robot.google_access_token,
refresh_token: robot.google_refresh_token,
});
2024-10-17 16:13:29 +05:30
2024-11-13 00:05:01 +05:30
// List user's Google Sheets files from their Google Drive
const drive = google.drive({ version: "v3", auth: oauth2Client });
const response = await drive.files.list({
q: "mimeType='application/vnd.google-apps.spreadsheet'",
fields: "files(id, name)",
});
2024-10-17 16:13:29 +05:30
2024-11-13 00:05:01 +05:30
const files = response.data.files || [];
if (files.length === 0) {
return res.status(404).json({ message: "No spreadsheets found." });
2024-10-17 16:13:29 +05:30
}
2024-11-13 00:05:01 +05:30
res.json(files);
} catch (error: any) {
console.log("Error fetching Google Sheets files:", error);
res
.status(500)
.json({
message: `Error retrieving Google Sheets files: ${error.message}`,
});
}
2024-10-17 17:28:44 +05:30
});
// Step 5: Update robot's google_sheet_id when a Google Sheet is selected
2024-11-13 00:05:01 +05:30
router.post("/gsheets/update", requireSignIn, async (req, res) => {
const { spreadsheetId, spreadsheetName, robotId } = req.body;
if (!spreadsheetId || !robotId) {
return res
.status(400)
.json({ message: "Spreadsheet ID and Robot ID are required" });
}
try {
let robot = await Robot.findOne({
where: { "recording_meta.id": robotId },
});
2024-10-17 17:28:44 +05:30
2024-11-13 00:05:01 +05:30
if (!robot) {
return res.status(404).json({ message: "Robot not found" });
2024-10-17 17:28:44 +05:30
}
2024-11-13 00:05:01 +05:30
await robot.update({
google_sheet_id: spreadsheetId,
google_sheet_name: spreadsheetName,
});
2024-10-17 17:28:44 +05:30
2024-11-13 00:05:01 +05:30
res.json({ message: "Robot updated with selected Google Sheet ID" });
} catch (error: any) {
res.status(500).json({ message: `Error updating robot: ${error.message}` });
}
2024-10-17 17:28:44 +05:30
});
2024-10-21 02:33:38 +05:30
2024-11-13 00:05:01 +05:30
router.post(
"/gsheets/remove",
requireSignIn,
async (req: Request, res) => {
2025-01-29 15:22:15 +05:30
const authenticatedReq = req as AuthenticatedRequest;
2024-10-21 02:33:38 +05:30
const { robotId } = req.body;
if (!robotId) {
2024-11-13 00:05:01 +05:30
return res.status(400).json({ message: "Robot ID is required" });
2024-10-21 02:33:38 +05:30
}
if (!authenticatedReq.user) {
2024-11-13 00:05:01 +05:30
return res.status(401).send({ error: "Unauthorized" });
2024-10-28 04:12:21 +05:30
}
2024-10-21 02:33:38 +05:30
try {
2024-11-13 00:05:01 +05:30
let robot = await Robot.findOne({
where: { "recording_meta.id": robotId },
});
if (!robot) {
return res.status(404).json({ message: "Robot not found" });
}
await robot.update({
google_sheet_id: null,
google_sheet_name: null,
google_sheet_email: null,
google_access_token: null,
google_refresh_token: null,
});
capture("maxun-oss-google-sheet-integration-removed", {
2025-01-29 15:24:19 +05:30
user_id: authenticatedReq.user.id,
2024-11-13 00:05:01 +05:30
robot_id: robotId,
deleted_at: new Date().toISOString(),
});
res.json({ message: "Google Sheets integration removed successfully" });
2024-10-21 02:33:38 +05:30
} catch (error: any) {
2024-11-13 00:05:01 +05:30
res
.status(500)
.json({
message: `Error removing Google Sheets integration: ${error.message}`,
});
2024-10-21 02:33:38 +05:30
}
2024-11-13 00:05:01 +05:30
}
);
2025-01-26 14:22:36 +05:30
import crypto from 'crypto';
// Airtable OAuth Routes
router.get("/airtable", (req, res) => {
const { robotId } = req.query;
if (!robotId) {
return res.status(400).json({ message: "Robot ID is required" });
}
// Generate PKCE codes
const code_verifier = crypto.randomBytes(64).toString('base64url');
const code_challenge = crypto.createHash('sha256')
.update(code_verifier)
.digest('base64url');
// Store in session
req.session.code_verifier = code_verifier;
req.session.robotId = robotId.toString();
const params = new URLSearchParams({
client_id: process.env.AIRTABLE_CLIENT_ID!,
redirect_uri: process.env.AIRTABLE_REDIRECT_URI!,
response_type: 'code',
state: robotId.toString(),
scope: 'data.records:read data.records:write schema.bases:read',
code_challenge: code_challenge,
code_challenge_method: 'S256'
});
res.redirect(`https://airtable.com/oauth2/v1/authorize?${params}`);
});
router.get("/airtable/callback", async (req, res) => {
try {
const { code, state, error } = req.query;
if (error) {
return res.redirect(
`${process.env.PUBLIC_URL}/robots/${state}/integrate?error=${encodeURIComponent(error.toString())}`
);
}
if (!code || !state) {
return res.status(400).json({ message: "Missing authorization code or state" });
}
// Verify session data
if (!req.session?.code_verifier || req.session.robotId !== state.toString()) {
return res.status(400).json({
message: "Session expired - please restart the OAuth flow"
});
}
// Exchange code for tokens
const tokenResponse = await fetch("https://airtable.com/oauth2/v1/token", {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
body: new URLSearchParams({
grant_type: "authorization_code",
code: code.toString(),
client_id: process.env.AIRTABLE_CLIENT_ID!,
redirect_uri: process.env.AIRTABLE_REDIRECT_URI!,
code_verifier: req.session.code_verifier
}),
});
if (!tokenResponse.ok) {
const errorData = await tokenResponse.json();
console.error('Token exchange failed:', errorData);
return res.redirect(
`${process.env.PUBLIC_URL}/robots/${state}/integrate?error=${encodeURIComponent(errorData.error_description || 'Authentication failed')}`
);
}
const tokens = await tokenResponse.json();
// Update robot with credentials
const robot = await Robot.findOne({
where: { "recording_meta.id": req.session.robotId }
});
if (!robot) {
return res.status(404).json({ message: "Robot not found" });
}
await robot.update({
airtable_access_token: tokens.access_token,
airtable_refresh_token: tokens.refresh_token,
2025-01-26 21:05:08 +05:30
2025-01-26 14:22:36 +05:30
});
// Clear session data
req.session.destroy((err) => {
if (err) console.error('Session cleanup error:', err);
});
2025-01-27 21:29:11 +05:30
res.cookie("airtable_auth_status", "success", {
httpOnly: false,
maxAge: 60000,
}); // 1-minute expiration
res.cookie("airtable_auth_message", "Robot successfully authenticated", {
httpOnly: false,
maxAge: 60000,
});
2025-01-26 14:22:36 +05:30
res.redirect(
2025-01-27 21:29:11 +05:30
`${process.env.PUBLIC_URL}/robots/${state}/integrate || http://localhost:5173/robots/${state}/integrate`
2025-01-26 14:22:36 +05:30
);
} catch (error: any) {
console.error('Airtable callback error:', error);
res.redirect(
`${process.env.PUBLIC_URL}/robots/${req.session.robotId}/integrate?error=${encodeURIComponent(error.message)}`
);
}
});
// Get Airtable bases
2025-01-26 21:05:08 +05:30
router.get("/airtable/bases", async (req: AuthenticatedRequest, res) => {
2025-01-26 14:22:36 +05:30
try {
const { robotId } = req.query;
if (!robotId) {
return res.status(400).json({ message: "Robot ID is required" });
}
const robot = await Robot.findOne({
2025-01-26 21:05:08 +05:30
where: { "recording_meta.id": robotId.toString() },
2025-01-26 14:22:36 +05:30
raw: true,
});
if (!robot?.airtable_access_token) {
return res.status(400).json({ message: "Robot not authenticated with Airtable" });
}
const response = await fetch('https://api.airtable.com/v0/meta/bases', {
headers: {
'Authorization': `Bearer ${robot.airtable_access_token}`
}
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.error.message || 'Failed to fetch bases');
}
const data = await response.json();
res.json(data.bases.map((base: any) => ({
id: base.id,
name: base.name
})));
} catch (error: any) {
res.status(500).json({ message: error.message });
}
});
// Update robot with selected base
router.post("/airtable/update", async (req: AuthenticatedRequest, res) => {
const { baseId, robotId , tableName} = req.body;
2025-01-26 14:22:36 +05:30
if (!baseId || !robotId) {
return res.status(400).json({ message: "Base ID and Robot ID are required" });
}
try {
const robot = await Robot.findOne({
where: { "recording_meta.id": robotId }
});
if (!robot) {
return res.status(404).json({ message: "Robot not found" });
}
await robot.update({
airtable_base_id: baseId,
airtable_table_name: tableName,
2025-01-26 14:22:36 +05:30
});
capture("maxun-oss-airtable-integration-created", {
user_id: req.user?.id,
robot_id: robotId,
created_at: new Date().toISOString(),
});
res.json({ message: "Airtable base updated successfully" });
} catch (error: any) {
res.status(500).json({ message: error.message });
}
});
// Remove Airtable integration
router.post("/airtable/remove", requireSignIn, async (req: AuthenticatedRequest, res) => {
const { robotId } = req.body;
if (!robotId) {
return res.status(400).json({ message: "Robot ID is required" });
}
try {
const robot = await Robot.findOne({
where: { "recording_meta.id": robotId }
});
if (!robot) {
return res.status(404).json({ message: "Robot not found" });
}
await robot.update({
airtable_access_token: null,
airtable_refresh_token: null,
airtable_base_id: null,
});
capture("maxun-oss-airtable-integration-removed", {
user_id: req.user?.id,
robot_id: robotId,
deleted_at: new Date().toISOString(),
});
res.json({ message: "Airtable integration removed successfully" });
} catch (error: any) {
res.status(500).json({ message: error.message });
}
});
// Fetch tables from an Airtable base
router.get("/airtable/tables", async (req: AuthenticatedRequest, res) => {
try {
const { baseId, robotId } = req.query;
if (!baseId || !robotId) {
return res.status(400).json({ message: "Base ID and Robot ID are required" });
}
const robot = await Robot.findOne({
where: { "recording_meta.id": robotId.toString() },
raw: true,
});
if (!robot?.airtable_access_token) {
return res.status(400).json({ message: "Robot not authenticated with Airtable" });
}
const response = await fetch(`https://api.airtable.com/v0/meta/bases/${baseId}/tables`, {
headers: {
'Authorization': `Bearer ${robot.airtable_access_token}`
}
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.error.message || 'Failed to fetch tables');
}
const data = await response.json();
res.json(data.tables.map((table: any) => ({
id: table.id,
name: table.name,
fields: table.fields
})));
} catch (error: any) {
res.status(500).json({ message: error.message });
}
});