forked from stripe/stripe-connect-rocketrides
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpilot.js
81 lines (68 loc) · 2.27 KB
/
pilot.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
'use strict';
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const bcrypt = require('bcrypt');
const Ride = require('./ride');
// Use native promises.
mongoose.Promise = global.Promise;
// Define the Pilot schema.
const PilotSchema = new Schema({
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
firstName: String,
lastName: String,
address: String,
postalCode: String,
city: String,
country: { type: String, default: 'US' },
created: { type: Date, default: Date.now },
rocket: {
model: String,
license: String,
color: String
},
// Stripe account ID to send payments obtained with Stripe Connect.
stripeAccountId: String
});
// List rides of the past week for the pilot.
PilotSchema.methods.listRecentRides = function() {
const weekAgo = Date.now() - (7*24*60*60*1000);
return Ride.find({ pilot: this, created: { $gte: weekAgo } })
.populate('passenger')
.sort({ created: -1 })
.exec();
};
// Generate a password hash (with an auto-generated salt for simplicity here).
PilotSchema.methods.generateHash = function(password) {
return bcrypt.hashSync(password, 8);
};
// Check if the password is valid by comparing with the stored hash.
PilotSchema.methods.validatePassword = function(password) {
return bcrypt.compareSync(password, this.password);
};
// Get the latest pilot.
PilotSchema.statics.getLatest = function() {
return Pilot.findOne()
.sort({ created: -1 })
.exec();
};
// Make sure the email has not been used.
PilotSchema.path('email').validate(function (email, callback) {
const Pilot = mongoose.model('Pilot');
// Check only when it is a new pilot or when the email has been modified.
if (this.isNew || this.isModified('email')) {
Pilot.find({ email: email }).exec(function (err, pilots) {
callback(!err && pilots.length === 0);
});
} else callback(true);
}, 'This email already exists. Please try to login instead.');
// Pre-save hook making sure the password is hashed before being stored.
PilotSchema.pre('save', function (next) {
if (!this.isModified('password')) {
return next();
}
this.password = this.generateHash(this.password);
next();
});
const Pilot = mongoose.model('Pilot', PilotSchema);
module.exports = Pilot;