-
Notifications
You must be signed in to change notification settings - Fork 349
/
Copy pathuser.js
196 lines (185 loc) · 5.12 KB
/
user.js
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
const crypto = require('crypto')
const jwt = require('jsonwebtoken')
const Sequelize = require('sequelize')
const { DataTypes, Op } = Sequelize
const config = require('../front/config')
module.exports = (sequelize) => {
let User = sequelize.define(
'User',
{
username: {
type: DataTypes.STRING,
set(v) {
this.setDataValue('username', v.toLowerCase())
},
unique: {
msg: 'This username is taken.',
},
validate: {
min: {
args: 3,
msg: 'Username must start with a letter, have no spaces, and be at least 3 characters.',
},
max: {
args: 40,
msg: 'Username must start with a letter, have no spaces, and be at less than 40 characters.',
},
is: {
args: /^[A-Za-z][A-Za-z0-9-_]+$/i, // must start with letter and only have letters, numbers, dashes
msg: 'Username must start with a letter, have no spaces, and be 3 - 40 characters.',
},
},
},
email: {
type: DataTypes.STRING,
set(v) {
this.setDataValue('email', v.toLowerCase())
},
unique: {
msg: 'This email is taken.',
},
validate: {
isEmail: {
msg: 'This email does not seem valid.',
},
max: {
args: 254,
msg: 'This email is too long, the maximum size is 254 characters.',
},
},
},
bio: DataTypes.STRING,
image: DataTypes.STRING,
hash: DataTypes.STRING(1024),
salt: DataTypes.STRING,
ip: {
type: DataTypes.STRING,
allowNull: true,
},
},
{
indexes: [{ fields: ['username'] }, { fields: ['email'] }],
}
)
User.prototype.generateJWT = function () {
let today = new Date()
let exp = new Date(today)
exp.setDate(today.getDate() + 60)
return jwt.sign(
{
id: this.id,
username: this.username,
exp: parseInt(exp.getTime() / 1000),
},
config.secret
)
}
User.prototype.toAuthJSON = function () {
return {
username: this.username,
email: this.email,
token: this.generateJWT(),
bio: this.bio === undefined ? '' : this.bio,
image: this.image === undefined ? '' : this.image,
}
}
User.prototype.toProfileJSONFor = async function (user) {
let data = {
username: this.username,
bio: this.bio === undefined ? '' : this.bio,
// This one returns the default image if empty, unlike toAuthJSON which returns nothing.
// Therefore, this one is what you want when viewing profiles, and toAuthJSON is what
// you want when loading profile settings forms for which we want an empty field.
image:
this.image ||
'https://static.productionready.io/images/smiley-cyrus.jpg',
following: user ? await user.hasFollow(this.id) : false,
}
return data
}
User.prototype.findAndCountArticlesByFollowed = async function (
offset,
limit
) {
return sequelize.models.Article.findAndCountAll({
offset: offset,
limit: limit,
subQuery: false,
order: [['createdAt', 'DESC']],
include: [
{
model: sequelize.models.User,
as: 'author',
required: true,
include: [
{
model: sequelize.models.UserFollowUser,
on: {
followId: { [Op.col]: 'author.id' },
},
attributes: [],
where: { userId: this.id },
},
],
},
],
})
}
User.prototype.findAndCountArticlesByFollowedToJson = async function (
offset,
limit
) {
const { count: articlesCount, rows: articles } =
await this.findAndCountArticlesByFollowed(offset, limit)
const articlesJson = await Promise.all(
articles.map((article) => {
return article.toJson(this)
})
)
return {
articles: articlesJson,
articlesCount,
}
}
User.prototype.getArticleCountByFollowed = async function () {
return (
await User.findByPk(this.id, {
subQuery: false,
attributes: [
[
Sequelize.fn('COUNT', Sequelize.col('follows.authoredArticles.id')),
'count',
],
],
include: [
{
model: User,
as: 'follows',
attributes: [],
through: { attributes: [] },
include: [
{
model: sequelize.models.Article,
as: 'authoredArticles',
attributes: [],
},
],
},
],
})
).dataValues.count
}
User.validPassword = function (user, password) {
let hash = crypto
.pbkdf2Sync(password, user.salt, 10000, 512, 'sha512')
.toString('hex')
return user.hash === hash
}
User.setPassword = function (user, password) {
user.salt = crypto.randomBytes(16).toString('hex')
user.hash = crypto
.pbkdf2Sync(password, user.salt, 10000, 512, 'sha512')
.toString('hex')
}
return User
}