user.model.js 1.81 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: {
한규민's avatar
한규민 committed
17
                type: DataTypes.STRING
18
            },
한규민's avatar
한규민 committed
19
            email: {
한규민's avatar
한규민 committed
20
                type: DataTypes.STRING
한규민's avatar
한규민 committed
21
            },
22
            nickname: {
한규민's avatar
한규민 committed
23
                type: DataTypes.STRING
24
25
            },
            birth: {
한규민's avatar
한규민 committed
26
                type: DataTypes.STRING
27
28
            },
            phoneNumber: {
한규민's avatar
한규민 committed
29
30
31
                type: DataTypes.STRING
            },
            password: {
한규민's avatar
한규민 committed
32
                type: DataTypes.STRING
33
            },
한규민's avatar
한규민 committed
34
35
36
            img: {
                type: DataTypes.STRING
            }
37
38
39
40
        },
        {
            timestamps: true,
            freezeTableName: true,
한규민's avatar
한규민 committed
41
42
43
44
45
46
47
48
49
            tableName: "users",
            defaultScope: {
                attributes: { exclude: ["password"] },
            },
            scopes: {
                withPassword: {
                    attributes: { include: ["password"] },
                },
            },
50
51
        }
    );
한규민's avatar
한규민 committed
52
53
54
55
56
57
58
59
60
61
62

    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
63

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

72
73
74
75
    return User
};

export default UserModel