All files / routes user.js

0% Statements 0/89
0% Branches 0/20
0% Functions 0/7
0% Lines 0/86

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                                                                                                                                                                                                                                                                                                                                                                                   
const express = require('express');
const router = express.Router();
const { User, Portfolio } = require('../models');
const { validate } = require('express-validator');
const logger = require('../utils/logger');
 
// Get current user profile
router.get('/profile', async (req, res) => {
  try {
    const user = await User.findByPk(req.userId, {
      include: [{ model: Portfolio, as: 'portfolio' }]
    });
    
    res.json({ user });
  } catch (error) {
    logger.error('Get profile error:', error);
    res.status(500).json({ error: 'Failed to fetch profile' });
  }
});
 
// Update user profile
router.put('/profile', async (req, res) => {
  try {
    const { email, username, riskProfile } = req.body;
    
    const user = await User.findByPk(req.userId);
    if (!user) {
      return res.status(404).json({ error: 'User not found' });
    }
 
    if (email) user.email = email;
    if (username) user.username = username;
    if (riskProfile) user.riskProfile = riskProfile;
 
    await user.save();
    
    res.json({ user, message: 'Profile updated successfully' });
  } catch (error) {
    logger.error('Update profile error:', error);
    res.status(500).json({ error: 'Failed to update profile' });
  }
});
 
// Get user statistics
router.get('/stats', async (req, res) => {
  try {
    const portfolio = await Portfolio.findOne({ where: { userId: req.userId } });
    
    if (!portfolio) {
      return res.json({
        totalDeposited: 0,
        currentValue: 0,
        totalProfits: 0,
        roi: 0
      });
    }
 
    res.json({
      totalDeposited: portfolio.totalDeposited,
      totalWithdrawn: portfolio.totalWithdrawn,
      currentValue: portfolio.currentValue,
      totalProfits: portfolio.totalProfits,
      totalLosses: portfolio.totalLosses,
      totalFeesPaid: portfolio.totalFeesPaid,
      roi: portfolio.calculateROI(),
      netValue: portfolio.calculateNetValue()
    });
  } catch (error) {
    logger.error('Get stats error:', error);
    res.status(500).json({ error: 'Failed to fetch statistics' });
  }
});
 
// Enable/disable 2FA
router.post('/2fa/enable', async (req, res) => {
  try {
    const speakeasy = require('speakeasy');
    const QRCode = require('qrcode');
    
    const user = await User.findByPk(req.userId);
    
    if (user.twoFactorEnabled) {
      return res.status(400).json({ error: '2FA already enabled' });
    }
 
    const secret = speakeasy.generateSecret({
      name: `Crypto Trading Bot (${user.walletAddress})`
    });
 
    user.twoFactorSecret = secret.base32;
    await user.save();
 
    const qrCode = await QRCode.toDataURL(secret.otpauth_url);
 
    res.json({
      secret: secret.base32,
      qrCode,
      message: 'Scan QR code with authenticator app'
    });
  } catch (error) {
    logger.error('Enable 2FA error:', error);
    res.status(500).json({ error: 'Failed to enable 2FA' });
  }
});
 
router.post('/2fa/verify', async (req, res) => {
  try {
    const { token } = req.body;
    const speakeasy = require('speakeasy');
    
    const user = await User.findByPk(req.userId);
    
    const verified = speakeasy.totp.verify({
      secret: user.twoFactorSecret,
      encoding: 'base32',
      token
    });
 
    if (!verified) {
      return res.status(400).json({ error: 'Invalid token' });
    }
 
    user.twoFactorEnabled = true;
    await user.save();
 
    res.json({ message: '2FA enabled successfully' });
  } catch (error) {
    logger.error('Verify 2FA error:', error);
    res.status(500).json({ error: 'Failed to verify 2FA' });
  }
});
 
router.post('/2fa/disable', async (req, res) => {
  try {
    const { token } = req.body;
    const speakeasy = require('speakeasy');
    
    const user = await User.findByPk(req.userId);
    
    if (!user.twoFactorEnabled) {
      return res.status(400).json({ error: '2FA not enabled' });
    }
 
    const verified = speakeasy.totp.verify({
      secret: user.twoFactorSecret,
      encoding: 'base32',
      token
    });
 
    if (!verified) {
      return res.status(400).json({ error: 'Invalid token' });
    }
 
    user.twoFactorEnabled = false;
    user.twoFactorSecret = null;
    await user.save();
 
    res.json({ message: '2FA disabled successfully' });
  } catch (error) {
    logger.error('Disable 2FA error:', error);
    res.status(500).json({ error: 'Failed to disable 2FA' });
  }
});
 
// Get referral information
router.get('/referral', async (req, res) => {
  try {
    const user = await User.findByPk(req.userId);
    
    // Generate referral code if not exists
    if (!user.referralCode) {
      user.referralCode = require('crypto').randomBytes(8).toString('hex');
      await user.save();
    }
 
    // Count referrals
    const referralCount = await User.count({
      where: { referredBy: user.id }
    });
 
    res.json({
      referralCode: user.referralCode,
      referralCount,
      referralLink: `${process.env.FRONTEND_URL}/signup?ref=${user.referralCode}`
    });
  } catch (error) {
    logger.error('Get referral error:', error);
    res.status(500).json({ error: 'Failed to fetch referral information' });
  }
});
 
module.exports = router;