user.model.js 1.74 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
            },
한규민's avatar
context    
한규민 committed
31
32
33
            roleId: {
                type: DataTypes.INTEGER
            }
34
35
36
37
        },
        {
            timestamps: true,
            freezeTableName: true,
한규민's avatar
한규민 committed
38
39
40
41
42
43
44
45
46
            tableName: "users",
            defaultScope: {
                attributes: { exclude: ["password"] },
            },
            scopes: {
                withPassword: {
                    attributes: { include: ["password"] },
                },
            },
47
48
        }
    );
한규민's avatar
한규민 committed
49
50
51
52
53
54
55
56
57
58
59

    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
60

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

69
70
71
72
    return User
};

export default UserModel