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

638 lines
17 KiB
TypeScript
Raw Normal View History

2024-11-13 00:05:01 +05:30
import { Router, Request, Response } from "express";
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";
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;
// Validation checks with translation codes
if (!email) {
return res.status(400).json({
error: "VALIDATION_ERROR",
code: "register.validation.email_required"
});
}
if (!password || password.length < 6) {
return res.status(400).json({
error: "VALIDATION_ERROR",
code: "register.validation.password_requirements"
});
}
2024-11-13 00:05:01 +05:30
// Check if user exists
2024-11-13 00:05:01 +05:30
let userExist = await User.findOne({ raw: true, where: { email } });
if (userExist) {
return res.status(400).json({
error: "USER_EXISTS",
code: "register.error.user_exists"
});
}
2024-11-13 00:05:01 +05:30
const hashedPassword = await hashPassword(password);
// Create user
2024-11-13 00:05:01 +05:30
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).json({
error: "DATABASE_ERROR",
code: "register.error.creation_failed"
});
2024-09-23 23:55:41 +05:30
}
2024-09-23 23:55:53 +05:30
// Check JWT secret
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).json({
error: "SERVER_ERROR",
code: "register.error.server_error"
});
2024-09-23 23:55:53 +05:30
}
2024-11-13 00:05:01 +05:30
// Success path
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,
});
2024-11-13 00:05:01 +05:30
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);
2024-11-13 00:05:01 +05:30
} catch (error: any) {
console.log(`Could not register user - ${error}`);
return res.status(500).json({
error: "SERVER_ERROR",
code: "register.error.generic"
});
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.post("/login", async (req, res) => {
try {
const { email, password } = req.body;
2025-02-01 16:25:19 +05:30
if (!email || !password) {
return res.status(400).json({
error: "VALIDATION_ERROR",
code: "login.validation.required_fields"
});
}
if (password.length < 6) {
return res.status(400).json({
error: "VALIDATION_ERROR",
code: "login.validation.password_length"
});
}
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 } });
2025-02-01 16:25:19 +05:30
if (!user) {
return res.status(404).json({
error: "USER_NOT_FOUND",
code: "login.error.user_not_found"
});
}
2024-10-28 21:10:02 +05:30
2024-11-13 00:05:01 +05:30
const match = await comparePassword(password, user.password);
2025-02-01 16:25:19 +05:30
if (!match) {
return res.status(401).json({
error: "INVALID_CREDENTIALS",
code: "login.error.invalid_credentials"
});
}
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) {
2025-02-01 16:25:19 +05:30
console.error(`Login error: ${error.message}`);
res.status(500).json({
error: "SERVER_ERROR",
code: "login.error.server_error"
});
2024-11-13 00:05:01 +05:30
}
});
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) {
return res.status(401).json({
ok: false,
error: "Unauthorized",
code: "unauthorized"
});
2024-11-13 00:05:01 +05:30
}
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({
ok: false,
error: "User not found",
code: "not_found"
});
2024-11-13 00:05:01 +05:30
}
return res.status(200).json({
ok: true,
2024-11-13 00:05:01 +05:30
message: "API key fetched successfully",
api_key: user.api_key || null,
});
2024-10-03 02:28:46 +05:30
} catch (error) {
console.error('API Key fetch error:', error);
return res.status(500).json({
ok: false,
error: "Error fetching API key",
code: "server",
});
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
}
);