From df998b4304aa3b4ac7948ba82a2a29f343912fc6 Mon Sep 17 00:00:00 2001 From: karishmas6 Date: Tue, 24 Sep 2024 17:23:53 +0530 Subject: [PATCH] feat: create User model --- server/src/models/User.ts | 58 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 server/src/models/User.ts diff --git a/server/src/models/User.ts b/server/src/models/User.ts new file mode 100644 index 00000000..82909785 --- /dev/null +++ b/server/src/models/User.ts @@ -0,0 +1,58 @@ +import { DataTypes, Model, Optional } from 'sequelize'; +import bcrypt from 'bcrypt'; +import sequelize from '../db/config'; + +interface UserAttributes { + id: number; + email: string; + password: string; +} + +// Optional fields for creating a new user +interface UserCreationAttributes extends Optional {} + +class User extends Model implements UserAttributes { + public id!: number; + public email!: string; + public password!: string; + + public async isValidPassword(password: string): Promise { + return bcrypt.compare(password, this.password); + } +} + +User.init( + { + id: { + type: DataTypes.INTEGER.UNSIGNED, + autoIncrement: true, + primaryKey: true, + }, + email: { + type: DataTypes.STRING, + allowNull: false, + unique: true, + validate: { + isEmail: true, + }, + }, + password: { + type: DataTypes.STRING, + allowNull: false, + }, + }, + { + sequelize, + tableName: 'user', + hooks: { + beforeCreate: async (user: User) => { + if (user.password) { + const salt = await bcrypt.genSalt(10); + user.password = await bcrypt.hash(user.password, salt); + } + }, + }, + } +); + +export default User;