Spaces:
Sleeping
Sleeping
File size: 5,546 Bytes
4bf0aa2 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 | import { Request, Response } from 'express';
import { PlatformConnection } from '../../models/PlatformConnection.model';
import { OAuthSimulatorService } from '../../services/oauth-simulator.service';
/**
* Initiate OAuth connection for a platform
*/
export const initiateConnection = async (req: Request, res: Response) => {
try {
const { platform } = req.params;
const userId = req.body.userId || req.query.userId; // Firebase UID
if (!userId) {
return res.status(400).json({ error: 'User ID is required' });
}
if (!OAuthSimulatorService.isValidPlatform(platform)) {
return res.status(400).json({ error: 'Invalid platform' });
}
// Generate OAuth URL
const { url, state } = OAuthSimulatorService.generateAuthUrl(platform, userId);
// Store state in session or temporary storage (for production, use Redis)
// For now, we'll include it in the URL and validate on callback
res.json({
authUrl: url,
state,
platform
});
} catch (error: any) {
console.error('Initiate connection error:', error);
res.status(500).json({ error: error.message || 'Failed to initiate connection' });
}
};
/**
* Handle OAuth callback
*/
export const handleCallback = async (req: Request, res: Response) => {
try {
const { code, state, platform, user_id, email } = req.query;
if (!code || !state || !platform || !user_id) {
return res.status(400).json({ error: 'Missing required parameters' });
}
// In production, validate state token against stored value
// For simulation, we'll proceed
// Generate tokens
const tokens = OAuthSimulatorService.generateTokens();
const encryptedTokens = OAuthSimulatorService.encryptTokens(tokens);
// Simulate fetching user info from platform
const userInfo = await OAuthSimulatorService.simulateUserInfo(
platform as string,
email as string || `user@${platform}.com`
);
// Check if connection already exists
const existingConnection = await PlatformConnection.findOne({
userId: user_id as string,
platform: platform as string
});
if (existingConnection) {
// Update existing connection
existingConnection.accessToken = encryptedTokens.accessToken;
existingConnection.refreshToken = encryptedTokens.refreshToken;
existingConnection.expiresAt = tokens.expiresAt;
existingConnection.lastUsed = new Date();
existingConnection.isActive = true;
existingConnection.email = userInfo.email;
existingConnection.displayName = userInfo.displayName;
await existingConnection.save();
} else {
// Create new connection
await PlatformConnection.create({
userId: user_id,
platform,
platformUserId: userInfo.platformUserId,
accessToken: encryptedTokens.accessToken,
refreshToken: encryptedTokens.refreshToken,
email: userInfo.email,
displayName: userInfo.displayName,
expiresAt: tokens.expiresAt,
metadata: {
accountType: userInfo.accountType
}
});
}
// Redirect back to frontend
const frontendUrl = process.env.FRONTEND_URL || 'http://localhost:3001';
res.redirect(`${frontendUrl}/profile?connected=${platform}&success=true`);
} catch (error: any) {
console.error('OAuth callback error:', error);
const frontendUrl = process.env.FRONTEND_URL || 'http://localhost:3001';
res.redirect(`${frontendUrl}/profile?error=${encodeURIComponent(error.message)}`);
}
};
/**
* Get user's platform connections
*/
export const getConnections = async (req: Request, res: Response) => {
try {
const { userId } = req.query;
if (!userId) {
return res.status(400).json({ error: 'User ID is required' });
}
const connections = await PlatformConnection.find({
userId: userId as string,
isActive: true
}).select('-accessToken -refreshToken'); // Don't send tokens to frontend
res.json({ connections });
} catch (error: any) {
console.error('Get connections error:', error);
res.status(500).json({ error: error.message || 'Failed to fetch connections' });
}
};
/**
* Disconnect a platform
*/
export const disconnectPlatform = async (req: Request, res: Response) => {
try {
const { platform } = req.params;
const { userId } = req.body;
if (!userId) {
return res.status(400).json({ error: 'User ID is required' });
}
const connection = await PlatformConnection.findOne({
userId,
platform
});
if (!connection) {
return res.status(404).json({ error: 'Connection not found' });
}
// Soft delete - mark as inactive
connection.isActive = false;
await connection.save();
res.json({ message: 'Platform disconnected successfully', platform });
} catch (error: any) {
console.error('Disconnect platform error:', error);
res.status(500).json({ error: error.message || 'Failed to disconnect platform' });
}
};
|