-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
275 lines (236 loc) · 8.72 KB
/
Copy pathserver.ts
File metadata and controls
275 lines (236 loc) · 8.72 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
import express from "express";
import { createServer as createViteServer } from "vite";
import nodemailer from 'nodemailer';
import 'dotenv/config';
import { createClient } from '@supabase/supabase-js';
let supabaseInstance: any = null;
let supabaseAdminInstance: any = null;
function getSupabase() {
if (!supabaseInstance) {
const supabaseUrl = process.env.VITE_SUPABASE_URL;
const supabaseAnonKey = process.env.VITE_SUPABASE_ANON_KEY;
if (!supabaseUrl || !supabaseAnonKey) {
throw new Error("Supabase URL and Anon Key are required environment variables");
}
supabaseInstance = createClient(supabaseUrl, supabaseAnonKey);
}
return supabaseInstance;
}
function getSupabaseAdmin() {
if (!supabaseAdminInstance) {
const supabaseUrl = process.env.VITE_SUPABASE_URL;
const supabaseServiceRoleKey = process.env.SUPABASE_SERVICE_ROLE_KEY;
if (!supabaseUrl || !supabaseServiceRoleKey) {
throw new Error("Supabase URL and Service Role Key are required environment variables");
}
supabaseAdminInstance = createClient(supabaseUrl, supabaseServiceRoleKey, {
auth: {
autoRefreshToken: false,
persistSession: false
}
});
}
return supabaseAdminInstance;
}
let transporter: nodemailer.Transporter | null = null;
function getTransporter() {
const EMAIL_USER = process.env.EMAIL_USER;
const EMAIL_PASS = process.env.EMAIL_PASS;
const SMTP_HOST = process.env.SMTP_HOST || 'smtp.gmail.com';
const SMTP_PORT = parseInt(process.env.SMTP_PORT || '465');
const SMTP_SECURE = process.env.SMTP_SECURE !== 'false'; // Default to true (SSL)
if (!EMAIL_USER || !EMAIL_PASS) {
console.warn("[SMTP Warning] EMAIL_USER or EMAIL_PASS is missing. Email features will not work.");
throw new Error("Email credentials are not configured (EMAIL_USER/EMAIL_PASS)");
}
if (!transporter) {
try {
// If service is provided, use it (e.g. 'gmail'), otherwise use host/port
const config: any = {
auth: {
user: EMAIL_USER,
pass: EMAIL_PASS,
},
};
if (process.env.SMTP_SERVICE) {
config.service = process.env.SMTP_SERVICE;
} else {
config.host = SMTP_HOST;
config.port = SMTP_PORT;
config.secure = SMTP_SECURE;
}
transporter = nodemailer.createTransport(config);
} catch (err: any) {
console.error("[SMTP Error] Failed to create transporter:", err.message);
throw err;
}
}
return { transporter, EMAIL_USER };
}
async function startServer() {
const app = express();
const PORT = 3000;
app.use(express.json());
// Log SMTP status on startup
console.log(`[SMTP Startup] EMAIL_USER: ${process.env.EMAIL_USER ? 'Present' : 'Missing'}`);
console.log(`[SMTP Startup] EMAIL_PASS: ${process.env.EMAIL_PASS ? 'Present' : 'Missing'}`);
console.log(`[SMTP Startup] SMTP_SERVICE: ${process.env.SMTP_SERVICE || 'Not set'}`);
// Debug endpoint to verify server is responding
app.get("/api/debug-server", (req, res) => {
res.json({
message: "Server is alive and handling API routes",
env: {
EMAIL_USER: !!process.env.EMAIL_USER,
EMAIL_PASS: !!process.env.EMAIL_PASS,
SMTP_SERVICE: process.env.SMTP_SERVICE || "none"
}
});
});
// Health check endpoint
app.get("/api/health", async (req, res) => {
let smtpVerified = false;
let smtpError = null;
try {
const { transporter } = getTransporter();
await transporter.verify();
smtpVerified = true;
} catch (err: any) {
smtpError = err.message;
}
res.json({
status: "ok",
smtp: {
user: process.env.EMAIL_USER ? 'Configured' : 'Missing',
pass: process.env.EMAIL_PASS ? 'Configured' : 'Missing',
verified: smtpVerified,
error: smtpError
},
environment: process.env.NODE_ENV || 'development'
});
});
// Test route for email
app.get("/api/test-email", async (req, res) => {
const testTo = req.query.to as string;
if (!testTo) return res.status(400).send("Provide 'to' query param");
try {
const { transporter, EMAIL_USER } = getTransporter();
const mailOptions = {
from: `"ESEC Test" <${EMAIL_USER}>`,
to: testTo,
subject: "Test Email from ESEC Portal",
html: "<h1>It works!</h1><p>This is a test email to verify the SMTP configuration.</p>",
};
const info = await transporter.sendMail(mailOptions);
res.json({ success: true, info });
} catch (err: any) {
console.error("[SMTP Test Error]", err);
res.status(500).json({ success: false, error: err.message });
}
});
// Verify SMTP connection
app.get("/api/verify-smtp", async (req, res) => {
try {
const { transporter } = getTransporter();
await transporter.verify();
res.json({ success: true, message: "SMTP connection verified successfully" });
} catch (err: any) {
console.error("[SMTP Verify Error]", err);
res.status(500).json({ success: false, error: err.message });
}
});
// API routes
app.post('/api/send-email', async (req, res) => {
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return res.status(401).json({ success: false, error: 'Unauthorized' });
}
const token = authHeader.split(' ')[1];
const { data: { user }, error: authError } = await getSupabase().auth.getUser(token);
if (authError || !user) {
return res.status(401).json({ success: false, error: 'Invalid session' });
}
const { to, subject, message } = req.body;
if (!to || !subject || !message) {
return res.status(400).json({ success: false, error: "Missing required fields (to, subject, message)" });
}
try {
const { transporter, EMAIL_USER } = getTransporter();
console.log(`[SMTP] Attempting to send email to: ${to}`);
console.log(`[SMTP] Subject: ${subject}`);
const mailOptions = {
from: `"ESEC Student On-Duty Management System" <${EMAIL_USER}>`,
to: to,
subject: subject,
html: message,
};
const info = await transporter.sendMail(mailOptions);
console.log("[SMTP] Email sent successfully!");
console.log("[SMTP] Message ID:", info.messageId);
console.log("[SMTP] Response:", info.response);
res.json({ success: true, data: info });
} catch (err: any) {
console.error("[SMTP Error]", err);
res.status(500).json({ success: false, error: err.message });
}
});
app.post('/api/verify-admin', (req, res) => {
const { password } = req.body;
const ADMIN_PASSWORD = process.env.VITE_ADMIN_PASSWORD || 'Adminesec@123';
if (password === ADMIN_PASSWORD) {
res.json({ success: true });
} else {
res.json({ success: false, error: 'Unauthorized' });
}
});
app.post('/api/delete-user', async (req, res) => {
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return res.status(401).json({ success: false, error: 'Unauthorized' });
}
const token = authHeader.split(' ')[1];
// 1. Verify user session
const { data: { user }, error: authError } = await getSupabase().auth.getUser(token);
if (authError || !user) {
return res.status(401).json({ success: false, error: 'Invalid session' });
}
// 2. Verify user is admin in profiles table
const { data: profile, error: profileError } = await getSupabase()
.from('profiles')
.select('role')
.eq('id', user.id)
.single();
if (profileError || profile?.role !== 'admin') {
return res.status(403).json({ success: false, error: 'Admin privileges required' });
}
const { userId } = req.body;
if (!userId) {
return res.status(400).json({ success: false, error: 'User ID is required' });
}
try {
// 3. Delete from auth.users using admin SDK
const { error: deleteError } = await getSupabaseAdmin().auth.admin.deleteUser(userId);
if (deleteError) throw deleteError;
res.json({ success: true, message: 'User deleted from auth successfully' });
} catch (err: any) {
console.error("[Delete User Error]", err);
res.status(500).json({ success: false, error: err.message });
}
});
// Vite middleware for development
if (process.env.NODE_ENV !== "production") {
const vite = await createViteServer({
server: { middlewareMode: true },
appType: "spa",
});
app.use(vite.middlewares);
} else {
app.use(express.static("dist"));
app.get("*all", (req, res) => {
res.sendFile("dist/index.html", { root: "." });
});
}
app.listen(PORT, "0.0.0.0", () => {
console.log(`Server running on http://localhost:${PORT}`);
});
}
startServer();