-
Notifications
You must be signed in to change notification settings - Fork 82
/
UserCollection.ts
75 lines (69 loc) · 2.42 KB
/
UserCollection.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
import bcrypt from "bcrypt-nodejs";
import mongoose, { Model, Schema } from "mongoose";
import UserDocument, { ComparePasswordFunction } from "./UserDocument";
import storage, { CONTAINER_AVATAR } from "../../repository/storage";
import { getBlobNameFromUrl } from "../../repository/utils";
export const userSchema: Schema = new mongoose.Schema({
email: { type: String, unique: true },
password: String,
name: { type: String, unique: true },
gender: String,
address: String,
website: String,
avatarUrl: String,
preferences: {
type: Map,
of: String
},
OTP: String,
otpExpireTime: Date,
invitationCode: String
}, { timestamps: true });
/**
* Password hashing & Signing Url middleware.
*/
userSchema.pre("save", function save(next: any) {
const user: any = this;
// email cannot have capital character
if (user && user.email) {
user.email = user.email.toLowerCase();
}
// Stripe signing params for Avatar Url
if (user && user.avatarUrl) {
const sasAvatarUrl: string = user.avatarUrl;
user.avatarUrl = sasAvatarUrl.substring(0, sasAvatarUrl.indexOf("?"));
}
if (!user.isModified("password")) {
return next();
}
bcrypt.genSalt(10, (err: any, salt: any) => {
if (err) { return next(err); }
// tslint:disable-next-line:no-null-keyword
bcrypt.hash(user.password as string, salt, null, (err: mongoose.Error, hash: any) => {
if (err) {
return next(err);
}
user.password = hash;
next();
});
});
});
export const postFind = (user: UserDocument, next?: any) => {
// Add signing params for Avatar Url so that client can consume
if (user && user.avatarUrl) {
const avatarFilename: string = getBlobNameFromUrl(user.avatarUrl);
user.avatarUrl = `${user.avatarUrl}?${storage.generateSigningUrlParams(CONTAINER_AVATAR, avatarFilename)}`;
}
if (next) {
next();
}
};
userSchema.post("findOne", postFind);
const comparePassword: ComparePasswordFunction = function (this: any, candidatePassword, cb) {
bcrypt.compare(candidatePassword, this.password, (err: mongoose.Error, isMatch: boolean) => {
cb(err, isMatch);
});
};
userSchema.methods.comparePassword = comparePassword;
const UserCollection: Model<UserDocument> = mongoose.model("User", userSchema);
export default UserCollection;