|
| 1 | +const bcrypt = require("bcryptjs"); |
| 2 | +const User = require("../models/User"); |
| 3 | +const jwt = require("jsonwebtoken"); |
| 4 | +const speakeasy = require("speakeasy"); |
| 5 | +const QRCode = require("qrcode"); |
| 6 | + |
| 7 | +// 📌 How this works: |
| 8 | + |
| 9 | +// Throws an error if the user is not found. |
| 10 | +// Passes it to errorHandler.js. |
| 11 | +exports.getUserProfile = async (req, res, next) => { |
| 12 | + try { |
| 13 | + const user = await User.findById(req.user.id); |
| 14 | + if (!user) { |
| 15 | + throw { status: 404, message: "User not found" }; // Throw an error |
| 16 | + } |
| 17 | + res.json(user); |
| 18 | + } catch (error) { |
| 19 | + next(error); // Pass error to middleware |
| 20 | + } |
| 21 | +}; |
| 22 | + |
| 23 | +exports.verify2FA = async (req, res) => { |
| 24 | + try { |
| 25 | + const { token } = req.body; |
| 26 | + const user = await User.findById(req.user.id); |
| 27 | + |
| 28 | + if (!user || !user.isTwoFactorEnabled) { |
| 29 | + return res.status(400).json({ message: "2FA is not enabled" }); |
| 30 | + } |
| 31 | + |
| 32 | + const isValid = speakeasy.totp.verify({ |
| 33 | + secret: user.twoFactorSecret, |
| 34 | + encoding: "base32", |
| 35 | + token, |
| 36 | + }); |
| 37 | + |
| 38 | + if (!isValid) { |
| 39 | + return res.status(400).json({ message: "Invalid OTP" }); |
| 40 | + } |
| 41 | + |
| 42 | + res.json({ message: "2FA verification successful" }); |
| 43 | + } catch (error) { |
| 44 | + res.status(500).json({ message: "Error verifying 2FA", error }); |
| 45 | + } |
| 46 | +}; |
| 47 | + |
| 48 | +// Generate and return a 2FA secret and QR code |
| 49 | +exports.enable2FA = async (req, res) => { |
| 50 | + try { |
| 51 | + const user = await User.findById(req.user.id); |
| 52 | + if (!user) { |
| 53 | + return res.status(404).json({ message: "User not found" }); |
| 54 | + } |
| 55 | + |
| 56 | + const secret = speakeasy.generateSecret({ length: 20 }); |
| 57 | + |
| 58 | + // Save the secret in the database |
| 59 | + user.twoFactorSecret = secret.base32; |
| 60 | + user.isTwoFactorEnabled = true; |
| 61 | + await user.save(); |
| 62 | + |
| 63 | + // Generate QR code for Google Authenticator |
| 64 | + const otpAuthUrl = `otpauth://totp/secure_auth_api?secret=${secret.ascii}&issuer=secure_auth_api`; |
| 65 | + QRCode.toDataURL(otpAuthUrl, (err, imageUrl) => { |
| 66 | + if (err) |
| 67 | + return res.status(500).json({ message: "QR Code generation failed" }); |
| 68 | + |
| 69 | + res.json({ |
| 70 | + message: "2FA enabled", |
| 71 | + secret: secret.base32, // Show only for testing |
| 72 | + qrCode: imageUrl, // Send QR Code image URL |
| 73 | + }); |
| 74 | + }); |
| 75 | + } catch (error) { |
| 76 | + res.status(500).json({ message: "Error enabling 2FA", error }); |
| 77 | + } |
| 78 | +}; |
| 79 | + |
| 80 | +exports.register = async (req, res) => { |
| 81 | + try { |
| 82 | + const { username, email, password } = req.body; |
| 83 | + |
| 84 | + // Check if user already exists |
| 85 | + const existingUser = await User.findOne({ email }); |
| 86 | + if (existingUser) { |
| 87 | + return res.status(400).json({ message: "Email already in use" }); |
| 88 | + } |
| 89 | + |
| 90 | + // Hash the password |
| 91 | + const salt = await bcrypt.genSalt(10); |
| 92 | + const hashedPassword = await bcrypt.hash(password, salt); |
| 93 | + |
| 94 | + // Create a new user |
| 95 | + const user = new User({ |
| 96 | + username, |
| 97 | + email, |
| 98 | + password: hashedPassword, |
| 99 | + }); |
| 100 | + |
| 101 | + await user.save(); |
| 102 | + |
| 103 | + res.status(201).json({ message: "User registered successfully" }); |
| 104 | + } catch (error) { |
| 105 | + res.status(500).json({ message: "Server error", error: error.message }); |
| 106 | + } |
| 107 | +}; |
| 108 | + |
| 109 | +exports.login = async (req, res) => { |
| 110 | + try { |
| 111 | + const { email, password } = req.body; |
| 112 | + |
| 113 | + // Check if user exists |
| 114 | + const user = await User.findOne({ email }); |
| 115 | + if (!user) { |
| 116 | + return res.status(400).json({ message: "Invalid email or password" }); |
| 117 | + } |
| 118 | + |
| 119 | + // Verify password |
| 120 | + const isMatch = await bcrypt.compare(password, user.password); |
| 121 | + if (!isMatch) { |
| 122 | + return res.status(400).json({ message: "Invalid email or password" }); |
| 123 | + } |
| 124 | + |
| 125 | + // Generate JWT token |
| 126 | + const payload = { userId: user._id }; |
| 127 | + const token = jwt.sign(payload, process.env.JWT_SECRET, { |
| 128 | + expiresIn: "1h", |
| 129 | + }); |
| 130 | + |
| 131 | + res.json({ message: "Login successful", token }); |
| 132 | + } catch (error) { |
| 133 | + res.status(500).json({ message: "Server error", error: error.message }); |
| 134 | + } |
| 135 | +}; |
0 commit comments