-
Notifications
You must be signed in to change notification settings - Fork 11
/
app.js
289 lines (244 loc) · 6.29 KB
/
app.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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
/**
* Module dependencies.
*/
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var session = require('express-session');
var methodOverride = require('method-override')
var sass = require('node-sass');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var crypto = require('crypto');
var bcrypt = require('bcrypt');
/**
* Mongoose configuration
*/
mongoose.connect('localhost');
mongoose.connection.on('error', function() {
console.log('← MongoDB Connection Error →');
});
/**
* Person Schema.
*
* @type {mongoose.Schema}
*/
var personSchema = new mongoose.Schema({
name: String,
age: Number
});
/**
* Person mongoose model.
*/
var Person = mongoose.model('Person', personSchema);
/**
* User Schema.
*
* @type {mongoose.Schema}
*/
var userSchema = new mongoose.Schema({
username: { type: String, unique: true },
email: { type: String, unique: true },
password: String,
token: String
});
/**
* User Schema pre-save hooks.
* It is used for hashing and salting user's password and token.
*/
userSchema.pre('save', function(next) {
var user = this;
var hashContent = user.username + user.password + Date.now() + Math.random();
user.token = crypto.createHash('sha1').update(hashContent).digest('hex');
if (!user.isModified('password')) return next();
bcrypt.genSalt(5, function(err, salt) {
if (err) return next(err);
bcrypt.hash(user.password, salt, function(err, hash) {
if (err) return next(err);
user.password = hash;
next();
});
});
});
/**
* Helper method for comparing user's password input with a
* hashed and salted password stored in the database.
*/
userSchema.methods.comparePassword = function(candidatePassword, cb) {
bcrypt.compare(candidatePassword, this.password, function(err, isMatch) {
if(err) return cb(err);
cb(null, isMatch);
});
};
/**
* User mongoose model.
*/
var User = mongoose.model('User', userSchema);
/**
* Passport setup.
*/
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
User.findById(id, function (err, user) {
done(err, user);
});
});
passport.use(new LocalStrategy(function(username, password, done) {
User.findOne({ username: username }, function(err, user) {
if (err) return done(err);
if (!user) return done(null, false);
user.comparePassword(password, function(err, isMatch) {
if (err) return done(err);
if (isMatch) return done(null, user);
return done(null, false);
});
});
}));
var app = express();
app.use(favicon(__dirname + '/public/favicon.png'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(methodOverride());
app.use(cookieParser());
app.use(session({
secret: 'place secret here',
resave: false,
saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(sass.middleware({ src: path.join(__dirname, 'public') }));
app.use(express.static(path.join(__dirname, 'public')));
/**
* Find person by id.
*
* @param {string} id
* @returns {object} person
*/
app.get('/api/people/:id', function(req, res, next) {
Person.findById(req.params.id, function(err, person) {
if (err) return next(err);
res.send({ person: person });
});
});
/**
* Find all people.
*
* @returns {object} person
*/
app.get('/api/people', function(req, res, next) {
Person.find(function(err, people) {
if (err) return next(err);
res.send({ person: people });
});
});
/**
* Update person by id.
*
* @param {string} id
* @returns {object} person
*/
app.put('/api/people/:id', function(req, res, next) {
Person.findByIdAndUpdate(req.params.id, req.body.person, function(err, person) {
if (err) return next(err);
res.send({ person: person });
});
});
/**
* Create new person.
*
* @param {object} person
* @returns {object} person
*/
app.post('/api/people', function(req, res, next) {
var person = new Person(req.body.person);
person.save(function(err) {
if (err) return next(err);
res.send({ person: person });
});
});
/**
* Delete person by id.
*
* @param {string} id
* @returns 200 OK
*/
app.delete('/api/people/:id', function(req, res, next) {
Person.findById(req.params.id).remove(function(err) {
if (err) return next(err);
res.send(200);
});
});
/**
* POST /token
* Sign in using email and password.
* @param {string} username
* @param {string} password
*/
app.post('/token', function(req, res, next) {
passport.authenticate('local', function(err, user) {
if (err) return next(err);
if (user) res.send({ access_token: user.token });
else res.send(404, 'Incorrect username or password.');
})(req, res, next);
});
/**
* POST /signup
* Create a new local account.
* @param {string} username
* @param {string} email
* @param {string} password
* @param {string} confirmPassword
*/
app.post('/signup', function(req, res, next) {
if (!req.body.username) {
return res.send(400, 'Username cannot be blank.');
}
if (!req.body.email) {
return res.send(400, 'Email cannot be blank.');
}
if (!req.body.password) {
return res.send(400, 'Password cannot be blank.');
}
if (req.body.password !== req.body.confirmPassword) {
return res.send(400, 'Passwords do not match.');
}
var user = new User({
username: req.body.username,
email: req.body.email,
password: req.body.password
});
user.save(function(err) {
if (err) return res.send(500, err.message);
res.send(200);
});
});
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.send(err);
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.send(err.message);
});
module.exports = app;