user.model.js 1.35 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import bcrypt from "bcryptjs";
import { DataTypes } from "sequelize";
// import img from 'bora_it\client\public\user.png'

const UserModel = (sequelize) => {
  const User = sequelize.define(
    "user",
    {
      id: {
        type: DataTypes.INTEGER,
        primaryKey: true,
      },
      name: {
        type: DataTypes.STRING,
      },
      email: {
        type: DataTypes.STRING,
      },
      password: {
        type: DataTypes.STRING,
      },
      gender: {
        type: DataTypes.INTEGER,
      },
      phone: {
        type: DataTypes.STRING,
      },
      img: {
        type: DataTypes.STRING,
        defaultValue:'defaultimg'
      },
      roomNumber: {
        type: DataTypes.ARRAY(DataTypes.STRING),
      },
    },
    { timestamps: true }
  );

  User.beforeSave(async (user) => {
    if (!user.changed("password")) {
      return;
    }

    if (user.password) {
      const hashedPassword = await bcrypt.hash(user.password, 10);
      user.password = hashedPassword;
    }
  });

  User.prototype.toJSON = function toJSON() {
    const values = Object.assign({}, this.get());

    delete values.password;
    return values;
  };

  User.prototype.comparePassword = async function (plainPassword) {
    const passwordMatch = await bcrypt.compare(plainPassword, this.password);
    return passwordMatch;
  };

  return User;
};

export default UserModel;