123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475 |
- import {
- hashPassword,
- verifyPassword,
- } from '../utils/helpers/hashPasswordHelpers';
-
- const mongoose = require('mongoose');
- const validator = require('validator');
-
- const UserSchema = new mongoose.Schema({
- fullName: {
- type: String,
- required: [true, 'Please provide a name.'],
- maxlength: [60, 'Name cannot be more than 60 characters'],
- trim: true,
- },
- username: {
- type: String,
- required: [true, 'Please provide a name.'],
- maxlength: [60, 'Name cannot be more than 60 characters'],
- trim: true,
- unique: true,
- },
- email: {
- type: String,
- unique: true,
- required: true,
- trim: true,
- lowercase: true,
- validate(value) {
- if (!validator.isEmail(value)) {
- throw new Error('Email is invalid');
- }
- },
- },
- password: {
- type: String,
- required: true,
- minlength: 7,
- trim: true,
- validate(value) {
- if (value.toLowerCase().includes('password')) {
- throw new Error('Password cannot contain "password"');
- }
- },
- },
- });
-
- UserSchema.statics.findByCredentials = async (username, password) => {
- const user = await User.findOne({ username });
-
- if (!user) {
- throw new Error('Unable to login');
- }
-
- const isMatch = await verifyPassword(password, user.password);
-
- if (!isMatch) {
- throw new Error('Unable to login');
- }
-
- return user;
- };
-
- UserSchema.pre('save', async function (next) {
- const user = this;
-
- if (user.isModified('password')) {
- user.password = await hashPassword(user.password);
- }
-
- next();
- });
-
- const User = mongoose.models.User || mongoose.model('User', UserSchema);
- module.exports = User;
|