user.model.js 1.29 KB
Newer Older
1
import bcrypt from "bcryptjs";
Kim, Chaerin's avatar
Kim, Chaerin committed
2
3
import pkg from "sequelize";
const { DataTypes } = pkg;
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

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: {
우지원's avatar
e    
우지원 committed
26
        type: DataTypes.INTEGER,
27
28
      },
      img: {
우지원's avatar
e    
우지원 committed
29
        type: DataTypes.STRING,
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
      },
      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;