Jamesabira / Open-CV

0 stars 0 forks source link

Server side validation (express.js) #5

Open Jamesabira opened 10 months ago

Jamesabira commented 10 months ago

We'll use the express-validator library for validation. First, install the library by running:

npm install express-validator

Now, let's update the code for the registration route with proper validation and error handling. We'll also structure the code more neatly:

const express = require('express');
const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const session = require('express-session');
const MongoStore = require('connect-mongo')(session);
const { check, validationResult } = require('express-validator');

const app = express();

app.use(express.json());
app.use(express.urlencoded({ extended: true }));

app.use(session({
  secret: 'your-secret-key',
  resave: false,
  saveUninitialized: true,
  store: new MongoStore({ mongooseConnection: mongoose.connection }),
}));

mongoose.connect('mongodb://localhost/login-register-system', {
  useNewUrlParser: true,
  useUnifiedTopology: true,
  useCreateIndex: true,
});

const User = mongoose.model('User', {
  firstName: String,
  lastName: String,
  email: String,
  phoneNumber: String,
  username: { type: String, unique: true },
  password: String,
  failedLoginAttempts: { type: Number, default: 0 },
  isLockedOut: { type: Boolean, default: false },
  lockoutUntil: { type: Date, default: Date.now },
});

User.pre('save', async function(next) {
  if (!this.isModified('password')) {
    return next();
  }
  try {
    const hash = await bcrypt.hash(this.password, 10);
    this.password = hash;
    next();
  } catch (error) {
    next(error);
  }
});

// Validation rules for registration
const registrationValidationRules = [
  check('firstName', 'First name is required').notEmpty(),
  check('lastName', 'Last name is required').notEmpty(),
  check('email', 'Invalid email').isEmail(),
  check('phoneNumber', 'Invalid phone number').optional().isMobilePhone(),
  check('username', 'Username must be at least 5 characters').isLength({ min: 5 }),
  check('password', 'Password must be at least 6 characters').isLength({ min: 6 }),
];

// Registration route with validation
app.post('/register', registrationValidationRules, async (req, res) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(400).json({ errors: errors.array() });
  }

  const { firstName, lastName, email, phoneNumber, username, password } = req.body;

  try {
    const user = new User({ firstName, lastName, email, phoneNumber, username, password });
    await user.save();
    res.json({ message: 'Registration successful.' });
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: 'Registration failed.' });
  }
});

// Login route (unchanged)
app.post('/login', async (req, res) => {
  // Handle user login
  // ...
});

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

we've added validation rules for the registration route and used express-validator to check for validation errors. If there are validation errors, the server will respond with a 400 Bad Request status and provide details about the validation errors. Otherwise, if the input is valid, it will proceed with user registration.