64 lines
2.0 KiB
JavaScript
64 lines
2.0 KiB
JavaScript
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;
|