user.model.js 1.67 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
import bcrypt from "bcryptjs";
import Sequelize from "sequelize";
// import { ROLE_NAME } from "./role.model.js";

const { DataTypes } = Sequelize;

const UserModel = (sequelize) => {
    const User = sequelize.define(
        "user",
        {
            id: {
                type: DataTypes.INTEGER,
                primaryKey: true,
                autoIncrement: true,
            },
            userId: {
                type: DataTypes.STRING,
            },
            nickname: {
                type: DataTypes.STRING,
            },
            birth: {
한규민's avatar
한규민 committed
23
                type: DataTypes.STRING,
24
25
            },
            phoneNumber: {
한규민's avatar
한규민 committed
26
27
28
29
                type: DataTypes.STRING
            },
            password: {
                type: DataTypes.STRING,
30
31
32
33
34
            },
        },
        {
            timestamps: true,
            freezeTableName: true,
한규민's avatar
한규민 committed
35
36
37
38
39
40
41
42
43
            tableName: "users",
            defaultScope: {
                attributes: { exclude: ["password"] },
            },
            scopes: {
                withPassword: {
                    attributes: { include: ["password"] },
                },
            },
44
45
        }
    );
한규민's avatar
한규민 committed
46
47
48
49
50
51
52
53
54
55
56

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

        if (user.password) {
            const hashedPassword = await bcrypt.hash(user.password, 10);
            user.password = hashedPassword;
        }
    });
한규민's avatar
한규민 committed
57

한규민's avatar
한규민 committed
58
59
60
61
62
63
64
65
    User.prototype.comparePassword = async function (plainPassword) {
        const passwordMatch = await bcrypt.compare(
            plainPassword,
            this.password
        );
        return passwordMatch;
    };

66
67
68
69
    return User
};

export default UserModel