-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver-2.js
More file actions
134 lines (116 loc) · 3.45 KB
/
Copy pathserver-2.js
File metadata and controls
134 lines (116 loc) · 3.45 KB
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
'use strict';
/**
* Step 2
* - Create User with plain-text UN/PW and store in DB
* - Update Basic Strategy to finduser and compare
*/
require('dotenv').config();
const express = require('express');
const bodyParser = require('body-parser');
const passport = require('passport');
const BasicStrategy = require('passport-http').BasicStrategy;
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
const app = express();
app.use(bodyParser.json());
// ===== Define UserSchema & UserModel =====
const UserSchema = new mongoose.Schema({
firstName: {type: String, default: ''},
lastName: {type: String, default: ''},
username: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true
}
});
UserSchema.methods.apiRepr = function() {
return {
id: this._id,
username: this.username,
firstName: this.firstName,
lastName: this.lastName
};
};
UserSchema.methods.validatePassword = function(password) {
return password === this.password;
};
const UserModel = mongoose.model('User', UserSchema);
// ===== Define and create basicStrategy =====
const basicStrategy = new BasicStrategy(function(username, password, done) {
UserModel
.findOne({ username })
.then(user => {
if (!user) {
return Promise.reject({
reason: 'LoginError',
message: 'Incorrect username',
location: 'username'
});
}
const isValid = user.validatePassword(password);
if (!isValid) {
return Promise.reject({
reason: 'LoginError',
message: 'Incorrect password',
location: 'password'
});
}
return done(null, user);
}).catch(err => {
console.log(err);
if (err.reason === 'LoginError') {
return done(null, false);
}
return done(err);
});
});
passport.use(basicStrategy);
const authenticate = passport.authenticate('basic', {session: false});
// ===== Protected endpoint =====
app.get('/api/protected', authenticate, function (req, res) {
// res.send(`Hello, ${req.user.username}. <br>Details: ${req.user}`);
res.send(`Hello, ${req.user.username}. <br>Details: ${JSON.stringify(req.user.apiRepr())}`);
});
// ===== Public endpoint =====
app.get('/api/public', function (req, res) {
res.send( 'Hello World!' );
});
// ===== Post '/users' endpoint to save a new User =====
// saves a user with plain-text password to the DB
app.post('/api/users', jsonParser, function(req, res) {
// NOTE: validation removed for brevity
let {username, password, firstName, lastName} = req.body;
return UserModel
.find({username})
.count()
.then(count => {
if (count > 0) {
return Promise.reject({
code: 422,
reason: 'ValidationError',
message: 'Username already taken',
location: 'username'
});
}
return UserModel.create({username, password, firstName, lastName});
})
.then(user => {
return res.status(201).json(user.apiRepr());
})
.catch(err => {
if (err.reason === 'ValidationError') {
return res.status(err.code).json(err);
}
res.status(500).json({code: 500, message: 'Internal server error'});
});
});
mongoose.connect(process.env.DATABASE_URL, {useMongoClient: true})
.then(() => {
app.listen(process.env.PORT || 8080, () => {
console.log(`app listening on port ${process.env.PORT || 8080}`);
});
});