This repository was archived by the owner on Oct 9, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
220 lines (192 loc) · 6.74 KB
/
Copy pathserver.js
File metadata and controls
220 lines (192 loc) · 6.74 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
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
/*
Run with node --inspect server.js
*/
// Express Setup
const express = require('express');
const bodyParser = require("body-parser");
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static('public'));
// Knex Setup
const env = process.env.NODE_ENV || 'development';
const config = require('./knexfile')[env];
const knex = require('knex')(config);
// bcrypt setup
let bcrypt = require('bcrypt');
const saltRounds = 10;
const jwt = require('jsonwebtoken');
let jwtSecret = process.env.jwtSecret;
if (jwtSecret === undefined) {
console.log("You need to define a jwtSecret environment variable to continue.");
knex.destroy();
process.exit();
}
const verifyToken = (req, res, next) => {
const token = req.headers['authorization'];
if (!token)
return res.status(403).send({ error: 'No token provided.' });
jwt.verify(token, jwtSecret, function(err, decoded) {
if (err)
return res.status(500).send({ error: 'Failed to authenticate token.' });
req.userID = decoded.id;
next();
});
}
app.get('/api/me', verifyToken, (req,res) => {
knex('authors').where('id',req.userID).first().select('username','name','id').then(author => {
res.status(200).json({author:author});
}).catch(error => {
res.status(500).json({ error });
});
});
// Login
app.post('/api/login', (req, res) => {
if (!req.body.username || !req.body.password)
return res.status(400).send();
knex('authors').where('username',req.body.username).first().then(author => {
if (author === undefined) {
res.status(403).send("Invalid credentials");
throw new Error('abort');
}
return [bcrypt.compare(req.body.password, author.hash),author];
}).spread((result,author) => {
if (result) {
let token = jwt.sign({ id: author.id }, jwtSecret, {
expiresIn: 86400 // expires in 24 hours
});
res.status(200).json({author:{username:author.username,name:author.name,id:author.id},token:token});
} else {
res.status(403).send("Invalid credentials");
}
return;
}).catch(error => {
if (error.message !== 'abort') {
console.log(error);
res.status(500).json({ error });
}
});
});
// Create an author
app.post('/api/authors', (req, res) => {
if (!req.body.username || !req.body.password || !req.body.name || !req.body.gender || !req.body.location)
return res.status(400).send();
knex('authors').where('username',req.body.username).first().then(author => {
if (author !== undefined) {
res.status(403).send("Username already exists");
throw new Error('abort');
}
return bcrypt.hash(req.body.password, saltRounds);
}).then(hash => {
return knex('authors').insert({hash: hash, username:req.body.username,
name:req.body.name, gender:req.body.gender, location:req.body.location});
}).then(ids => {
return knex('authors').where('id',ids[0]).first().select('username','name','id');
}).then(author => {
let token = jwt.sign({ id: author.id }, jwtSecret, {
expiresIn: 86400 // expires in 24 hours
});
res.status(200).json({author:author,token:token});
return;
}).catch(error => {
if (error.message !== 'abort') {
console.log(error);
res.status(500).json({ error });
}
});
});
// Get all stories for an author
app.get('/api/authors/:id/stories', (req, res) => {
let id = parseInt(req.params.id);
if (id === NaN) {
res.status(500).json({ error });
}
knex('authors').join('stories','authors.id','stories.user_id')
.where('authors.id',id)
.orderBy('stories.id', 'desc')
.select('title','link','status','genre','username','name', 'stories.id').then(stories => {
res.status(200).json({stories:stories});
}).catch(error => {
console.log(error);
res.status(500).json({ error });
});
});
// Get all updates for an author
app.get('/api/authors/:id/updates', (req, res) => {
let id = parseInt(req.params.id);
knex('updates').join('authors','authors.id','updates.user_id')
.join('stories', 'stories.id','updates.story_id')
.where('authors.id',id)
.orderBy('updates.updated', 'desc')
.select('stories.title','updates.old','updates.new','updates.updated').then(updates => {
res.status(200).json({updates:updates});
}).catch(error => {
res.status(500).json({ error });
});
});
// Add a story for an author
app.post('/api/authors/:id/stories', (req, res) => {
let id = parseInt(req.params.id);
knex('authors').where('id',id).first().then(author => {
return knex('stories').insert({user_id: id, title:req.body.title, link:req.body.link, status:req.body.status,
genre:req.body.genre});
}).then(ids => {
return knex('stories').where('id',ids[0]).first();
}).then(story => {
res.status(200).json({story:story});
return;
}).catch(error => {
console.log(error);
res.status(500).json({ error });
});
});
// Delete a story
app.delete('/api/authors/:authorid/stories/:storyid', (req, res) => {
let storyid = parseInt(req.params.storyid);
let authorid = parseInt(req.params.authorid);
knex('authors').where('id',authorid).first().then(author => {
return knex('stories').where('id',storyid).first();
}).then(story => {
return knex('updates').where({'story_id':storyid}).del();
}).then(story => {
return knex('stories').where({'id':storyid,user_id:authorid}).first().del();
}).then(ids => {
res.sendStatus(200);
return;
}).catch(error => {
console.log(error);
res.status(500).json({ error });
});
})
// Update a story and add an update entry
app.post('/api/authors/:authorid/stories/:storyid', (req, res) => {
let storyid = parseInt(req.params.storyid);
let authorid = parseInt(req.params.authorid);
let oldval = '';
knex('stories').where('id',storyid).first().then(story => { // Check if story exists
if (story === undefined) {
res.status(403).send("Cannot update story; story does not exist");
throw new Error('abort');
}
else if (story.user_id !== authorid) { // Check if author owns it
res.status(403).send("Cannot update story; you do not own it!");
throw new Error('abort');
}
else {
oldval = story.status;
return story;
}
}).then(story => {
return knex('stories').where('id', storyid).update({status:req.body.newStatus});
}).then(story => {
return knex('updates').insert({type: 'status', old: oldval, new: req.body.newStatus, updated: new Date(),
user_id: authorid, story_id: storyid});
}).then (story => {
res.status(200).json({story:story});
return;
}).catch(error => {
console.log(error);
res.status(500).json({ error });
});
});
app.listen(3000, () => console.log('Server listening on port 3000!'));