user.model.js 1.16 KB
Newer Older
1
2
3
4
5
6
7
8
9
import bcrypt from "bcryptjs";
import Sequelize from "sequelize";

const { DataTypes } = Sequelize;

const UserModel = (sequelize) => {
  const User = sequelize.define(
    "user",
    {
Choi Ga Young's avatar
Choi Ga Young committed
10
      userID: {
11
12
        type: DataTypes.STRING
      },
Choi Ga Young's avatar
Choi Ga Young committed
13
14
15
16
17
18
19
20
21
      userName: {
        type: DataTypes.STRING
      },
      password: {
        type: DataTypes.STRING
      },
      studNum: {
        type: DataTypes.STRING
      }
22
23
24
25
26
27
28
29
30
31
32
33
34
    },
    {
      timestamps: true,
      freezeTableName: true,
      tableName: "users",
      defaultScope: {
        attributes: { exclude: ["password"] },
      },
      scopes: {
        withPassword: {
          attributes: { include: ["password"] },
        },
      },
35
    }
Choi Ga Young's avatar
Choi Ga Young committed
36
37
38
39
40
41
42
43
44
45
46
  );

  User.beforeSave(async (user) => {
    // if (!user.changed("password")) {
    //   return;
    // }
    if (user.password) {
      const hashedPassword = await bcrypt.hash(user.password, 10);
      user.password = hashedPassword;
    }
  });
47
48
49
50
51
52
53
54
55

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

Choi Ga Young's avatar
Choi Ga Young committed
56
57
58
59
60
  return User
};


export default UserModel;