-
Notifications
You must be signed in to change notification settings - Fork 0
/
user.model.ts
91 lines (80 loc) · 2.34 KB
/
user.model.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import * as bcrypt from 'bcryptjs';
import { DataTypes, ModelDefined, Optional } from 'sequelize';
import { DbCommonAttributes } from '../interfaces/common.db';
import sequelize from '../sequelize';
import { BannedUser } from './banned-user.model';
import { CreatedCourses } from './created-courses.model';
import { Course, JwtAuth, Like, Role } from './index';
import { StudentCourses } from './student-courses.model';
export enum UserRoles {
Student = 'student',
Teacher = 'teacher',
Admin = 'admin',
}
export interface UserAttributes extends DbCommonAttributes {
username: string;
email: string;
password: string;
role: UserRoles | number;
firstName?: string | null;
lastName?: string | null;
}
type UserCreationAttributes = Optional<UserAttributes, 'id'>;
export const User: ModelDefined<UserAttributes, UserCreationAttributes> = sequelize.define('user', {
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true,
},
username: {
type: DataTypes.STRING,
unique: true,
allowNull: false,
},
email: {
type: DataTypes.STRING,
unique: true,
allowNull: false,
},
firstName: {
type: DataTypes.STRING,
allowNull: true,
},
lastName: {
type: DataTypes.STRING,
allowNull: true,
},
password: {
type: DataTypes.STRING,
allowNull: false,
},
});
User.beforeCreate(async (user: any) => {
// hash password
const salt = await bcrypt.genSalt(10);
const passwordHash = await bcrypt.hash(user.password, salt);
user.password = passwordHash;
// find and set role id
const role: any = await Role.findOne({
raw: true,
where: {
role: user.role,
},
});
if (role) {
user.role = role.id;
}
});
User.hasMany(BannedUser, {
onUpdate: 'CASCADE',
onDelete: 'CASCADE',
});
BannedUser.belongsTo(User);
User.hasMany(Like, { onUpdate: 'CASCADE', onDelete: 'CASCADE' });
Like.belongsTo(User);
User.belongsToMany(Course, { through: StudentCourses });
Course.belongsToMany(User, { through: StudentCourses });
User.belongsToMany(Course, { through: CreatedCourses });
Course.belongsToMany(User, { through: CreatedCourses });
User.hasMany(JwtAuth, { onUpdate: 'CASCADE', onDelete: 'CASCADE' });
JwtAuth.belongsTo(User);