-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
217 lines (181 loc) · 5.96 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
const axios = require('axios');
const express = require('express');
const http = require('http');
const WebSocket = require('ws');
const { body, query, validationResult } = require('express-validator');
const jwt = require('jsonwebtoken');
require('dotenv').config();
const app = express();
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });
const port = process.env.PORT || 6007;
const secretKey = process.env.JWTKEY;
app.use(express.static('public'));
app.set('view engine', 'ejs');
app.set('views', './view');
app.use(express.json());
app.use(express.urlencoded({
extended: true
}));
const checkNonJWTAuthorization = (req, res, next) => {
const apiKey = req.headers['x-api-key'];
if (!apiKey || apiKey !== process.env.XAPIKEY) {
return res.status(401).json({ error: 'Unauthorized: Invalid API Key' });
}
next();
};
const verifyToken = (req, res, next) => {
const token = req.headers['authorization'];
if (!token) {
return res.status(401).json({ error: 'Unauthorized: No token provided' });
}
try {
const decoded = jwt.verify(token, secretKey);
req.user = decoded;
next();
} catch (error) {
console.error('Error verifying token');
return res.status(401).json({ error: 'Unauthorized: Invalid token' });
}
};
app.get('/api/token', checkNonJWTAuthorization, (req, res) => {
res.header('X-Frame-Options', 'DENY');
res.header('X-XSS-Protection', '1; mode=block');
res.header('X-Content-Type-Options', 'nosniff');
res.header('Strict-Transport-Security', 'max-age=63072000');
try {
const payload = {
userId: process.env.USERID,
username: process.env.USERNAME
};
const token = jwt.sign(payload, secretKey, { expiresIn: '5m' });
res.json({ token });
} catch (error) {
console.error('Error generating token');
res.status(500).json({ error: 'Internal Server Error' });
}
});
app.get('/', (req, res) => {
res.header('X-Frame-Options', 'DENY');
res.header('X-XSS-Protection', '1; mode=block');
res.header('X-Content-Type-Options', 'nosniff');
res.header('Strict-Transport-Security', 'max-age=63072000');
const current_page = 'https://' + req.headers.host + req.url;
const homepage = 'https://' + req.headers.host + '/';
const title = 'Live Cricket Score 🏏';
const description = 'Free online - Live Cricket Score 🏏.'
res.render('home', {
seourl: current_page || '/',
homepage: homepage,
title : title,
description : description
});
});
wss.on('connection', (ws) => {
//console.log('Client connected');
ws.on('message', (message) => {
console.log(`Received message: ${message}`);
});
});
app.get('/api/score', [
query('id')
.notEmpty().withMessage('ID parameter is required')
.isNumeric().withMessage('ID parameter must be a number')
.isLength({ min: 5, max: 10 }).withMessage('ID parameter must be exactly 6 characters long')
], async (req, res) => {
res.header('X-Frame-Options', 'DENY');
res.header('X-XSS-Protection', '1; mode=block');
res.header('X-Content-Type-Options', 'nosniff');
res.header('Strict-Transport-Security', 'max-age=63072000');
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
try {
const { id } = req.query;
const apiURL = process.env.API + id;
const response = await axios.get(apiURL, {
family: 4
});
res.json(response.data);
} catch (error) {
console.error('Error fetching external data');
res.status(500).json({ error: 'Error fetching external data' });
}
});
app.post('/api/message',
verifyToken,
body('message')
.trim()
.custom((value) => value === 'reload')
.withMessage('Message must be "reload"'),
(req, res) => {
res.header('X-Frame-Options', 'DENY');
res.header('X-XSS-Protection', '1; mode=block');
res.header('X-Content-Type-Options', 'nosniff');
res.header('Strict-Transport-Security', 'max-age=63072000');
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const { message } = req.body;
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(message);
}
});
let responseMessage;
if (message === 'reload') {
responseMessage = 'Message sent to all clients';
} else {
responseMessage = 'Warning: Message is not "reload"';
}
res.status(200).json({ success: true, message: responseMessage });
}
);
app.post('/api/alexa',
verifyToken,
body('alexamessage')
.trim()
.notEmpty().withMessage('Alexa message cannot be empty')
.isLength({ min: 2, max: 500 }).withMessage('Alexa message must be between 2 and 500 characters')
.escape(),
(req, res) => {
res.header('X-Frame-Options', 'DENY');
res.header('X-XSS-Protection', '1; mode=block');
res.header('X-Content-Type-Options', 'nosniff');
res.header('Strict-Transport-Security', 'max-age=63072000');
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const { alexamessage } = req.body;
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(alexamessage);
}
});
let responseMessage;
if (alexamessage) {
responseMessage = 'Message sent to all clients';
} else {
responseMessage = 'Warning: Message is not Sent to Clients';
}
res.status(200).json({ success: true, alexamessage: responseMessage });
}
);
app.get('/robots.txt', (req, res) => {
res.type('text/plain');
res.send('User-agent: *\nDisallow: /');
});
app.use((req, res, next) => {
res.status(404).json({ error: 'Not Found' });
});
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json({ error: 'Internal Server Error' });
});
server.listen(port, () => {
console.log('listening on port ' + port);
});
module.exports = app;