user.model.js 1.88 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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: {
Kim, Subin's avatar
Kim, Subin committed
17
18
19
20
                type: DataTypes.STRING
            },
            name: {
                type: DataTypes.STRING
21
            },
한규민's avatar
한규민 committed
22
            email: {
Kim, Subin's avatar
Kim, Subin committed
23
                type: DataTypes.STRING
한규민's avatar
한규민 committed
24
            },
25
            nickname: {
Kim, Subin's avatar
Kim, Subin committed
26
                type: DataTypes.STRING
27
28
            },
            birth: {
Kim, Subin's avatar
Kim, Subin committed
29
                type: DataTypes.STRING
30
31
            },
            phoneNumber: {
한규민's avatar
한규민 committed
32
33
34
                type: DataTypes.STRING
            },
            password: {
Kim, Subin's avatar
Kim, Subin committed
35
                type: DataTypes.STRING
36
            },
Kim, Subin's avatar
Kim, Subin committed
37
38
39
            img: {
                type: DataTypes.STRING
            }
40
41
42
43
        },
        {
            timestamps: true,
            freezeTableName: true,
한규민's avatar
한규민 committed
44
45
46
47
48
49
50
51
52
            tableName: "users",
            defaultScope: {
                attributes: { exclude: ["password"] },
            },
            scopes: {
                withPassword: {
                    attributes: { include: ["password"] },
                },
            },
53
54
        }
    );
한규민's avatar
한규민 committed
55
56
57
58
59
60
61
62
63
64
65

    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
66

한규민's avatar
한규민 committed
67
68
69
70
71
72
73
74
    User.prototype.comparePassword = async function (plainPassword) {
        const passwordMatch = await bcrypt.compare(
            plainPassword,
            this.password
        );
        return passwordMatch;
    };

75
76
77
78
    return User
};

export default UserModel