-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
210 lines (173 loc) · 5.66 KB
/
server.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
// load the express package and create our app
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/test'); // connect to our database
var Schema = mongoose.Schema;
var User = require('./app/models/user');
var morgan = require('morgan');
var port = process.env.PORT || 8080;
var jwt = require('jsonwebtoken');
//secret string not really though since github
var superSecret = 'ilovescotchscotchyscotchscotch';
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
// configure our app to handle CORS requests
app.use(function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type, \
Authorization');
next();
});
//log all requests to the console
app.use(morgan('dev'));
// ROUTES FOR OUR API
// =============================
// basic route for the home page
app.get('/', function (req, res) {
res.send('Welcome to the home page!');
});
// get an instance of the express router
var apiRouter = express.Router();
// route for authenticating users
apiRouter.post('/authenticate', function (req, res) {
// find the user
// select the name username and password explicitly
User.findOne({
username: req.body.username
}).select('name username password').exec(function (err, user) {
if (err) throw err;
// no user with that username was found
if (!user) {
res.json({
success: false,
message: 'Authentication failed. User not found.'
});
} else if (user) {
// check if password matches
var validPassword = user.comparePassword(req.body.password);
if (!validPassword) {
res.json({
success: false,
message: 'Authentication failed. Wrong password.'
});
} else {
// if user is found and password is right
// create a token
var token = jwt.sign({
name: user.name,
username: user.username
}, superSecret, {
expiresInMinutes: 1440 // expires in 24 hours
});
// return the information including token as JSON
res.json({
success: true,
message: 'Enjoy your token!',
token: token
});
}
}
});
});
// MIDDLEWARE
apiRouter.use(function (req, res, next) {
//do logging
console.log("Someone just came to the app!");
//TODO: Add authenticating users here
next();
});
// test route to make sure everything is working
// accessed at GET http://localhost:8080/api
apiRouter.get('/', function (req, res) {
res.json({
message: 'hooray! welcome to our api!'
});
});
apiRouter.route("/users")
// create a user (accessed at POST http://localhost:8080/api/users)
.post(function (req, res) {
// create a new instance of the User model
var user = new User();
// set the users information (comes from the request)
user.name = req.body.name;
user.username = req.body.username;
user.password = req.body.password;
// save the user and check for errors
user.save(function (err) {
if (err) {
// duplicate entry
if (err.code == 11000)
return res.json({
success: false,
message: 'A user with that username already exists. '
});
else
return res.send(err);
}
res.json({
message: 'User created!'
});
});
})
// get all the users (accessed at GET http://localhost:8080/api/users)
.get(function (req, res) {
User.find(function (err, users) {
if (err) res.send(err);
//return the users
res.json(users);
});
});
apiRouter.route("/users/:user_id")
// get the user with that id
// (accessed at GET http://localhost:8080/api/users/:user_id)
.get(function (req, res) {
User.findById(req.params.user_id, function (err, user) {
if (err) res.send(err);
//return user
res.json(user);
});
})
//update the user with this id
//(accessed at PUT http://localhost:8080/api/users/:user_id)
.put(function (req, res) {
User.findById(req.params.user_id, function (err, user) {
if (err) res.send(err);
// update the users info only if its new
if (req.body.name) user.name = req.body.name;
if (req.body.username) user.username = req.body.username;
if (req.body.password) user.password = req.body.password;
//save the user
user.save(function (err) {
if (err) res.send(err);
//return a message
res.json({
message: "User updated!"
});
});
});
})
//delete user with this id
//(accessed at DELETE http://localhost:8080/api/users/:user_id)
.delete(function (req, res) {
User.remove({
_id: req.params.user_id
}, function (err, user) {
if (err) return res.send(err);
res.json({
message: 'Successfully deleted'
});
});
});
// more routes for our API will happen here
// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
app.use('/api', apiRouter);
// START THE SERVER
// ===============================
app.listen(port);
console.log('Magic happens on port ' + port);