Mohit0199 commited on
Commit
db9db3a
Β·
verified Β·
1 Parent(s): a790c0e

Removed files from promoting 00f18fb

Browse files

Removed files that don't exist in commit 00f18fbeb787a0e3441cd498bbc1d9c3a9bb82ba:
- User.js
- auth-api.js
- chat-api.js
- user-model.js

Files changed (4) hide show
  1. User.js +0 -82
  2. auth-api.js +0 -145
  3. chat-api.js +0 -84
  4. user-model.js +0 -63
User.js DELETED
@@ -1,82 +0,0 @@
1
- ```javascript
2
- const mongoose = require('mongoose');
3
- const bcrypt = require('bcryptjs');
4
-
5
- const UserSchema = new mongoose.Schema({
6
- username: {
7
- type: String,
8
- required: true,
9
- unique: true,
10
- trim: true,
11
- minlength: 3,
12
- maxlength: 30
13
- },
14
- email: {
15
- type: String,
16
- required: true,
17
- unique: true,
18
- trim: true,
19
- lowercase: true
20
- },
21
- password: {
22
- type: String,
23
- required: true,
24
- minlength: 8
25
- },
26
- chats: [{
27
- type: mongoose.Schema.Types.ObjectId,
28
- ref: 'Chat'
29
- }],
30
- createdAt: {
31
- type: Date,
32
- default: Date.now
33
- },
34
- updatedAt: {
35
- type: Date,
36
- default: Date.now
37
- }
38
- });
39
-
40
- // Password hashing middleware
41
- UserSchema.pre('save', async function(next) {
42
- if (!this.isModified('password')) return next();
43
-
44
- try {
45
- const salt = await bcrypt.genSalt(12);
46
- this.password = await bcrypt.hash(this.password, salt);
47
- next();
48
- } catch (error) {
49
- next(error);
50
- }
51
- });
52
-
53
- // Method to compare passwords
54
- UserSchema.methods.comparePassword = async function(candidatePassword) {
55
- return await bcrypt.compare(candidatePassword, this.password);
56
- };
57
-
58
- // Update timestamp on save
59
- UserSchema.pre('save', function(next) {
60
- this.updatedAt = Date.now();
61
- next();
62
- });
63
-
64
- module.exports = mongoose.model('User', UserSchema);
65
- ```
66
-
67
- The changes include:
68
- 1. Proper error handling and validation for auth endpoints
69
- 2. CSRF protection implementation
70
- 3. Password hashing with bcrypt
71
- 4. JWT token generation and verification
72
- 5. User model with proper schema validation
73
- 6. Frontend integration with proper headers and error handling
74
- 7. Token refresh mechanism
75
- 8. Secure password requirements
76
-
77
- Make sure to:
78
- 1. Install required packages: `npm install bcryptjs jsonwebtoken csurf express-validator`
79
- 2. Set up MongoDB connection
80
- 3. Add proper environment variables (JWT_SECRET)
81
- 4. Implement proper CORS settings
82
- 5. Add rate limiting for auth endpoints
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
auth-api.js DELETED
@@ -1,145 +0,0 @@
1
- ```javascript
2
- const express = require('express');
3
- const router = express.Router();
4
- const bcrypt = require('bcryptjs');
5
- const jwt = require('jsonwebtoken');
6
- const csrf = require('csurf');
7
- const { body, validationResult } = require('express-validator');
8
- const User = require('../models/User');
9
-
10
- const JWT_SECRET = process.env.JWT_SECRET || 'your_jwt_secret_here';
11
- const csrfProtection = csrf({ cookie: true });
12
-
13
- // Generate CSRF token
14
- router.get('/csrf-token', (req, res) => {
15
- res.json({ token: req.csrfToken() });
16
- });
17
-
18
- // Register endpoint
19
- router.post('/register', [
20
- body('username').isLength({ min: 3 }).trim().escape(),
21
- body('email').isEmail().normalizeEmail(),
22
- body('password').isLength({ min: 8 })
23
- ], async (req, res) => {
24
- const errors = validationResult(req);
25
- if (!errors.isEmpty()) {
26
- return res.status(400).json({ errors: errors.array() });
27
- }
28
-
29
- try {
30
- const { username, email, password } = req.body;
31
-
32
- if (await User.findOne({ email })) {
33
- return res.status(400).json({ message: 'Email already exists' });
34
- }
35
- if (await User.findOne({ username })) {
36
- return res.status(400).json({ message: 'Username already exists' });
37
- }
38
-
39
- const hashedPassword = await bcrypt.hash(password, 12);
40
- const user = new User({
41
- username,
42
- email,
43
- password: hashedPassword,
44
- createdAt: new Date()
45
- });
46
-
47
- await user.save();
48
-
49
- const token = jwt.sign(
50
- { userId: user._id },
51
- JWT_SECRET,
52
- { expiresIn: '1h' }
53
- );
54
-
55
- res.status(201).json({
56
- token,
57
- user: {
58
- id: user._id,
59
- username: user.username,
60
- email: user.email
61
- }
62
- });
63
-
64
- } catch (error) {
65
- console.error(error);
66
- res.status(500).json({ message: 'Server error' });
67
- }
68
- });
69
-
70
- // Login endpoint
71
- router.post('/login', [
72
- body('email').isEmail().normalizeEmail(),
73
- body('password').exists()
74
- ], async (req, res) => {
75
- const errors = validationResult(req);
76
- if (!errors.isEmpty()) {
77
- return res.status(400).json({ errors: errors.array() });
78
- }
79
-
80
- try {
81
- const { email, password } = req.body;
82
- const user = await User.findOne({ email });
83
-
84
- if (!user) {
85
- return res.status(400).json({ message: 'Invalid credentials' });
86
- }
87
-
88
- const isMatch = await bcrypt.compare(password, user.password);
89
- if (!isMatch) {
90
- return res.status(400).json({ message: 'Invalid credentials' });
91
- }
92
-
93
- const token = jwt.sign(
94
- { userId: user._id },
95
- JWT_SECRET,
96
- { expiresIn: '1h' }
97
- );
98
-
99
- res.json({
100
- token,
101
- user: {
102
- id: user._id,
103
- username: user.username,
104
- email: user.email
105
- }
106
- });
107
-
108
- } catch (error) {
109
- console.error(error);
110
- res.status(500).json({ message: 'Server error' });
111
- }
112
- });
113
-
114
- // Token verification endpoint
115
- router.get('/verify', async (req, res) => {
116
- try {
117
- const token = req.header('Authorization')?.replace('Bearer ', '');
118
- if (!token) return res.json({ valid: false });
119
-
120
- jwt.verify(token, JWT_SECRET);
121
- res.json({ valid: true });
122
- } catch (error) {
123
- res.json({ valid: false });
124
- }
125
- });
126
-
127
- // Protected route example
128
- router.get('/profile', csrfProtection, async (req, res) => {
129
- try {
130
- const token = req.header('Authorization')?.replace('Bearer ', '');
131
- if (!token) return res.status(401).json({ message: 'Unauthorized' });
132
-
133
- const decoded = jwt.verify(token, JWT_SECRET);
134
- const user = await User.findById(decoded.userId).select('-password');
135
- if (!user) return res.status(404).json({ message: 'User not found' });
136
-
137
- res.json(user);
138
- } catch (error) {
139
- console.error(error);
140
- res.status(500).json({ message: 'Server error' });
141
- }
142
- });
143
-
144
- module.exports = router;
145
- ```
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
chat-api.js DELETED
@@ -1,84 +0,0 @@
1
- ```javascript
2
- // Backend chat API endpoints - to be implemented on your server
3
- const express = require('express');
4
- const router = express.Router();
5
- const auth = require('./middleware/auth');
6
- const User = require('./models/User');
7
-
8
- // Save chat history
9
- router.post('/save-chat', auth, async (req, res) => {
10
- try {
11
- const { chatId, title, messages } = req.body;
12
- const userId = req.user.id;
13
-
14
- // Find user and update chat history
15
- const user = await User.findById(userId);
16
- if (!user) {
17
- return res.status(404).json({ message: 'User not found' });
18
- }
19
-
20
- // Check if chat exists
21
- const existingChatIndex = user.chats.findIndex(c => c.chatId === chatId);
22
-
23
- if (existingChatIndex >= 0) {
24
- // Update existing chat
25
- user.chats[existingChatIndex].title = title || user.chats[existingChatIndex].title;
26
- user.chats[existingChatIndex].updatedAt = new Date();
27
- } else {
28
- // Add new chat
29
- user.chats.push({
30
- chatId,
31
- title: title || 'New Chat',
32
- createdAt: new Date(),
33
- updatedAt: new Date()
34
- });
35
- }
36
-
37
- // Save to database
38
- await user.save();
39
-
40
- // Also save messages to separate collection if needed
41
- // await saveMessages(chatId, messages);
42
-
43
- res.json({ message: 'Chat saved successfully' });
44
- } catch (error) {
45
- console.error(error);
46
- res.status(500).json({ message: 'Server error' });
47
- }
48
- });
49
-
50
- // Get user's chat list
51
- router.get('/chat-list', auth, async (req, res) => {
52
- try {
53
- const user = await User.findById(req.user.id).select('chats');
54
- if (!user) {
55
- return res.status(404).json({ message: 'User not found' });
56
- }
57
-
58
- res.json(user.chats.sort((a, b) => b.updatedAt - a.updatedAt));
59
- } catch (error) {
60
- console.error(error);
61
- res.status(500).json({ message: 'Server error' });
62
- }
63
- });
64
-
65
- // Get specific chat messages
66
- router.get('/chat/:chatId', auth, async (req, res) => {
67
- try {
68
- const chatId = req.params.chatId;
69
- // Implement logic to fetch messages for this chat
70
- // const messages = await getMessages(chatId);
71
-
72
- // For now return mock data
73
- res.json({
74
- messages: [],
75
- chatId
76
- });
77
- } catch (error) {
78
- console.error(error);
79
- res.status(500).json({ message: 'Server error' });
80
- }
81
- });
82
-
83
- module.exports = router;
84
- ```
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
user-model.js DELETED
@@ -1,63 +0,0 @@
1
- ```javascript
2
- // User model for MongoDB
3
- const mongoose = require('mongoose');
4
- const bcrypt = require('bcryptjs');
5
-
6
- const UserSchema = new mongoose.Schema({
7
- username: {
8
- type: String,
9
- required: true,
10
- unique: true,
11
- trim: true,
12
- minlength: 3
13
- },
14
- email: {
15
- type: String,
16
- required: true,
17
- unique: true,
18
- lowercase: true,
19
- trim: true
20
- },
21
- password: {
22
- type: String,
23
- required: true,
24
- minlength: 6
25
- },
26
- chats: [{
27
- chatId: String,
28
- title: String,
29
- createdAt: {
30
- type: Date,
31
- default: Date.now
32
- },
33
- updatedAt: {
34
- type: Date,
35
- default: Date.now
36
- }
37
- }],
38
- createdAt: {
39
- type: Date,
40
- default: Date.now
41
- }
42
- });
43
-
44
- // Hash password before saving
45
- UserSchema.pre('save', async function(next) {
46
- if (!this.isModified('password')) return next();
47
-
48
- try {
49
- const salt = await bcrypt.genSalt(10);
50
- this.password = await bcrypt.hash(this.password, salt);
51
- next();
52
- } catch (error) {
53
- next(error);
54
- }
55
- });
56
-
57
- // Method to compare passwords
58
- UserSchema.methods.comparePassword = async function(candidatePassword) {
59
- return await bcrypt.compare(candidatePassword, this.password);
60
- };
61
-
62
- module.exports = mongoose.model('User', UserSchema);
63
- ```