-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
172 lines (143 loc) · 4.76 KB
/
server.js
File metadata and controls
172 lines (143 loc) · 4.76 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
const express = require('express');
const firebase = require('firebase/compat/app');
require('firebase/compat/auth');
require('firebase/compat/firestore');
const bodyParser = require('body-parser');
const { apiKey, authDomain, projectId, storageBucket, messagingSenderId, appId, measurementId } = require('./firebase_env.json')
// start express + extras
const port = process.env.port || 8800;
const app = express();
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.set('view engine', 'ejs');
const firebaseConfig = {
apiKey: apiKey,
authDomain: authDomain,
projectId: projectId,
storageBucket: storageBucket,
messagingSenderId: messagingSenderId,
appId: appId,
measurementId: measurementId
};
const dbapp = firebase.initializeApp(firebaseConfig);
const store = firebase.firestore();
// listen to app
app.listen(port, function(){
console.log('Ready to Hy some Draulisc! Port: ' + port);
})
function cleanseHTML(text) {
const cleansedHTML = text.replace(/[<>"&]/g, function (match) {
return {
'<': '<',
'>': '>',
'"': '"',
'&': '&',
}[match];
});
return cleansedHTML;
}
// login page
app.get('/auth', function (req, res) {
const checkUser = firebase.auth().currentUser;
if(checkUser) {
res.redirect(`/`)
} else {
res.render('pages/auth');
}
});
/* WARNING!
authorise existing user
**WARNING!!** DO NOT USE THIS AUTH METHOD IN PRODUCTION. IT HAS BEEN PROVEN (COUNTLESS TIMES) THAT IT STORES THE USER INFO LOCALLY ON THE SERVER,
CREATING A SEVERE SECURITY VULNERABILITY.
*/
app.post('/auth/login', async (req, res) => {
const email = req.body.email;
const password = req.body.password;
try {
await firebase.auth().signInWithEmailAndPassword(email, password);
res.redirect('/');
} catch (error) {
const errorMessage = error.message;
console.error(errorMessage);
res.status(500).send(errorMessage);
}
});
app.get('/', async (req, res) => {
if(firebase.auth().currentUser != null) {
res.render('pages/blogger', {
username: firebase.auth().currentUser.email,
uid: firebase.auth().currentUser
});
} else {
res.redirect('/auth')
}
})
// FETCH ALL POSTS:
app.get('/posts', async (req, res) => {
if(firebase.auth().currentUser != null) {
const post = [];
const snapshot = await firebase.firestore().collection('entries').orderBy('pnum', 'desc').get();
const promises = snapshot.docs.map(async (postDoc) => {
post.push({
data: postDoc.data()
})
})
res.render('pages/entries', {
username: firebase.auth().currentUser.email,
uid: firebase.auth().currentUser,
posts: post
})
} else {
res.redirect('/auth')
}
})
/* UPLOAD BLOG ENTRIES
This is used to upload the actual blog posts. Don't ask what kind of wizardry goes into this. We just know it works.
*/
app.post('/post/create', async (req, res) => {
const preSanitizedTitle = req.body.title;
const preSanitizedBlog = req.body.content;
// Check if any of the required fields are blank
if (!preSanitizedTitle || preSanitizedTitle.trim().length === 0 || !preSanitizedBlog || preSanitizedBlog.trim().length === 0) {
return res.status(400).send('Blog Title and Post Body are all required fields.');
}
try {
// Get the count of existing documents in the "entries" collection
const snapshot = await store.collection('entries').get();
const docCount = snapshot.size;
const blogPost = {
title: cleanseHTML(preSanitizedTitle),
content: cleanseHTML(preSanitizedBlog),
pnum: docCount + 1
}
const docRef = await store.collection('entries').add(blogPost);
const postId = docRef.id;
const timestamp = firebase.firestore.FieldValue.serverTimestamp();
const updatedPost = { path: postId, update: timestamp };
await docRef.update(updatedPost);
res.status(200).redirect('/');
} catch (error) {
console.error(error);
res.status(500).json({ error: 'Error patching blog post: ' + error.message });
}
})
// Download all posts (JSON)
app.get('/download-json', async (req, res) => {
try {
const postsSnapshot = await store.collection('entries').get();
const posts = postsSnapshot.docs.map(doc => ({
id: doc.id,
...doc.data()
}));
// Convert to JSON string
const jsonData = JSON.stringify(posts, null, 2);
// Set headers for download
res.setHeader('Content-Disposition', 'attachment; filename="entries.json"');
res.setHeader('Content-Type', 'application/json');
res.send(jsonData);
} catch (err) {
console.error('Error exporting posts:', err);
res.status(500).send('Failed to export posts');
}
})