diff --git a/backend/src/index.js b/backend/src/index.js index e3965d3..db0f294 100644 --- a/backend/src/index.js +++ b/backend/src/index.js @@ -5,6 +5,7 @@ const fileRoutes = require('./routes/files'); const shareRoutes = require('./routes/share'); const syncRoutes = require('./routes/sync'); const previewRoutes = require('./routes/preview'); +const userRoutes = require('./routes/user'); const errorHandler = require('./middleware/errorHandler'); const app = express(); @@ -19,6 +20,7 @@ app.use('/api/files', fileRoutes); app.use('/api/share', shareRoutes); app.use('/api/sync', syncRoutes); app.use('/api/preview', previewRoutes); +app.use('/api/user', userRoutes); // Error handler app.use(errorHandler); diff --git a/backend/src/routes/user.js b/backend/src/routes/user.js new file mode 100644 index 0000000..cc10143 --- /dev/null +++ b/backend/src/routes/user.js @@ -0,0 +1,63 @@ +const express = require('express'); +const bcrypt = require('bcrypt'); +const db = require('../db'); + +const router = express.Router(); + +// Get user profile +router.get('/profile', (req, res) => { + const token = req.headers.authorization?.replace('Bearer ', ''); + if (!token) return res.status(401).json({ error: 'No token' }); + + try { + const jwt = require('jsonwebtoken'); + const decoded = jwt.verify(token, process.env.JWT_SECRET || 'clouddisk-secret-key'); + + db.query( + 'SELECT id, username, email, storage_used, storage_limit FROM users WHERE id = ?', + [decoded.userId] + ).then(users => { + if (users.length === 0) { + return res.status(404).json({ error: 'User not found' }); + } + res.json({ user: users[0] }); + }); + } catch (error) { + res.status(401).json({ error: 'Invalid token' }); + } +}); + +// Update password +router.put('/password', (req, res) => { + const token = req.headers.authorization?.replace('Bearer ', ''); + if (!token) return res.status(401).json({ error: 'No token' }); + + try { + const jwt = require('jsonwebtoken'); + const decoded = jwt.verify(token, process.env.JWT_SECRET || 'clouddisk-secret-key'); + + const { oldPassword, newPassword } = req.body; + + db.query('SELECT password_hash FROM users WHERE id = ?', [decoded.userId]) + .then(users => { + if (users.length === 0) { + return res.status(404).json({ error: 'User not found' }); + } + + bcrypt.compare(oldPassword, users[0].password_hash, (err, valid) => { + if (!valid) { + return res.status(400).json({ error: 'Old password incorrect' }); + } + + bcrypt.hash(newPassword, 10, (err, hash) => { + db.run('UPDATE users SET password_hash = ? WHERE id = ?', [hash, decoded.userId]) + .then(() => res.json({ success: true })); + }); + }); + }); + } catch (error) { + res.status(500).json({ error: error.message }); + } +}); + +module.exports = router;