File size: 7,052 Bytes
1d3aceb
 
 
 
 
 
 
 
 
0ba1efd
 
 
1d3aceb
 
 
 
0ba1efd
1d3aceb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0ba1efd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1d3aceb
0ba1efd
 
 
 
 
1d3aceb
 
0ba1efd
 
 
 
 
 
 
1d3aceb
0ba1efd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1d3aceb
0ba1efd
 
 
 
 
 
 
1d3aceb
 
 
 
 
 
0ba1efd
1d3aceb
0ba1efd
 
1d3aceb
0ba1efd
 
 
 
 
 
 
 
 
 
 
 
 
1d3aceb
0ba1efd
 
 
 
 
 
 
 
 
 
 
 
 
1d3aceb
0ba1efd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1d3aceb
 
 
 
 
 
0ba1efd
 
 
 
 
 
 
 
 
 
 
 
1d3aceb
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
import User from '../models/User.js';
import jwt from 'jsonwebtoken';
import axios from 'axios';
import ActivityLog from '../models/ActivityLog.js';

const ADMIN_EMAIL = 'nerdyjinnyas@gmail.com';

// Generate JWT
const generateToken = (id) => {
  return jwt.sign({ id }, process.env.JWT_SECRET, {
    expiresIn: process.env.JWT_EXPIRE,
  });
};

// Helper to build fancy HTML email
const buildLoginEmail = (code) => {
  return `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Your Login Code</title>
</head>
<body style="margin:0;padding:0;background-color:#0f172a;font-family:'Segoe UI',Arial,sans-serif;">
  <table width="100%" cellpadding="0" cellspacing="0" style="background:#0f172a;padding:40px 20px;">
    <tr>
      <td align="center">
        <table width="560" cellpadding="0" cellspacing="0" style="background:#1e293b;border-radius:16px;overflow:hidden;border:1px solid #334155;">
          <!-- Header -->
          <tr>
            <td style="background:linear-gradient(135deg,#065f46,#10b981);padding:36px 40px;text-align:center;">
              <h1 style="margin:0;color:#ffffff;font-size:28px;font-weight:800;letter-spacing:-0.5px;">⚡ The Tenderizer</h1>
              <p style="margin:8px 0 0;color:#a7f3d0;font-size:14px;">AI-Powered Tender & Proposal Platform</p>
            </td>
          </tr>
          <!-- Body -->
          <tr>
            <td style="padding:40px 40px 30px;">
              <h2 style="margin:0 0 16px;color:#f1f5f9;font-size:20px;font-weight:600;">Your Login Code</h2>
              <p style="margin:0 0 28px;color:#94a3b8;font-size:15px;line-height:1.6;">
                Use the code below to sign in to your account. This code expires in <strong style="color:#e2e8f0;">10 minutes</strong>.
              </p>
              <!-- Code Box -->
              <div style="background:#0f172a;border:2px solid #10b981;border-radius:12px;padding:28px;text-align:center;margin-bottom:28px;">
                <span style="font-size:48px;font-weight:900;letter-spacing:12px;color:#10b981;font-family:'Courier New',monospace;">${code}</span>
              </div>
              <p style="margin:0 0 8px;color:#64748b;font-size:13px;line-height:1.6;">
                🔒 If you did not request this code, please ignore this email. Your account remains secure.
              </p>
              <p style="margin:0;color:#64748b;font-size:13px;line-height:1.6;">
                Do not share this code with anyone, including The Tenderizer support staff.
              </p>
            </td>
          </tr>
          <!-- Footer -->
          <tr>
            <td style="padding:20px 40px 30px;border-top:1px solid #334155;text-align:center;">
              <p style="margin:0;color:#475569;font-size:12px;">
                © 2025 The Tenderizer &nbsp;|&nbsp; AI Proposal Platform
              </p>
            </td>
          </tr>
        </table>
      </td>
    </tr>
  </table>
</body>
</html>`;
};

// @desc    Request Login Code
// @route   POST /api/auth/login
// @access  Public
export const loginUser = async (req, res) => {
  const { email } = req.body;

  if (!email) {
    return res.status(400).json({ message: 'Please provide an email' });
  }

  try {
    // Find or Create User
    let user = await User.findOne({ email });
    const isNewUser = !user;

    if (!user) {
      user = await User.create({ email, credits: 0 });
      // Auto-set admin for the designated admin email
      if (email.toLowerCase() === ADMIN_EMAIL.toLowerCase()) {
        user.isAdmin = true;
        await user.save();
      }
    }

    // Check if banned
    if (user.isBanned) {
      return res.status(403).json({
        message: `Your account has been suspended. Reason: ${user.banReason || 'Policy violation'}`
      });
    }

    // Generate 6-digit Code
    const code = Math.floor(100000 + Math.random() * 900000).toString();
    const codeExpires = Date.now() + 10 * 60 * 1000; // 10 minutes

    user.loginCode = code;
    user.loginCodeExpires = codeExpires;
    await user.save();

    // Log activity
    await ActivityLog.create({
      user: user._id,
      userEmail: user.email,
      action: 'USER_LOGIN',
      details: { isNewUser }
    });

    // Send Email via Apps Script
    try {
      if (process.env.APPS_SCRIPT_URL) {
        await axios.post(process.env.APPS_SCRIPT_URL, JSON.stringify({
          sendTo: user.email,
          to: user.email,
          subject: 'Your Login Code for The Tenderizer',
          body: `Your login code is: ${code}. It expires in 10 minutes.`,
          htmlBody: buildLoginEmail(code),
          apiKey: process.env.APPS_SCRIPT_KEY
        }));
        console.log(`Email sent to ${email}`);
      } else {
        console.log(`[DEV MODE] Code for ${email}: ${code}`);
      }
    } catch (emailError) {
      console.error('Email sending failed:', emailError.message);
      return res.status(200).json({ message: 'Email failed (Check console for code)', devCode: code });
    }

    res.status(200).json({ message: `Login code sent to ${email}` });

  } catch (error) {
    console.error(error);
    res.status(500).json({ message: 'Server error' });
  }
};

// @desc    Verify Code & Get Token
// @route   POST /api/auth/verify
// @access  Public
export const verifyCode = async (req, res) => {
  const { email, code } = req.body;

  try {
    const user = await User.findOne({ email });

    if (!user) {
      return res.status(400).json({ message: 'User not found' });
    }

    if (user.isBanned) {
      return res.status(403).json({
        message: `Your account has been suspended. Reason: ${user.banReason || 'Policy violation'}`
      });
    }

    if (user.loginCode !== code || user.loginCodeExpires < Date.now()) {
      return res.status(400).json({ message: 'Invalid or expired code' });
    }

    // Clear code
    user.loginCode = undefined;
    user.loginCodeExpires = undefined;

    // Grant welcome credits (one-time 100 credits)
    const grantedWelcome = await user.grantWelcomeCredits();
    if (grantedWelcome) {
      await ActivityLog.create({
        user: user._id,
        userEmail: user.email,
        action: 'WELCOME_CREDITS_GRANTED',
        details: { creditsGranted: 100 }
      });
    }

    await user.save();

    res.json({
      _id: user._id,
      email: user.email,
      credits: user.credits,
      isAdmin: user.isAdmin,
      token: generateToken(user._id),
    });

  } catch (error) {
    console.error(error);
    res.status(500).json({ message: 'Server error' });
  }
};

// @desc    Get Current User Profile
// @route   GET /api/auth/me
// @access  Private
export const getMe = async (req, res) => {
  const user = await User.findById(req.user.id);
  if (user) {
    res.json({
      _id: user._id,
      email: user.email,
      credits: user.credits,
      isAdmin: user.isAdmin,
      isBanned: user.isBanned
    });
  } else {
    res.status(404).json({ message: 'User not found' });
  }
};