forked from hasura-imad/imad-2016-app
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
354 lines (352 loc) · 13.1 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
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
var express = require('express');
var morgan = require('morgan');
var path = require('path');
var ArticleTemplate = require('./template/article');
var DBConfig = require('./config/db');
var Pool=require('pg').Pool;
var crypto=require('crypto');
var bodyParser=require('body-parser');
var session=require('express-session');
var app = express();
app.use(morgan('combined'));
app.use(bodyParser.json());
//session specific
app.use(session({
secret: 'AjIMADWebApplicationOfYear2016',
cookie: {maxAge: 1000*60*60*24*30},
resave: true,
saveUninitialized: true
}));
//db specific
var dbconfig=new DBConfig();
var pool=new Pool(dbconfig.setup.prod);
//template specific
var articleTemplate=new ArticleTemplate();
//login specific
function pwd_hash(password,salt){
var key=crypto.pbkdf2Sync(password,salt,10000,512,'sha512');
return ["pbkdf2","10000",salt,key.toString('hex')].join("$");
}
function pwd_verify(password,hash){
var salt=hash.split("$")[2];
var hashedPassword=pwd_hash(password,salt);
if(hashedPassword===hash){
return true;
}
return false;
}
function get_auth_status(req){
var status="";
if(req.session && req.session.userAuth && req.session.userAuth.id && req.session.userAuth.role){
status=req.session.userAuth.role;
}
return status;
}
function get_random_number(min,max){
return Math.floor(Math.random() * (max - min + 1)) + min;
}
app.get("/login-template",function(req,res){
res.send(articleTemplate.loginTemplate());
});
app.post("/login",function(req,res){
var username=req.body.un;
var password=req.body.pwd;
var un_pattern=/^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$/;
if(username.trim()===""||password.trim()===""||!un_pattern.test(username)||username.length>25){
res.status(400).send("Invalid input values!");
}else{
pool.query("SELECT * FROM users WHERE username=$1",[username],function(err,result){
if(err){
res.status(500).send(err.toString());
}else{
if(result.rows.length===0){
res.status(403).send("Username/Password is invalid!");
}else{
var db_pass=result.rows[0].password;
if(pwd_verify(password,db_pass)){
req.session.userAuth={id:result.rows[0].id,role:result.rows[0].role};
res.send(result.rows[0].role);
}else{
res.status(403).send("Username/Password is invalid!");
}
}
}
});
}
});
app.post("/register",function(req,res){
var username=req.body.un;
var password=req.body.pwd;
var email=req.body.email;
var un_pattern=/^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$/;
if(username.trim()===""||password.trim()===""||email.trim()==""||!un_pattern.test(username)||username.length>25){
res.status(400).send("Invalid input values!");
}else{
var salt = crypto.randomBytes(128).toString('hex');
var hashed_pwd= pwd_hash(password,salt);
var user_logo="user_logo.png";
var user_first_char=(username.charAt(0)).toLowerCase();
if(/[a-zA-Z0-9]/.test(user_first_char)){
user_logo=user_first_char+"_"+get_random_number(1,3)+".png";
}
pool.query("INSERT INTO users(username,password,email,user_logo) VALUES($1,$2,$3,$4)",[username,hashed_pwd,email,user_logo],function(err,result){
if(err){
res.status(500).send(err.toString());
}else{
res.send("Successfully Registered!");
}
});
}
});
app.get("/get-user-details",function(req,res){
if(get_auth_status(req)!==""){
pool.query("SELECT username,user_logo FROM users WHERE id=$1",[req.session.userAuth.id],function(err,result){
if(err){
res.status(500).send(err.toString());
}else{
res.status(200).send(JSON.stringify(result.rows[0]));
}
});
}else{
res.status(400).send("Not logged in!");
}
});
app.get("/logout",function(req,res){
delete req.session.userAuth;
res.sendFile(path.join(__dirname, "ui", "logout.html"));
});
//admin specific routes
app.get('/admin',function(req,res){
if(get_auth_status(req)!=="admin"){
res.redirect("/");
}else{
res.sendFile(path.join(__dirname, "ui/admin/", "index.html"));
}
});
app.get('/admin/:page',function(req,res){
if(get_auth_status(req)!=="admin"){
res.redirect("/");
}else{
res.sendFile(path.join(__dirname, "ui/admin/", req.params.page+".html"));
}
});
//like button specific
app.get('/like-article/:articleName',function(req,res){
if(get_auth_status(req)!==""){
var articleName=req.params.articleName;
var userId=req.session.userAuth.id;
pool.query("SELECT * FROM article WHERE article_name=$1",[articleName],function(err,result){
if(err){
res.status(500).send(err.toString());
}else{
if(result.rows.length===0){
res.status(404).send("No article found!");
}else{
var articleId=result.rows[0].id;
pool.query("INSERT INTO likes(article_id, user_id) VALUES($1, $2)",[articleId,userId],function(err,result){
if(err){
res.status(500).send("Not allowed to like more than once!");
}else{
res.status(200).send("Liked");
}
});
}
}
});
}else{
res.status(403).send("Please login to like article!");
}
});
app.get('/get-likes/:articleName',function(req,res){
var likes={count:0,status:""};
var articleName=req.params.articleName;
pool.query("SELECT COUNT(likes.*) FROM article,likes WHERE article.article_name=$1 AND article.id=likes.article_id GROUP BY likes.article_id",[articleName],function(err,result){
if(err){
res.status(500).send(err.toString());
}else{
if(result.rows.length!==0){
likes.count=result.rows[0].count;
if(get_auth_status(req)!==""){
var userId=req.session.userAuth.id;
pool.query("SELECT users.username FROM article,users,likes WHERE article.article_name=$1 AND article.id=likes.article_id AND likes.user_id=$2",[articleName,userId],function(err,result){
if(err){
res.status(500).send(err.toString());
}else{
if(result.rows.length===0){
likes.status="not liked";
}else{
likes.status="liked";
}
res.status(200).send(JSON.stringify(likes));
}
});
}else{
res.status(200).send(JSON.stringify(likes));
}
}else{
res.send(JSON.stringify(likes));
}
}
});
});
//comments specific
app.post('/submit-comment/:articleName',function(req,res){
if(get_auth_status(req)!==""){
var articleName=req.params.articleName;
var comment=req.body.comment;
var userId=req.session.userAuth.id;
if(comment.trim()===""){
res.status(400).send("Not a valid comment!");
}else{
pool.query("SELECT * FROM article WHERE article_name=$1",[articleName],function(err,result){
if(err){
res.status(500).send(err.toString());
}else{
if(result.rows.length===0){
res.status(404).send("No article found!");
}else{
var articleId=result.rows[0].id;
pool.query("INSERT INTO comments(article_id, user_id, comment) VALUES($1, $2, $3)",[articleId,userId,comment],function(err,result){
if(err){
res.status(500).send(err.toString());
}else{
res.status(200).send("Comment successfully inserted!");
}
});
}
}
});
}
}else{
res.status(403).send("Please login to comment!");
}
});
app.get("/get-comment/:articleName",function(req,res){
var articleName=req.params.articleName;
pool.query("SELECT comments.comment,comments.comment_date,users.username,users.user_logo FROM article,comments,users WHERE article.article_name=$1 AND article.id=comments.article_id AND comments.user_id=users.id ORDER BY comments.comment_date DESC",[articleName],function(err,result){
if(err){
res.status(500).send(err.toString());
}else{
res.send(JSON.stringify(result.rows));
}
});
});
//articles specifc
app.get("/blog",function(req,res){
res.sendFile(path.join(__dirname, "ui/", "blog.html"));
});
app.post('/add-page',function(req,res){
if(get_auth_status(req)==="admin"){
var articleTitle=req.body.title;
var articleName=(articleTitle.replace(/\s+/g,"-")).toLowerCase();
var article=req.body.content;
var articleType=req.body.type;
if(articleType==="blog"){
article=article+"<div class='blog_link'><a href='/blog' title='Return to blog'>Return to Blog</a></div>";
}
pool.query("INSERT INTO article(title,date,article_name,content,article_type) VALUES($1,now(),$2,$3,$4)",[articleTitle,articleName,article,articleType],function(err,result){
if(err){
res.status(500).send("Error: "+err.toString());
}else{
res.status(200).send("Successfully added!");
}
});
}else{
res.status(403).send("Not authorized!");
}
});
app.post('/update-page',function(req,res){
if(get_auth_status(req)==="admin"){
var article=req.body.content;
var articleID=req.body.id;
pool.query("UPDATE article SET content=$1 WHERE id=$2",[article,articleID],function(err,result){
if(err){
res.status(500).send("Error: "+err.toString());
}else{
res.status(200).send("Successfully Updated!");
}
});
}else{
res.status(403).send("Not authorized!");
}
});
app.get('/get-articles',function(req,res){
pool.query("SELECT title,article_name FROM article ORDER By date DESC",function(err,result){
if(err){
res.status(500).send("Error: "+err.toString());
}else{
if(result.rows.length===0){
res.status(404).send("Not Found!");
}else{
res.send(JSON.stringify(result.rows));
}
}
});
});
app.get('/get-article',function(req,res){
var articleName=req.query.articleName;
pool.query("SELECT * FROM article WHERE article_name=$1",[articleName],function(err,result){
if(err){
res.status(500).send("Error: "+err.toString());
}else{
if(result.rows.length===0){
res.status(404).send("Not Found!");
}else{
res.send(JSON.stringify(result.rows));
}
}
});
});
app.get('/blog-posts',function(req,res){
pool.query("SELECT * FROM article WHERE article_type='blog' ORDER BY date DESC",function(err,result){
if(err){
res.status(500).send("Error: "+err.toString());
}else{
if(result.rows.length===0){
res.status(404).send("Not Found!");
}else{
for(var i=0;i<result.rows.length;i++){
var content=result.rows[i].content;
result.rows[i].content=content.substr(content.indexOf("<p>"),content.indexOf("</p>")+4);
}
res.send(JSON.stringify(result.rows));
}
}
});
});
app.get('/articles/:articleName',function(req,res){
var artName=req.params.articleName;
pool.query("SELECT * FROM article WHERE article_name=$1",[artName],function(err,result){
if(err){
res.status(500).send("Error: "+err.toString());
}else{
if(result.rows.length===0){
res.status(404).sendFile(path.join(__dirname, 'ui', '404.html'));
}else{
var artData=result.rows[0];
res.send(articleTemplate.create(artData));
}
}
});
});
//menu specific
app.get('/menu',function(req,res){
pool.query("SELECT title,article_name FROM article WHERE article_type='main' ORDER BY id",function(err,result){
if(err){
res.status(500).send("Error: "+err.toString());
}else{
if(result.rows.length===0){
res.status(404).send("Not Found!");
}else{
var menu_data=result.rows;
res.send(JSON.stringify(menu_data));
}
}
});
});
//loading static files
app.use(express.static(path.join(__dirname, 'ui')));
var port = 8080; // Use 8080 for local development because you might already have apache running on 80
app.listen(port, function () {
console.log(`IMAD course app listening on port ${port}!`);
});