Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
2444 lines (2056 loc) · 79.2 KB
/
Copy pathindex.js
File metadata and controls
2444 lines (2056 loc) · 79.2 KB
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
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import mongoose from 'mongoose';
import express from 'express';
import bodyParser from 'body-parser';
import jwt from 'jsonwebtoken';
import path from 'path';
import PDFDocument from 'pdfkit';
import Razorpay from 'razorpay';
import dotenv from 'dotenv';
import nodemailer from 'nodemailer';
import request from 'request';
import geoip from 'geoip-lite';
import axios from 'axios';
import cookieParser from 'cookie-parser';
import chalk from 'chalk';
import crypto from 'crypto';
import { GoogleGenerativeAI } from '@google/generative-ai';
// Importing models
import Coupon from './models/coupon.js';
import Putoken from './models/putcoupon.js';
import GoldInvestment from './models/goldschema.js';
import UserInvestment from './models/userinvestingold.js';
import SensexSchema from './models/sensexschema.js';
import Message from './models/contact.js';
import NiftySchema from './models/niftyschema.js';
import Ipo from './models/Ipo.js';
import MutualFund from './models/mutulfund.js';
import fundst from './models/fundst.js';
import UserProfile from './models/userprofile.js';
import Register from './models/register.js';
import Help from './models/help.js';
import Stock from './models/stock.js';
import userstock from './models/userstocks.js';
// Importing utilities
import createEmailTemplate from './page/fundsmail.js';
// Load environment variables
dotenv.config();
// Constants
const SECRET_KEY = 'xyxxx'; // Replace with your actual secret key
const port = 3000;
const uri = process.env.MONGO_URL;
// Express app setup
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());
// Setting up the view engine
const __dirname = path.resolve();
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
app.use(express.static(path.join(__dirname, 'public')));
// Initialize other logic or routes here
// Connect to MongoDB
mongoose.connect(uri)
.then(() => console.log(chalk.white(`\nConnected to MongoDB successfully!\n`)))
.catch(err => console.error('Failed to connect to MongoDB', err));
// Middleware to verify JWT token
const verifyToken = async (req, res, next) => {
// Skip token verification for the /login route
if (req.path === '/login') {
return next();
}
const token = req.cookies.authToken; // Assuming token is stored in cookies
if (!token) {
return res.redirect('/login');
}
jwt.verify(token, SECRET_KEY, async (err, decoded) => {
if (err) {
return res.redirect('/login');
}
try {
// Fetch the user data from the database
const user = await Register.findById(decoded.id);
if (!user) {
return res.redirect('/login');
}
req.user = user; // Store the user data in the request object
next();
} catch (error) {
console.error(error);
return res.redirect('/login');
}
});
};
// Middleware to restrict access for logged-in users
const restrictAccess = (req, res, next) => {
const token = req.cookies.authToken;
if (token) {
// Check if the token is valid
jwt.verify(token, SECRET_KEY, (err, decoded) => {
if (!err) {
// Redirect to home if the token is valid
return res.redirect('/home');
}
});
}
next(); // Only call next() if there is no valid token
};
// Route to the login page
app.get('/login', restrictAccess, (req, res) => {
console.log("login page accessed");
res.render('login');
});
// Help page route
app.get('/help', verifyToken, async (req, res) => {
try {
// Find queries related to the logged-in user
const userEmail = req.user.email; // Assuming req.user contains the logged-in user's info
const pendingQueries = await Help.find({ email: userEmail, query_resolved: 'No' });
const resolvedQueries = await Help.find({ email: userEmail, query_resolved: 'Yes' });
res.render('help.ejs', {
pendingQueries,
resolvedQueries,
message: null,
user: req.user
});
} catch (error) {
console.error(error);
res.status(500).send('Server Error');
}
});
app.get("/delete",async (req,res)=>{
await Help.deleteMany({});
res.send("deletedd");
})
// Query route
// app.get('/date/:email',async (req,res)=>{
// const x=req.params.email;
// const xt=await Register.findOne({email:x});
// if(!xt){
// res.send("not found")
// }
// res.send(xt);
// console.log(x);
// });
app.post('/submit-query', verifyToken, async (req, res) => {
const { name, email, query } = req.body;
try {
// Create a new query document
const newQuery = new Help({ name, email, query });
// Save the document to the database
await newQuery.save();
console.log('Query saved to the database');
// Render the help page with a success message
res.send(`<html>
<head>
<title>Success</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<style>
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #f8f9fa;
}
.success-message {
background-color: #fff;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
text-align: center;
}
</style>
</head>
<body>
<div class="success-message">
<h2>Your query has been submitted successfully!</h2>
<p>You will be redirected in a moment...</p>
</div>
<script>
setTimeout(function() {
window.location.href = '/help'; // Redirect to the help query page
}, 2000); // 2 seconds delay
</script>
</body>
</html>
`);
// res.render('help', { message: 'Query submitted successfully. We\'ll get back to you on this!', user: req.user });
} catch (error) {
console.error('Error saving query:', error);
// Render the help page with an error message
// r
res.send("there is problem to sending your quer");
}
});
// app.get('/data',async (req,res)=>{
// const x = await Help.find({});
// console.log(x);
// });
// Home route
app.get('/', verifyToken, (req, res) => {
console.log("home page accessed");
res.render('home', { user: req.user });
});
// Home route
app.get('/home', verifyToken, (req, res) => {
res.render('home', { user: req.user }); // Pass the user data to the home page
});
app.get('/profile', verifyToken, async (req, res) => {
try {
const userdata = await UserProfile.findOne({ email: req.user.email });
console.log(userdata);
// Check if userdata exists or profile details are incomplete
if (!userdata ) {
// If user data does not exist or is not verified, ask the user to fill in details
return res.render('profile', { user: req.user, userdata: null });
}
// If user data is available and profile is verified
res.render('profile', { user: req.user, userdata });
} catch (error) {
console.error("Error fetching user profile: ", error);
res.status(500).send("Server Error");
}
});
app.get('/userdata',(req,res)=>{
res.render('userdata',{user:req.user});
})
function generateRandomDematAccountNumber() {
return Math.floor(Math.random() * 10000000000).toString(); // Generates a random 10-digit number
}
function generateRandomDpId() {
return Math.floor(Math.random() * 10000000).toString(); // Generates a random 7-digit number
}
function generateRandomDepositoryParticipant() {
const participants = ['Tradehub Limited', 'Zerodha', 'Upstox', 'ICICI Direct', 'HDFC Securities'];
return participants[Math.floor(Math.random() * participants.length)]; // Randomly selects a participant
}
function generateRandomDepository() {
const depositories = ['CDSL', 'NSDL'];
return depositories[Math.floor(Math.random() * depositories.length)]; // Randomly selects a depository
}
app.post('/submit', async (req, res) => {
console.log(req.body);
try {
// Generate random data
const randomDematAccountNumber = generateRandomDematAccountNumber();
const randomDpId = generateRandomDpId();
const randomDepositoryParticipant = generateRandomDepositoryParticipant();
const randomDepository = generateRandomDepository();
// Create a new user profile with the provided data and generated random data
const userProfile = new UserProfile({
...req.body, // Spread the incoming request body
dematAccountNumber: randomDematAccountNumber,
dpId: randomDpId,
depositoryParticipant: randomDepositoryParticipant,
depository: randomDepository,
});
console.log(userProfile); // Log the userProfile to see the generated data
await userProfile.save(); // Save the user profile to the database
res.status(200).json({ message: 'Your request has been accepted.', success: true });
} catch (error) {
console.error('Error saving user profile:', error);
res.status(500).json({ message: 'There was an error processing your request.', success: false });
}
});
// Handle login POST request
app.get('/update',async (req,res)=>{
await Register.updateOne({email:"nitinraj844126@gmail.com"},{userType:"admin"});
res.send("ok");
})
app.post('/login', restrictAccess, async (req, res) => {
console.log("login request page accessed");
const { email, password } = req.body;
try {
// Find the user by email
const user = await Register.findOne({ email });
// Check if user exists
if (!user) {
return res.render("wrongpassword.ejs", { username: 'Invalid email or password.' });
}
// Check if the account is locked
const currentTime = Date.now();
if (user.lockUntil && currentTime < user.lockUntil) {
const remainingTime = Math.ceil((user.lockUntil - currentTime) / (1000 * 60)); // Remaining time in minutes
return res.render("wrongpassword.ejs", {
username: `Account locked. Try again in ${remainingTime} minutes.`,
});
}
// Validate password
if (password !== user.password) {
user.failedAttempts = (user.failedAttempts || 0) + 1;
// Lock account if failed attempts exceed the threshold (e.g., 3)
if (user.failedAttempts >= 3) {
user.lockUntil = currentTime + 60 * 60 * 1000; // Lock for 1 hour
await user.save();
return res.render("wrongpassword.ejs", {
username: `Too many failed attempts. Your account is locked. Try again in 60 minutes.`,
});
}
// Save the updated failed attempts
await user.save();
return res.render("wrongpassword.ejs", {
username: `Invalid password. You have ${
3 - user.failedAttempts
} attempt(s) left before the account is locked.`,
});
}
// If login is successful, reset failed attempts and lockUntil
user.failedAttempts = 0;
user.lockUntil = null;
await user.save();
// Generate a JWT token
const token = jwt.sign({ id: user._id }, SECRET_KEY, { expiresIn: '1h' });
// Set the token in cookies
res.cookie('authToken', token, { httpOnly: true });
// Get the user's IP address from the request
const ipAddress = req.ip;
// Get location data based on the IP address
const geo = geoip.lookup(ipAddress);
const location = geo ? `${geo.city}, ${geo.country}` : 'Location not found';
// Prepare email notification
const subject = 'Login Notification';
const message = `
<p>Dear ${user.name},</p>
<p>You have successfully logged in to your account.</p>
<p><strong>IP Address:</strong> ${ipAddress}</p>
<p><strong>Location:</strong> ${location}</p>
<p><strong>Operating System:</strong> ${req.headers['user-agent']}</p>
<p>Thank you for using our service!</p>
<p>Best Regards,<br>Your Support Team</p>
`;
// Function to send email
async function sendEmailNotification(toEmail, subject, message) {
const transporter = nodemailer.createTransport({
service: 'gmail', // or any other email service
auth: {
user: process.env.EMAIL_USER,
pass: process.env.EMAIL_PASS,
},
});
const mailOptions = {
from: process.env.EMAIL_USER,
to: toEmail,
subject: subject,
html: message,
};
// Send email
await transporter.sendMail(mailOptions);
}
// Send email notification
await sendEmailNotification(user.email, subject, message);
// Redirect to home page with user data on successful login
res.redirect('/home');
} catch (error) {
console.error(error);
res.render('login', { error: 'Something went wrong. Please try again!' });
}
});
// logout
app.get('/logout', verifyToken ,(req,res)=>{
res.clearCookie('authToken');
res.redirect('/login');
console.log("logout successfully");
});
// Route to the register page
app.get('/register', restrictAccess, (req, res) => {
console.log("register request page accessed");
res.render('register', { error: null });
});
// Handle register POST request
app.post('/register', restrictAccess, async (req, res) => {
const { name, email, phoneNumber, dob, password, confirmPassword } = req.body;
if (!name || !email || !phoneNumber || !dob || !password || !confirmPassword) {
return res.render('register', { error: 'All fields are required!' });
}
if (password !== confirmPassword) {
return res.render('register', { error: 'Passwords do not match!' });
}
if (password.length < 6) {
return res.render('register', { error: 'Password must be at least 6 characters long!' });
}
try {
const existingUser = await Register.findOne({
$or: [{ email }, { phoneNumber }]
});
if (existingUser) {
return res.render('register', { error: 'Email or Phone Number already in use!' });
}
const newUser = new Register({ name, email, phoneNumber, dob, password ,funds:0});
await newUser.save();
res.render('registersuccess');
} catch (error) {
console.error(error);
res.render('register', { error: 'Something went wrong. Please try again!' });
}
});
// app.post('/updateji', async (req, res) => {
// try {
// // Update all users to set funds to 0
// const result = await Register.updateMany({}, { $set: { funds: 0 } });
// // Send back a response indicating how many documents were modified
// res.send(`${result.modifiedCount} users' funds have been set to 0 successfully.`);
// } catch (error) {
// // Send an error response if something goes wrong
// console.error('Error updating users:', error);
// res.status(500).send('Server error while updating users.');
// }
// });
// Route to verify email
// otp verification system
let transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: process.env.EMAIL_USER, // Email address stored in .env
pass: process.env.EMAIL_PASS // Email password stored in .env
}
});
// updating route:
// Route to verify OTP and update password
app.post('/check-email', async (req, res) => {
console.log("check accessed");
const { email } = req.body;
try {
const user = await Register.findOne({ email: email });
if (!user) {
return res.status(400).json({ error: 'Email not found!' });
}
const otp = Math.floor(100000 + Math.random() * 900000).toString();
const otpExpiry = Date.now() + 5 * 60 * 1000;
otpMap.set(email, { otp, otpExpiry });
const mailOptions = {
from: process.env.EMAIL_USER,
to: email,
subject: 'Your OTP for Password Reset',
text: `Your OTP for password reset is: ${otp}. This OTP is valid for 5 minutes.`,
html: `<p>Your OTP for password reset is: <strong>${otp}</strong>.</p><p>This OTP is valid for 5 minutes.</p>`
};
await transporter.sendMail(mailOptions);
res.status(200).json({ message: 'OTP sent to your email!' });
} catch (error) {
console.error(error);
res.status(500).json({ error: 'Something went wrong. Please try again!' });
}
});
app.post('/verify-otp', async (req, res) => {
console.log("verify email accessed");
const { email, otp, newPassword } = req.body;
console.log(req.body);
const storedOtpInfo = otpMap.get(email);
if (!storedOtpInfo || storedOtpInfo.otp !== otp || Date.now() > storedOtpInfo.otpExpiry) {
return res.status(400).json({ error: 'Invalid or expired OTP!' });
}
try {
await Register.updateOne({ email: email }, { password: newPassword });
console.log("Password updated successfully.");
otpMap.delete(email);
res.status(200).json({ message: 'Password updated successfully!' });
} catch (error) {
console.error(error);
res.status(500).json({ error: 'Something went wrong. Please try again!' });
}
});
// verify account section
app.get('/verify_account', verifyToken, async (req, res) => {
try {
// Check if the user is an admin
if (req.user.userType !== 'admin') {
return res.status(403).send('Access denied: You are not authorized to view this page.');
}
// Fetch all user profiles from the database
const userProfiles = await UserProfile.find();
// Separate user profiles into unverified, verified, and rejected
const unverifiedProfiles = userProfiles.filter(profile => profile.isVerified === 'false');
const verifiedProfiles = userProfiles.filter(profile => profile.isVerified === 'true');
const rejectedProfiles = userProfiles.filter(profile => profile.isVerified === 'rejected');
// Render the verify_account.ejs view with the userProfiles data
res.render('verify_account.ejs', { user: req.user, unverifiedProfiles, verifiedProfiles, rejectedProfiles });
} catch (error) {
console.error(error);
res.status(500).send('Server error');
}
});
app.post('/reject/:id', async (req, res) => {
try {
const { reason } = req.body; // Get the reason from the request body
const updatedProfile = await UserProfile.findByIdAndUpdate(req.params.id, {
isVerified: 'rejected', // Update the verification status
reason: reason, // Store the rejection reason
verified_by: null, // Clear verified_by since the user is rejected
}, { new: true });
if (!updatedProfile) {
return res.status(404).send('User not found');
}
res.status(200).send('User rejected successfully');
} catch (error) {
console.error(error);
res.status(500).send('Server error');
}
});
// app.get('/verifyed',async (req,res)=>{
// await UserProfile.updateMany({isVerified:'true'},{isVerified:'false'});
// res.send("changed");
// console.log("done");
// });
app.get('/contact',(re,res)=>{
console.log("contact page accessed");
res.render('contact.ejs');
})
// Handle contact POST request
app.post("/contact", async (req, res) => {
const { firstName, lastName, email, mobileNumber, message } = req.body;
if (!firstName || !lastName || !email || !mobileNumber || !message) {
return res.render("contact", { error: "All fields are required!" });
}
try {
const newMessage = new Message({
firstName,
lastName,
email,
mobileNumber,
message,
});
await newMessage.save();
res.redirect("/home"); // Redirect user after saving
} catch (error) {
console.error(error);
res.render("contact", {
error: "Failed to send your message. Please try again.",
});
}
});
// app.get("/updatedata",async(req,res)=>{
// const user=await UserProfile.findOne({email:"nitinraj844126@gmail.com"},{isVerified:"true"});
// console.log(user);
// res.send("update yopur data");
// })
app.post('/verify/:id', async (req, res) => {
try {
const updatedProfile = await UserProfile.findByIdAndUpdate(req.params.id, {
isVerified: true, // Use boolean true instead of string 'true'
verified_by: req.body.verifiedBy,
}, { new: true });
if (!updatedProfile) {
return res.status(404).send('User not found');
}
// Send verification email
await sendVerificationEmail(updatedProfile.email, updatedProfile.name);
res.status(200).send('User verified successfully');
} catch (error) {
console.error(error);
res.status(500).send('Server error');
}
});
// Function to send verification email
async function sendVerificationEmail(userEmail, userName) {
// Create a Nodemailer transporter
let transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: process.env.EMAIL_USER, // Your email address stored in .env
pass: process.env.EMAIL_PASS, // Your email password stored in .env
},
});
// Email options
const mailOptions = {
from: process.env.EMAIL_USER, // Sender email
to: userEmail, // Recipient email (user's email)
subject: 'Your Profile has been Verified',
html: `
<div style="font-family: Arial, sans-serif; background-color: #f4f4f4; padding: 20px; border-radius: 8px; max-width: 600px; margin: auto;">
<h2 style="color: #2c3e50;">Hello ${userName},</h2>
<p style="font-size: 16px;">We are pleased to inform you that your profile has been successfully verified.</p>
<p style="font-size: 16px;">Thank you for your patience and for being a valued member of our community!</p>
<div style="background-color: #3498db; padding: 10px; border-radius: 5px; text-align: center;">
<a href="https://yourwebsite.com" style="color: white; text-decoration: none; font-weight: bold;">Visit Your Profile</a>
</div>
<p style="font-size: 16px; margin-top: 20px;">Best Regards,<br>Your Support Team</p>
</div>
`
};
try {
// Send the email
await transporter.sendMail(mailOptions);
console.log('Verification email sent successfully');
} catch (error) {
console.error('Error sending verification email:', error);
}
}
// user profile
app.get('/user_profile/:id', async (req, res) => {
try {
const userId = req.params.id;
const user = await UserProfile.findById(userId); // Adjust according to your database query method
if (!user) {
return res.status(404).json({ error: 'User not found' });
}
// Prepare user data to send
const userData = {
name: user.name,
email: user.email,
dematAccountNumber: user.dematAccountNumber,
dpId: user.dpId,
depositoryParticipant: user.depositoryParticipant,
depository: user.depository,
aadharNumber: user.aadharNumber,
pancard: user.pancard,
phoneNumber: user.phoneNumber,
bankName: user.bankName,
accountNumber: user.accountNumber,
branch: user.branch,
nominees: user.nominees,
kycCopyUrl: user.kycCopyUrl || 'N/A'
};
res.json(userData);
} catch (error) {
console.error('Error fetching user details:', error);
res.status(500).json({ error: 'Internal server error' });
}
});
// resolving query
app.get('/help-query', async (req, res) => {
try {
const pendingQueries = await Help.find({ query_resolved: 'No' });
const resolvedQueries = await Help.find({ query_resolved: 'Yes' });
res.render('help_query', { pendingQueries, resolvedQueries });
} catch (error) {
console.error(error);
res.status(500).send('Server Error');
}
});
// user query
// app.get('/updatedata',(req,res)=>{
// UserProfile.updateMany({email : "nitinraj844126@gmail.com"},{isVerified:"true"});
// res.send("updated");
// })
// Route to resolve a query
app.post('/help-query/resolve/:id', verifyToken, async (req, res) => {
const useremail = req.user.email; // Get the user's email from the token
const { resolved_message } = req.body; // Get the resolved message from the request body
try {
// Update the query in the database
const updatedQuery = await Help.findByIdAndUpdate(req.params.id, {
query_resolved: 'Yes',
resolved_message,
resolved_time: Date.now(),
}, { new: true }); // Return the updated document
// Send an email notification
await sendResolutionEmail(useremail, updatedQuery);
// Send a success response
res.json({ success: true, resolvedMessage: updatedQuery.resolved_message });
} catch (error) {
console.error(error);
res.status(500).json({ success: false, error: 'Server Error' });
}
});
// Function to send the resolution email
async function sendResolutionEmail(userEmail, query) {
// Create a Nodemailer transporter
let transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: process.env.EMAIL_USER, // Email address stored in .env
pass: process.env.EMAIL_PASS, // Email password stored in .env
},
});
// Email options
const mailOptions = {
from: process.env.EMAIL_USER, // Sender email
to: userEmail, // Recipient email (user's email)
subject: 'Your Query has been Resolved',
html: `
<div style="font-family: Arial, sans-serif; padding: 20px; border: 1px solid #ddd; border-radius: 5px; background-color: #f9f9f9;">
<h2 style="color: #333;">Dear User,</h2>
<p style="font-size: 16px;">Your query has been resolved:</p>
<ul style="list-style-type: none; padding: 0;">
<li style="margin: 10px 0;"><strong>Query:</strong> ${query.query}</li>
<li style="margin: 10px 0;"><strong>Resolved Message:</strong> ${query.resolved_message}</li>
<li style="margin: 10px 0;"><strong>Resolved Time:</strong> ${new Date(query.resolved_time).toLocaleString()}</li>
</ul>
<p style="font-size: 16px;">Thank you for reaching out!</p>
<p style="font-size: 16px;">Best Regards,<br>Support Team</p>
</div>
`
};
try {
// Send the email
await transporter.sendMail(mailOptions);
console.log('Email sent successfully');
} catch (error) {
console.error('Error sending email:', error);
throw new Error('Email not sent'); // Handle email error
}
}
// Route to submit a new help query
// discover page all stock show
app.get('/stocks', verifyToken,async (req, res) => {
try {
const allStocks = await Stock.find({});
const topStocks = allStocks.slice(0, 3); // Get top 3 stocks
res.render('stocks', { user:req.user,topStocks, allStocks });
} catch (error) {
console.error(error);
res.status(500).send('Error retrieving stocks');
}
});
// funds sectuon
app.get('/funds', verifyToken, async (req, res) => {
const userdata = await UserProfile.findOne({ email: req.user.email });
console.log(userdata);
try {
const userId = req.user.id; // Assuming user is logged in and ID is available
const user = await Register.findById(userId);
const alltransaction=await fundst.find({userId:req.user._id});
if (user) {
// Render the 'funds.ejs' template and pass user data
res.render('funds', { user,alltransaction,userdata });
} else {
res.status(404).json({ message: 'User not found' });
}
} catch (err) {
res.status(500).json({ message: 'Server error' });
}
});
const sendEmailNotification = (userEmail, subject, message) => {
const mailOptions = {
from: process.env.EMAIL_USER,
to: userEmail,
subject: subject,
html: message, // Use HTML to format the email nicely
};
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
console.error('Error sending email:', error);
} else {
console.log('Email sent:', info.response);
}
});
};
const razorpay = new Razorpay({
key_id: process.env.RazorPay_API,
key_secret: process.env.Rozorpay_secret,
});
app.post('/funds/add', verifyToken, async (req, res) => {
const { amount } = req.body;
try {
const user = await Register.findById(req.user.id);
if (!user) return res.status(404).send('User not found');
const options = {
amount: amount * 100, // Razorpay expects amount in paise
currency: 'INR',
receipt: `receipt_${Date.now()}`,
};
const order = await razorpay.orders.create(options);
res.json({ orderId: order.id });
} catch (error) {
console.error(error);
res.status(500).send({ message: 'Error creating Razorpay order' });
}
});
app.post('/funds/verify', verifyToken, async (req, res) => {
const { paymentId, orderId, signature, amount } = req.body;
console.log(req.body);
try {
// Update user's funds directly
const user = await Register.findById(req.user.id);
if (!user) return res.status(404).send('User not found');
// Add funds to the user's account
user.funds += parseFloat(amount);
await user.save();
// Log transaction
const subject = 'Funds Added Successfully';
const message = createEmailTemplate(user.name, subject, amount, user.funds, 'added');
sendEmailNotification(user.email, subject, message);
res.json({ message: 'Funds added successfully!' });
} catch (error) {
console.error(error);
res.status(500).json({ message: 'Error processing payment' });
}
});
// app.post('/funds/add', verifyToken, async (req, res) => {
// const { amount } = req.body;
// try {
// const user = await Register.findById(req.user.id);
// if (!user) return res.status(404).send('User not found');
// user.funds += amount;
// await user.save();
// // Prepare email notification
// const subject = 'Funds Added Successfully';
// const message = createEmailTemplate(user.name, subject, amount, user.funds, 'added');
// sendEmailNotification(user.email, subject, message);
// res.send({ message: 'Funds added successfully!' });
// } catch (error) {
// res.status(500).send({ message: 'Server error' });
// }
// });
app.post('/funds/verify', verifyToken, async (req, res) => {
const { payment_id, order_id, signature } = req.body;
const generated_signature = crypto
.createHmac('sha256', 'rj1C0dsKibu56PiiOhUqdGFp') // Your Razorpay Key Secret
.update(order_id + '|' + payment_id)
.digest('hex');
if (generated_signature === signature) {
try {
const user = await Register.findById(req.user.id);
if (!user) return res.status(404).send('User not found');
const paymentDetails = await razorpay.payments.fetch(payment_id);
const amount = paymentDetails.amount / 100; // Convert from paise
user.funds += amount;
await user.save();
// Send success response
res.send({ message: 'Funds added successfully!' });
} catch (error) {
console.error(error);
res.status(500).send({ message: 'Server error' });
}
} else {
res.status(400).send({ message: 'Payment verification failed.' });
}
});
// Withdraw funds
app.post('/funds/withdraw', verifyToken, async (req, res) => {
const { amount } = req.body;
try {
const user = await Register.findById(req.user.id);
if (!user) return res.status(404).send('User not found');
if (user.funds < amount) {
return res.status(400).send({ message: 'Insufficient funds' });
}
user.funds -= amount;
await user.save();
// Prepare email notification
const subject = 'Funds Withdrawn Successfully';
const message = createEmailTemplate(user.name, subject, amount, user.funds, 'withdrawn');
sendEmailNotification(user.email, subject, message);
res.send({ message: 'Funds withdrawn successfully!' });
} catch (error) {
res.status(500).send({ message: 'Server error' });
}
});
app.post('/funds/withdraw', verifyToken, async (req, res) => {
const { amount } = req.body;
try {
const user = await Register.findById(req.user.id);
if (!user) return res.status(404).send('User not found');
if (user.funds < amount) {
return res.status(400).send({ message: 'Insufficient funds' });
}
user.funds -= amount;
await user.save();
// Prepare email notification
const subject = 'Funds Withdrawn Successfully';