// server.js
const express = require('express');
const { SmartAPI } = require('smartapi-javascript');
const WebSocket = require('ws');
const path = require('path');
require('dotenv').config();
const app = express();
const port = 3000;
// Middleware
app.use(express.json());
app.use(express.static('public'));
// Initialize SmartAPI
let smart_api;
try {
smart_api = new SmartAPI({
api_key: process.env.SMART_API_KEY, // Your API Key
clientId: process.env.CLIENT_ID, // Your Client ID
clientSecret: process.env.CLIENT_SECRET // Your Client Secret
});
console.log('SmartAPI initialized successfully');
} catch (error) {
console.error('Error initializing SmartAPI:', error);
process.exit(1);
}
// Store session data
let session = null;
// Session check middleware
const checkSession = (req, res, next) => {
if (!session || !session.feedToken) {
return res.status(401).json({ success: false, message: 'Not logged in or session expired' });
}
next();
};
//login code test
app.post('/api/login', async (req, res) => {
try {
console.log('Login attempt started...');
const { client_code, password, totp } = req.body;
if (!client_code || !password || !totp) {
throw new Error('Missing required login parameters');
}
console.log('Generating session...');
const data = await smart_api.generateSession(client_code, password, totp);
console.log('Full API Response:', JSON.stringify(data, null, 2));
if (!data || !data.jwtToken || !data.feedToken) {
throw new Error('Session generation failed, missing tokens.');
}
console.log('Session generated successfully:', {
hasAccessToken: !!data.accessToken,
hasRefreshToken: !!data.refreshToken,
hasJwtToken: !!data.jwtToken,
hasFeedToken: !!data.feedToken
});
session = data;
smart_api.jwtToken = data.jwtToken;
smart_api.feedToken = data.feedToken;
res.json({
success: true,
message: 'Login successful',
sessionInfo: {
hasAccessToken: !!data.accessToken,
hasJwtToken: !!data.jwtToken,
hasFeedToken: !!data.feedToken
}
});
} catch (error) {
console.error('Login error details:', error);
res.status(500).json({
success: false,
message: error.message || 'Login failed',
errorDetails: error.toString()
});
}
});
clientcode:"K624646"