import express from 'express';
import { ZerodhaClient } from './zerodha-client.js';
import dotenv from 'dotenv';
dotenv.config();
const app = express();
const PORT = 3000;
const zerodhaClient = new ZerodhaClient(
process.env.ZERODHA_API_KEY,
process.env.ZERODHA_API_SECRET,
process.env.ZERODHA_REDIRECT_URI
);
app.get('/', (req, res) => {
const loginURL = zerodhaClient.getLoginURL();
res.send(`
<html>
<head><title>Zerodha Authentication</title></head>
<body>
<h1>Zerodha Trading Bot Authentication</h1>
<p>Click the link below to authenticate with Zerodha:</p>
<a href="${loginURL}" target="_blank">Login to Zerodha</a>
<br><br>
<p>After successful authentication, you'll be redirected back here with a request token.</p>
<p>The request token will be displayed on this page.</p>
</body>
</html>
`);
});
app.get('/callback', async (req, res) => {
const { action, status, request_token } = req.query;
if (action === 'login' && status === 'success' && request_token) {
try {
const tokens = await zerodhaClient.getAccessToken(request_token);
res.send(`
<html>
<head><title>Authentication Success</title></head>
<body>
<h1>Authentication Successful!</h1>
<p>Your access token has been generated successfully.</p>
<h3>Access Token:</h3>
<pre>${tokens.accessToken}</pre>
<h3>Refresh Token:</h3>
<pre>${tokens.refreshToken}</pre>
<p>You can now use this access token with your MCP server.</p>
<p>Add it to your .env file as ZERODHA_ACCESS_TOKEN=${tokens.accessToken}</p>
</body>
</html>
`);
} catch (error) {
res.send(`
<html>
<head><title>Authentication Failed</title></head>
<body>
<h1>Authentication Failed</h1>
<p>Error: ${error.message}</p>
<a href="/">Try Again</a>
</body>
</html>
`);
}
} else {
res.send(`
<html>
<head><title>Authentication Failed</title></head>
<body>
<h1>Authentication Failed</h1>
<p>Invalid response from Zerodha.</p>
<a href="/">Try Again</a>
</body>
</html>
`);
}
});
app.listen(PORT, () => {
console.log(`Authentication server running at http://localhost:${PORT}`);
console.log(`Zerodha login URL: ${zerodhaClient.getLoginURL()}`);
});