-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
293 lines (237 loc) · 7.91 KB
/
index.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
290
291
292
293
var express = require('express');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var busboy = require('connect-busboy');
var mysql = require('mysql');
var fs = require('fs-extra');
var uuid = require('node-uuid');
// var path = require('path');
// Authentication
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var session = require("express-session");
var publicDirectory = __dirname + "/public";
var uploadDirectory = "/uploads/";
var imageUploadDirectory = publicDirectory + uploadDirectory;
// Create uploads directory if not exists
fs.mkdirp(imageUploadDirectory, function (err) {
if (err)
return console.error(err);
console.log("Directory: " + imageUploadDirectory + " created.");
});
var server = express();
server.use(busboy());
server.use(bodyParser.urlencoded());
server.use(bodyParser.json());
server.use(session({
secret: '9bf8ea38-fb8a-11e3-8cf1-782bcbe8d576'
}));
// Initialize passport
server.use(passport.initialize());
// Set up the passport session
server.use(passport.session());
// Serve static files in public directory
server.use(express.static(publicDirectory));
// Create MySQL Connection Pool
var connectionPool = mysql.createPool({
host : "localhost",
user : "root",
password : "root",
database : "onlinegallery"
});
// Get user by id from db
function getUserById(id, done) {
connectionPool.getConnection(function (err, connection) {
if (err) {
console.error("Connection error: ", err);
return done(err);
}
var lookupQuery = "select id, username, password from user where id=?";
connection.query(lookupQuery, [id], function (err, result) {
connection.release();
if (err)
return done(err, null);
var userInfo = result[0];
if (!userInfo)
return done(null, null);
return done(null, {id:userInfo.id, username:userInfo.username});
});
});
}
// This is how a user gets serialized
passport.serializeUser(function(user, done) {
done(null, user.id);
});
// This is how a user gets deserialized
passport.deserializeUser(function(id, done) {
// Look the user up in the database and return the user object
return getUserById(id, function (err, user) {
if (err)
return done(err);
if (!user)
return done(null, false, {success: false, message: "No user found"});
return done(err, user);
});
});
// Lookup a user in our database
var lookupUser = function(username, password, done) {
var lookupQuery = "select id, username, password from user where username=?";
connectionPool.getConnection(function (err, connection) {
if (err) {
console.error("Connection error: ", err);
return done(err);
}
connection.query(lookupQuery, [username], function (err, result) {
connection.release();
if (err)
return done(err);
var userInfo = result[0];
if (!userInfo)
return done (null, false, {success: false, message: "No user exists"});
else if (password === result[0]["password"])
return done (null, {id:userInfo.id, username:userInfo.username});
else
return done (null, false, {success: false, message: "Wrong password"});
});
});
};
// Use local strategy for authenticating users
passport.use('local', new LocalStrategy(lookupUser));
// POST /signup
var signupRoute = function (req, res, next) {
var username = req.body.username;
var password = req.body.password;
if (!username || !password) {
return res.json({success: false, message:"Invalid fields"});
}
connectionPool.getConnection(function (err, connection) {
if (err)
return next(err);
var lookupQuery = "select id, username, password from user where username = ?";
connection.query(lookupQuery, [username], function (err, result) {
if (err)
return next(err);
if (result.length > 0) {
connection.release();
return res.json({success: false, message: "User " + username + " already exists"});
}
else {
var insertQuery = "insert into user set username = ?, password = ?";
connection.query(insertQuery, [username, password], function (err, result) {
connection.release();
if (err)
return next (err);
return getUserById(result.insertId, function (err, user) {
// Create user directory
var directory = imageUploadDirectory + user.id;
fs.mkdir(directory, null);
return performLogin(req, res, user, next);
});
});
}
});
});
};
// Login the user
function performLogin (req, res, user, next) {
// Log the user in!
req.logIn(user, function(err) {
if (err) {
return next(err);
}
console.log(req.isAuthenticated());
req.session.user_id = req.user.id;
if(user.username) {
return res.json({ success: true, message: 'Welcome ' + user.username + "!"});
}
return res.json({ success: true, message: 'Welcome!'});
});
}
// POST /login
var loginRoute = function(req, res, next) {
console.log("Got login request");
// The local login strategy
passport.authenticate('local', function (err, user) {
if (err) {
return next(err);
}
// Technically, the user should exist at this point, but if not, check
if(!user) {
return res.json(200, {success: false, message:"Please check your details and try again."});
}
return performLogin(req, res, user, next);
})(req, res, next);
};
// POST /photos
var postPhotosRoute = function (req, res, next) {
req.pipe(req.busboy);
req.busboy.on('file', function (fieldname, file, filename) {
if (!file) {
return res.json({success: false, message: "There was an error uploading the image"});
}
var imageName = filename;//uuid.v1() + path.extname(filename);
var directory = imageUploadDirectory + req.session.user_id;
var newPath = directory + "/" + imageName;
var fileStream = fs.createWriteStream(newPath);
if (!fileStream)
return res.json({success: false, message: "Cannot create file on server. Please try again."});
file.pipe(fileStream);
fileStream.on('close', function () {
connectionPool.getConnection(function (err, connection) {
if (err)
return next(err);
var insertQuery = "insert into photos set userid = ?, imagename = ?";
connection.query(insertQuery, [req.session.user_id, imageName], function (err, result) {
connection.release();
if (err)
return next(err);
return res.json({success: true, message: "Image saved successfully: " + imageName});
});
});
});
});
}
// GET /photos
var getPhotosRoute = function (req, res, next) {
connectionPool.getConnection(function (err, connection) {
if (err)
return next(err);
var query = "select imagename from photos where userid = ?";
connection.query(query, [req.session.user_id], function (err, result) {
if (err)
return next(err);
connection.release();
var images = [];
for (var idx in result) {
// Create image url based on currently logged in user
var imageURL = req.protocol + "://" + req.get('Host') + uploadDirectory + req.session.user_id + "/" + result[idx].imagename;
images.push(imageURL);
};
return res.json({success: true, message: images});
});
});
};
// GET /hello
// Just for testing purposes
var helloRoute =function(req, res, next) {
if(req.user) {
return res.send("Hello " + req.user.username);
} else {
return res.send("Hello unauthenticated user");
}
};
// Ensure Authentication for request middleware
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) { return next() };
res.json(401, {succes: false, message: "Please login again", error: "Invalid request"});
};
// Routes
server.post('/signup', signupRoute);
server.post('/login', loginRoute);
server.get('/hello', helloRoute);
server.post('/photos', ensureAuthenticated, postPhotosRoute);
server.get('/photos', ensureAuthenticated, getPhotosRoute);
// Launch the server
server.listen(5000, function() {
console.log('Server running at port 5000');
});