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.

user.js 1.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import {
  2. hashPassword,
  3. verifyPassword,
  4. } from '../utils/helpers/hashPasswordHelpers';
  5. const mongoose = require('mongoose');
  6. const validator = require('validator');
  7. const UserSchema = new mongoose.Schema({
  8. fullName: {
  9. type: String,
  10. required: [true, 'Please provide a name.'],
  11. maxlength: [60, 'Name cannot be more than 60 characters'],
  12. trim: true,
  13. },
  14. username: {
  15. type: String,
  16. required: [true, 'Please provide a name.'],
  17. maxlength: [60, 'Name cannot be more than 60 characters'],
  18. trim: true,
  19. unique: true,
  20. },
  21. email: {
  22. type: String,
  23. unique: true,
  24. required: true,
  25. trim: true,
  26. lowercase: true,
  27. validate(value) {
  28. if (!validator.isEmail(value)) {
  29. throw new Error('Email is invalid');
  30. }
  31. },
  32. },
  33. password: {
  34. type: String,
  35. required: true,
  36. minlength: 7,
  37. trim: true,
  38. validate(value) {
  39. if (value.toLowerCase().includes('password')) {
  40. throw new Error('Password cannot contain "password"');
  41. }
  42. },
  43. },
  44. });
  45. UserSchema.statics.findByCredentials = async (username, password) => {
  46. const user = await User.findOne({ username });
  47. if (!user) {
  48. throw new Error('Unable to login');
  49. }
  50. const isMatch = await verifyPassword(password, user.password);
  51. if (!isMatch) {
  52. throw new Error('Unable to login');
  53. }
  54. return user;
  55. };
  56. UserSchema.pre('save', async function (next) {
  57. const user = this;
  58. if (user.isModified('password')) {
  59. user.password = await hashPassword(user.password);
  60. }
  61. next();
  62. });
  63. const User = mongoose.models.User || mongoose.model('User', UserSchema);
  64. module.exports = User;