Next.js template
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

signup.js 1.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import { connectToDatabase } from '../../../utils/helpers/dbHelpers';
  2. import { hashPassword } from '../../../utils/helpers/hashPasswordHelpers';
  3. async function handler(req, res) {
  4. if (req.method !== 'POST') {
  5. return;
  6. }
  7. const { fullName, username, email, password } = req.body;
  8. if (
  9. !fullName ||
  10. !username ||
  11. !email ||
  12. !email.includes('@') ||
  13. !password ||
  14. password.trim().length < 7
  15. ) {
  16. res.status(422).json({
  17. message: 'Invalid input ',
  18. });
  19. return;
  20. }
  21. const client = await connectToDatabase();
  22. const db = client.db();
  23. const existingUser = await db
  24. .collection('users')
  25. .findOne({ $or: [{ email: email }, { username: username }] });
  26. if (existingUser) {
  27. res.status(422).json({ message: 'User exists already!' });
  28. client.close();
  29. return;
  30. }
  31. const hashedPassword = await hashPassword(password);
  32. const result = await db.collection('users').insertOne({
  33. fullName: fullName,
  34. username: username,
  35. email: email,
  36. password: hashedPassword,
  37. });
  38. res.status(201).json({ message: 'Created user!', result: result });
  39. client.close();
  40. }
  41. export default handler;