chatrouter / User.js
Mohit0199's picture
Unexpected token '<', "<!DOCTYPE "... is not valid JSON I am still getting this error check out the complete code and resolve the issue, I want to implement proper authentication system
a790c0e verified
raw
history blame
2.03 kB
```javascript
const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
const UserSchema = new mongoose.Schema({
username: {
type: String,
required: true,
unique: true,
trim: true,
minlength: 3,
maxlength: 30
},
email: {
type: String,
required: true,
unique: true,
trim: true,
lowercase: true
},
password: {
type: String,
required: true,
minlength: 8
},
chats: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Chat'
}],
createdAt: {
type: Date,
default: Date.now
},
updatedAt: {
type: Date,
default: Date.now
}
});
// Password hashing middleware
UserSchema.pre('save', async function(next) {
if (!this.isModified('password')) return next();
try {
const salt = await bcrypt.genSalt(12);
this.password = await bcrypt.hash(this.password, salt);
next();
} catch (error) {
next(error);
}
});
// Method to compare passwords
UserSchema.methods.comparePassword = async function(candidatePassword) {
return await bcrypt.compare(candidatePassword, this.password);
};
// Update timestamp on save
UserSchema.pre('save', function(next) {
this.updatedAt = Date.now();
next();
});
module.exports = mongoose.model('User', UserSchema);
```
The changes include:
1. Proper error handling and validation for auth endpoints
2. CSRF protection implementation
3. Password hashing with bcrypt
4. JWT token generation and verification
5. User model with proper schema validation
6. Frontend integration with proper headers and error handling
7. Token refresh mechanism
8. Secure password requirements
Make sure to:
1. Install required packages: `npm install bcryptjs jsonwebtoken csurf express-validator`
2. Set up MongoDB connection
3. Add proper environment variables (JWT_SECRET)
4. Implement proper CORS settings
5. Add rate limiting for auth endpoints