Spaces:
Sleeping
Sleeping
Download backend/src/controllers/userController.js from edichat/edi.chat.test: direct link, hf CLI and curl.
- Browser
- Download file 8.69 kB
-
https://huggingface.co/spaces/edichat/edi.chat.test/resolve/main/backend/src/controllers/userController.js
- Command line
-
hf download hf://spaces/edichat/edi.chat.test/backend/src/controllers/userController.js
-
curl -L -o userController.js https://huggingface.co/spaces/edichat/edi.chat.test/resolve/main/backend/src/controllers/userController.js
8.69 kB
| const { validationResult } = require('express-validator'); | |
| const User = require('../models/User'); | |
| const Conversation = require('../models/Conversation'); | |
| const logger = require('../utils/logger'); | |
| class UserController { | |
| async getProfile(req, res) { | |
| try { | |
| // Require authenticated user | |
| if (!req.user || !req.user.id) { | |
| return res.status(401).json({ | |
| success: false, | |
| error: 'Authentication required' | |
| }); | |
| } | |
| const userId = req.user.id; | |
| const user = await User.findById(userId).select('-passwordHash -integrationTokens'); | |
| if (!user) { | |
| return res.status(404).json({ | |
| success: false, | |
| error: 'User not found' | |
| }); | |
| } | |
| res.json({ | |
| success: true, | |
| data: user | |
| }); | |
| } catch (error) { | |
| logger.error('Get profile error:', error); | |
| res.status(500).json({ | |
| success: false, | |
| error: 'Failed to fetch profile' | |
| }); | |
| } | |
| } | |
| async updateProfile(req, res) { | |
| try { | |
| const errors = validationResult(req); | |
| if (!errors.isEmpty()) { | |
| return res.status(400).json({ | |
| success: false, | |
| errors: errors.array() | |
| }); | |
| } | |
| const updateData = {}; | |
| const allowedFields = ['firstName', 'lastName', 'displayName', 'college', 'department', 'major', 'classification']; | |
| allowedFields.forEach(field => { | |
| if (req.body[field] !== undefined) { | |
| updateData[field] = req.body[field]; | |
| } | |
| }); | |
| // Require authenticated user | |
| if (!req.user || !req.user.id) { | |
| return res.status(401).json({ | |
| success: false, | |
| error: 'Authentication required' | |
| }); | |
| } | |
| const user = await User.findByIdAndUpdate( | |
| req.user.id, | |
| updateData, | |
| { new: true, runValidators: true } | |
| ).select('-passwordHash -integrationTokens'); | |
| if (!user) { | |
| return res.status(404).json({ | |
| success: false, | |
| error: 'User not found' | |
| }); | |
| } | |
| logger.info('Profile updated', { userId: req.user.id, updates: Object.keys(updateData) }); | |
| res.json({ | |
| success: true, | |
| data: user, | |
| message: 'Profile updated successfully' | |
| }); | |
| } catch (error) { | |
| logger.error('Update profile error:', error); | |
| res.status(500).json({ | |
| success: false, | |
| error: 'Failed to update profile' | |
| }); | |
| } | |
| } | |
| async getPreferences(req, res) { | |
| try { | |
| // Require authenticated user | |
| if (!req.user || !req.user.id) { | |
| return res.status(401).json({ | |
| success: false, | |
| error: 'Authentication required' | |
| }); | |
| } | |
| const user = await User.findById(req.user.id).select('preferences'); | |
| if (!user) { | |
| return res.status(404).json({ | |
| success: false, | |
| error: 'User not found' | |
| }); | |
| } | |
| res.json({ | |
| success: true, | |
| data: user.preferences | |
| }); | |
| } catch (error) { | |
| logger.error('Get preferences error:', error); | |
| res.status(500).json({ | |
| success: false, | |
| error: 'Failed to fetch preferences' | |
| }); | |
| } | |
| } | |
| async updatePreferences(req, res) { | |
| try { | |
| const errors = validationResult(req); | |
| if (!errors.isEmpty()) { | |
| return res.status(400).json({ | |
| success: false, | |
| errors: errors.array() | |
| }); | |
| } | |
| const updateData = {}; | |
| // Handle nested preference updates | |
| if (req.body.theme) updateData['preferences.theme'] = req.body.theme; | |
| if (req.body.language) updateData['preferences.language'] = req.body.language; | |
| if (req.body.chatHistory !== undefined) updateData['preferences.chatHistory'] = req.body.chatHistory; | |
| // Handle notifications object | |
| if (req.body.notifications) { | |
| if (req.body.notifications.email !== undefined) { | |
| updateData['preferences.notifications.email'] = req.body.notifications.email; | |
| } | |
| if (req.body.notifications.push !== undefined) { | |
| updateData['preferences.notifications.push'] = req.body.notifications.push; | |
| } | |
| if (req.body.notifications.sms !== undefined) { | |
| updateData['preferences.notifications.sms'] = req.body.notifications.sms; | |
| } | |
| } | |
| // Require authenticated user | |
| if (!req.user || !req.user.id) { | |
| return res.status(401).json({ | |
| success: false, | |
| error: 'Authentication required' | |
| }); | |
| } | |
| const user = await User.findByIdAndUpdate( | |
| req.user.id, | |
| updateData, | |
| { new: true, runValidators: true } | |
| ).select('preferences'); | |
| if (!user) { | |
| return res.status(404).json({ | |
| success: false, | |
| error: 'User not found' | |
| }); | |
| } | |
| logger.info('Preferences updated', { userId: req.user.id, updates: Object.keys(updateData) }); | |
| res.json({ | |
| success: true, | |
| data: user.preferences, | |
| message: 'Preferences updated successfully' | |
| }); | |
| } catch (error) { | |
| logger.error('Update preferences error:', error); | |
| res.status(500).json({ | |
| success: false, | |
| error: 'Failed to update preferences' | |
| }); | |
| } | |
| } | |
| async getStats(req, res) { | |
| try { | |
| // Require authenticated user | |
| if (!req.user || !req.user.id) { | |
| return res.status(401).json({ | |
| success: false, | |
| error: 'Authentication required' | |
| }); | |
| } | |
| const userId = req.user.id; | |
| const user = await User.findById(userId).select('stats'); | |
| if (!user) { | |
| return res.status(404).json({ | |
| success: false, | |
| error: 'User not found' | |
| }); | |
| } | |
| // Ensure stats object exists and has default values | |
| const userStats = user.stats || { | |
| totalChats: 0, | |
| totalQuestions: 0, | |
| favoriteTopics: [], | |
| lastActive: new Date() | |
| }; | |
| // Get additional conversation statistics | |
| const conversationStats = await Conversation.aggregate([ | |
| { $match: { userId: userId, isActive: true } }, | |
| { | |
| $group: { | |
| _id: '$category', | |
| count: { $sum: 1 }, | |
| avgMessageCount: { $avg: '$stats.messageCount' }, | |
| totalMessages: { $sum: '$stats.messageCount' } | |
| } | |
| } | |
| ]); | |
| const totalConversations = await Conversation.countDocuments({ | |
| userId: userId, | |
| isActive: true | |
| }); | |
| const stats = { | |
| totalChats: userStats.totalChats || 0, | |
| totalQuestions: userStats.totalQuestions || 0, | |
| favoriteTopics: userStats.favoriteTopics || [], | |
| lastActive: userStats.lastActive || new Date(), | |
| totalConversations, | |
| conversationsByCategory: conversationStats, | |
| averageConversationLength: conversationStats.reduce((acc, cat) => acc + (cat.avgMessageCount || 0), 0) / (conversationStats.length || 1) | |
| }; | |
| res.json({ | |
| success: true, | |
| data: stats | |
| }); | |
| } catch (error) { | |
| logger.error('Get stats error:', error); | |
| res.status(500).json({ | |
| success: false, | |
| error: 'Failed to fetch statistics' | |
| }); | |
| } | |
| } | |
| async getConversationsSummary(req, res) { | |
| try { | |
| const { limit = 10, category } = req.query; | |
| // Require authenticated user | |
| if (!req.user || !req.user.id) { | |
| return res.status(401).json({ | |
| success: false, | |
| error: 'Authentication required' | |
| }); | |
| } | |
| const matchQuery = { userId: req.user.id, isActive: true }; | |
| if (category && category !== 'all') { | |
| matchQuery.category = category; | |
| } | |
| const conversations = await Conversation.find(matchQuery) | |
| .select('title category lastActivity stats.messageCount stats.userSatisfaction') | |
| .sort({ lastActivity: -1 }) | |
| .limit(parseInt(limit)); | |
| const summary = { | |
| recentConversations: conversations, | |
| totalActive: await Conversation.countDocuments({ userId: req.user.id, isActive: true }), | |
| categories: await Conversation.aggregate([ | |
| { $match: { userId: req.user.id, isActive: true } }, | |
| { $group: { _id: '$category', count: { $sum: 1 } } }, | |
| { $sort: { count: -1 } } | |
| ]) | |
| }; | |
| res.json({ | |
| success: true, | |
| data: summary | |
| }); | |
| } catch (error) { | |
| logger.error('Get conversations summary error:', error); | |
| res.status(500).json({ | |
| success: false, | |
| error: 'Failed to fetch conversations summary' | |
| }); | |
| } | |
| } | |
| } | |
| module.exports = new UserController(); |