1 | var mongoose = require('mongoose')
|
2 | var crypto = require('crypto')
|
3 | var jwt = require('jsonwebtoken')
|
4 |
|
5 | var userSchema = new mongoose.Schema({
|
6 | email: {
|
7 | type: String,
|
8 | unique: true,
|
9 | required: true
|
10 | },
|
11 | emailVerified: {
|
12 | type: Boolean,
|
13 | required: false
|
14 | },
|
15 | firstName: {
|
16 | type: String,
|
17 | required: true
|
18 | },
|
19 | lastName: {
|
20 | type: String,
|
21 | required: true
|
22 | },
|
23 | middleName: {
|
24 | type: String,
|
25 | required: false
|
26 | },
|
27 | phone: {
|
28 | type: String,
|
29 | required: true
|
30 | },
|
31 | phoneVerified: {
|
32 | type: Boolean,
|
33 | required: false
|
34 | },
|
35 | hash: String,
|
36 | salt: String
|
37 | })
|
38 |
|
39 | userSchema.methods.setPassword = function(password){
|
40 | try {
|
41 | this.salt = crypto.randomBytes(16).toString('hex')
|
42 | this.hash = crypto.pbkdf2Sync(password, this.salt, 1000, 512, 'sha512').toString('hex')
|
43 | }
|
44 | catch(e) {
|
45 | console.log(e.message)
|
46 | }
|
47 | }
|
48 |
|
49 | userSchema.methods.validPassword = function(password) {
|
50 | try {
|
51 | var hash = crypto.pbkdf2Sync(password, this.salt, 1000, 512, 'sha512').toString('hex')
|
52 | return this.hash === hash
|
53 | }
|
54 | catch(e) {
|
55 | console.log(e.message)
|
56 | }
|
57 | }
|
58 |
|
59 | userSchema.methods.generateJwt = function() {
|
60 | try {
|
61 | var expiry = new Date()
|
62 | expiry.setDate(expiry.getDate() + 7)
|
63 |
|
64 | return jwt.sign({
|
65 | _id: this._id,
|
66 | email: this.email,
|
67 | fullName: this.fullName,
|
68 | phone: this.phone,
|
69 | exp: parseInt(expiry.getTime() / 1000),
|
70 | }, process.env.SESSION_SECRET);
|
71 | }
|
72 | catch(e) {
|
73 | console.log(e.message)
|
74 | }
|
75 | }
|
76 |
|
77 | mongoose.model('User', userSchema)
|