-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
426 lines (367 loc) · 13 KB
/
Copy pathserver.js
File metadata and controls
426 lines (367 loc) · 13 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
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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
/*Created by Exposure Team
---- Version 1/05/2020*/
//Declaring variables
//MongoDB
const MongoClient = require('mongodb').MongoClient;
const url = "mongodb://localhost:27017/exposure";
//Express
const express = require('express');
const session = require('express-session');
//BodyParser
const bodyParser = require('body-parser');
//Request
var request = require('request');
const app = express();
//Using sessions
app.use(session({ secret: 'example' }));
//Using body Parser
app.use(bodyParser.urlencoded({
extended: true
}));
//Setting the view engine to ejs
app.set('view engine', 'ejs');
//Database
var db;
//CurrentUser stores currently logged in user username
var currentUser;
//Connection to mongo db
MongoClient.connect(url, function (err, database) {
if (err) throw err;
db = database;
app.listen(8080);
console.log('Listening on 8080');
});
//Make server use public folder
app.use(express.static(__dirname + '/public'));
//---------------Get Routes Section ----------------------------
//Index Page Route
app.get('/', function (req, res) {
res.render('pages/index');
});
//Main Page Route
app.get('/MainPage', function (req, res) {
//if the user is not logged in redirect them to login page
if (!req.session.loggedin) { res.redirect('/login'); return; }
//Render main.ejs
res.render('pages/main', {
currentUser: currentUser
});
});
//About Route
app.get('/about', function (req, res) {
//If user is not logged in send him to aboute.ejs if he is send to about2.ejs
if (!req.session.loggedin) { res.render('pages/about'); return; }
res.render('pages/about2', {
currentUser: currentUser
});
});
//Login Route
app.get('/login', function (req, res) {
//Render login.ejs
res.render('pages/login');
});
//Register Route
app.get('/register', function (req, res) {
//Render reg.ejs
res.render('pages/reg');
});
//LogOut Route
app.get('/logout', function (req, res) {
//Loggs Out the current user
req.session.loggedin = false;
req.session.destroy();
res.redirect('/');
});
//Profile Route
app.get('/profile', function (req, res) {
//If not logged in send to log in page
if (!req.session.loggedin) { res.redirect('/login'); return; }
//Gets username from query
var uname = req.query.username;
//Finds the user in the database and renders profile page
db.collection('people').findOne({
"login.username": uname
}, function (err, result) {
if (err) throw err;
//Sending the result to the user page
res.render('pages/profile', {
user: result,
currentUser: currentUser
});
});
});
//Deletes a user from the database
app.get('/delete', function (req, res) {
//check for login
if (!req.session.loggedin) { res.redirect('/login'); return; }
//if so get the username
var uname = currentUser;
//checks for username in database if exists --> delete
db.collection('people').deleteOne({ "login.username": uname }, function (err, result) {
if (err) throw err;
//when complete redirect to the index
req.session.loggedin = false;
res.redirect('/');
});
});
//Get route for the results
app.get('/results', function (req, res) {
//Check if user is logged in
if (!req.session.loggedin) { res.redirect('/login'); return; }
db.collection('search').find().toArray(function (err, result) {
if (err) throw err;
res.render('pages/results', {
currentUser: currentUser,
data: result
});
});
});
//Gets addFavorite route and add selected artist to favorite
app.get('/addFavorite', function (req, res) {
//Check if user is logged in
if (!req.session.loggedin) { res.redirect('/login'); return; }
//Artist Details
var link = req.query.profile;
var thumb = req.query.image;
//Add new field to user in people collection
db.collection('people').update(
{ "login.username": currentUser },
{ $push: { "favorite": { "profile": link, "image": thumb } } }
)
//Redirect to
res.redirect('/results');
});
//Gets userProfile route and renders the page
app.get('/userProfile', function (req, res) {
//Check if the user is logged in
if (!req.session.loggedin) { res.redirect('/login'); return; }
//Artist details
var uname = req.query.user;
var icon = req.query.icon;
//Main Function// Renders the Page
getProfie();
//Sends a request for DeviantArt access token, returns a promise
function oAuth2() {
var accesToken;
//Create new promise
return new Promise(function (resolve, reject) {
//Request
request({
url: 'https://www.deviantart.com/oauth2/token',
method: 'POST',
form: {
'grant_type': 'client_credentials',
'client_id': '12052',
'client_secret': '13ae1cb7fdfb9753668db6e2310c9323'
}
}, function (err, res) {
if (err) reject(err);
var json = JSON.parse(res.body);
accesToken = json.access_token;
resolve(accesToken);
});
});
}
//Function waits for request to resolve and returns access token
async function getAccessToken() {
var accessToken = await oAuth2();
return accessToken;
}
//Function waits for access token then makes request for artist details
async function connectToDeviantArt() {
var accessToken = await getAccessToken();
return new Promise(function (resolve, reject) {
request('https://www.deviantart.com/api/v1/oauth2/user/profile/' + uname + '?ext_collections=false&ext_galleries=true&access_token=' + accessToken, function (err, res, body) {
if (err) reject(err);
var json = JSON.parse(body);
resolve(json);
});
});
}
//Function waits for request to resolve and returns artist details
async function getData() {
var data = await connectToDeviantArt();
return data;
}
//Function gets Artists Folder ID
async function getFolderId() {
var data = await getData();
var folderId = data.galleries[0].folderid;
return folderId;
}
//Function gets link to artist's profile
async function getUrl() {
var data = await getData();
var url = data.profile_url;
return url;
}
//Function gets artist's country
async function getCountry() {
var data = await getData();
var country = data.country;
return country;
}
//Function gets artists tagline
async function getTagline() {
var data = await getData();
var tagline = data.tagline;
return tagline;
}
//Function makes a request for artists gallery
async function connectToGallery() {
var folderId = await getFolderId();
var accessToken = await getAccessToken();
return new Promise(function (resolve, reject) {
request('https://www.deviantart.com/api/v1/oauth2/gallery/' + folderId + '?username=' + uname + '&mode=popular&mature_content=true&access_token=' + accessToken, function (err, res, body) {
if (err) reject(err);
var json = JSON.parse(body);
resolve(json);
});
});
}
//Function returns artists gallery
async function getGallery() {
var data = await connectToGallery();
return data;
}
//Function gets array of images from artist's gallery
async function getImages() {
var gallery = await getGallery();
var featured = [];
for (var i = 0; i < 5; i++) {
featured.push(gallery.results[i].thumbs[1].src);
}
return featured;
}
//Main function, waits for all the promises to resolve and renders the artist profile page
async function getProfie() {
var tagline = await getTagline();
var country = await getCountry();
var profile = await getUrl();
var featured = await getImages();
res.render('pages/userProfile', {
username: uname,
icon: icon,
tagline: tagline,
country: country,
link: profile,
featured: featured,
currentUser: currentUser
});
}
})
//---------------Post Routes Section----------------------------
//results post route, does all the request handling
app.post('/results', function (req, res) {
//Term to be searched
var searchItem = req.body.searchBar + " commission";
//Main function that redirects to results page
sendToPage();
//Sends a request for DeviantArt access token, returns a promise
function oAuth2() {
var accessToken;
return new Promise(function (resolve, reject) {
request({
url: 'https://www.deviantart.com/oauth2/token',
method: 'POST',
form: {
'grant_type': 'client_credentials',
'client_id': '12052',
'client_secret': '13ae1cb7fdfb9753668db6e2310c9323'
}
}, function (err, res) {
if (err) reject(err);
var json = JSON.parse(res.body);
//console.log("Access Token: ", json.access_token);
accessToken = json.access_token;
resolve(accessToken);
});
});
}
//Returns access token from the response
async function getAccessToken() {
var accessToken = await oAuth2();
return accessToken;
}
//Makes a request for entered search term
async function connectToDeviantArt() {
var accessToken = await getAccessToken();
return new Promise(function (resolve, reject) {
request('https://www.deviantart.com/api/v1/oauth2/browse/popular?category_path=digitalart%2Fpaintings&q=' + searchItem + '&timerange=1month&limit=8&access_token=' + accessToken, function (err, res, body) {
if (err) reject(err);
var json = JSON.parse(body);
resolve(json);
});
});
}
//Gets data from the response
async function getData() {
var data = await connectToDeviantArt();
return data;
}
//Erasing 'search' collection for new data to be stored
function EraseDatabase() {
db.collection('search').drop(function (err, delOK) {
if (err) {
console.log("Database was empty => continue");
}
});
}
//Adds the data from response to a 'search' collection
async function addToCollection() {
await EraseDatabase();
var data = await getData();
for (var i = 0; i < data.results.length; i++) {
var datatostore = {
"user": { "username": data.results[i].author.username, "userIcon": data.results[i].author.usericon },
"profile": data.results[i].url,
"image": data.results[i].thumbs[1].src
}
db.collection('search').save(datatostore, function (err, result) {
if (err) throw err;
console.log("Saved to database");
})
};
}
//Waits for a promise to be resolved and redirects to results page
async function sendToPage() {
await addToCollection();
res.redirect('/results');
}
});
//Gets the data from the login screen
app.post('/dologin', function (req, res) {
console.log(JSON.stringify(req.body))
//Gets user credentials
var uname = req.body.username;
var pword = req.body.password;
//If user is in the database check if passwords match and redirect to main page
db.collection('people').findOne({ "login.username": uname }, function (err, result) {
if (err) throw err;
if (!result) { res.redirect('/login'); return }
if (result.login.password == pword) { req.session.loggedin = true; res.redirect('/MainPage'); currentUser = uname; }
else { res.redirect('/login') }
});
});
//Creates an entry of the user in the databaase
app.post('/register', function (req, res) {
//if you are already logged in
if (req.session.loggedin) { console.log("Already logged in"); res.redirect('/'); return; }
// if passwords do not match
if (req.body.password != req.body.password2) { console.log("Passwords do not match"); return; }
//Data to be stored from the form
var datatostore = {
"name": req.body.fullname,
"login": { "username": req.body.username, "password": req.body.password },
"email": req.body.email,
"favorite": []
}
//Adding it to the database
db.collection('people').save(datatostore, function (err, result) {
if (err) throw err;
console.log("Saved to database");
//when completed redirect to main page
res.redirect('/login');
});
});
//-------------------------------------------------------------Server.js END------------------------------------------------------------