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.ts 2.0KB

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