-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
247 lines (202 loc) · 6.55 KB
/
index.js
File metadata and controls
247 lines (202 loc) · 6.55 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
const express = require("express");
const app = express();
const fs = require("fs");
const bodyParser = require("body-parser");
require("dotenv").config();
const pg = require("pg");
const { PrismaClient }= require("@prisma/client");
const winston = require('winston');
// Imports the Google Cloud client library for Winston
const { LoggingWinston } = require("@google-cloud/logging-winston");
const loggingWinston = new LoggingWinston();
// Create a Winston logger that streams to Cloud Logging
// Logs will be written to: "projects/YOUR_PROJECT_ID/logs/winston_log"
const logger = winston.createLogger({
level: "info",
transports: [
new winston.transports.Console(),
// Add Cloud Logging
loggingWinston
]
});
BigInt.prototype.toJSON = function() { return this.toString() }
// Writes some log entries
//logger.error('warp nacelles offline');
logger.info('Odpalam logowanie');
logger.info('Odpalam prisma new');
const prisma = new PrismaClient();
logger.info('Odpaliłem prisma new');
const client = new pg.Client({
user: process.env.DATABASE_USER,
password: process.env.DATABASE_PASSWORD,
database: process.env.DATABASE_NAME,
host: process.env.DATABASE_HOST
});
if (process.env.INSTANCE_CONNECTION_NAME) {
client.socketPath = `/cloudsql/${process.env.INSTANCE_CONNECTION_NAME}`;
}
if (process.env.DATABASE_URL) {
logger.info("Taki url do bazy danych mam: " + `${process.env.DATABASE_URL}`);
} else {
logger.info("Nie mam zdefiniowanego URL!");
}
logger.info("Podpinam sie do bazy: " + `${client.host}-->${client.database}/${client.user}:${client.port} chmurowo? ${client.socketPath}`);
client
.connect()
.then(() => {
logger.info("Podpinam sie do bazy");
console.log(
"Connected to database: " + `${client.host}-->${client.database}/${client.user}:${client.port} chmurowo? ${client.socketPath}`
);
logger.info(
"Connected to database: " + `${client.host}-->${client.database}/${client.user}:${client.port} chmurowo? ${client.socketPath}`
);
})
.catch(console.error);
app.use(bodyParser.json());
app.use(
bodyParser.urlencoded({
extended: true
})
);
const sleep = (ms) => {
return new Promise((resolve) => setTimeout(resolve, ms));
};
let dd, mm, yyyy, HH, hh, MM, SS;
// Function to convert
// single digit input
// to two digits
const formatData = (input) => {
if (input > 9) {
return input;
} else return `0${input}`;
};
// Function to convert
// 24 Hour to 12 Hour clock
const formatHour = (input) => {
if (input > 12) {
return input - 12;
}
return input;
};
// sprawdzenie dostępu do aplikacji
// Authorization token
// ?token=1234
app.use(async (req, res, next) => {
res.header("X-Powered-By", "NothingSpecialTbh");
req.db = client;
req.pcdb = prisma;
req.log = logger;
const tokenHeader = req.header.Authorization;
const tokenQuery = req.query.token;
logger.info("Szukam tokena w bazie...");
if (tokenHeader) {
logger.info("Szukam: " + `${tokenHeader}`);
const u = await client.query("select * from tokens where token = $1", [tokenHeader]);
if (u.rows.length == 0)
{
logger.info("nie znalazłem takiego tokena: " + `${tokenHeader}, error Unauthorized!`);
return res.status(401).send("Unauthorized");
}
if (u.rows[0].expires_at < new Date())
{
logger.info("Token jest: " + `${tokenHeader}, ale niestety nieważny - error Unauthorized - podaj poprawne dane!`);
return res.status(401).send("Unauthorized - use proper credentials");
}
req.userid = u.rows[0].user_id;
logger.info("znaleziony: " + `${u.rows[0].user_id}`);
return next();
}
if (!tokenQuery)
{
return res.status(401).send("Unauthorized");
}
logger.info("Szukam: "+ `${tokenQuery}`);
const tokeny = await prisma.tokens.findMany({
where: {
token: tokenQuery,
},
orderBy:[{
expires_at: 'desc',
}]
})
if (tokeny.length == 0)
{
logger.info("PRISMA -> nie znalazłem takiego tokena: " + `${tokenQuery}, error Unauthorized!`);
return res.status(401).send("PRISMA - Unauthorized");
}
else
{
logger.info("PRISMA");
logger.info(tokeny);
}
/*const u = await client.query("select * from tokens where token = $1", [tokenQuery]);
if (u.rows.length == 0)
{
logger.info("nie znalazłem takiego tokena: " + `${tokenQuery}, error Unauthorized!`);
return res.status(401).send("Unauthorized - wrong token");
}
if (users[0].expires_at < new Date())
{
logger.info("PRISMA Token jest: " + `${tokenQuery}, ale niestety nieważny - error Unauthorized - podaj poprawne dane!`);
return res.status(401).send("PRISMA Unauthorized - use proper credentials");
}
*/
/*if (u.rows[0].expires_at < new Date())
{
logger.info("Token jest: " + `${tokenQuery}, ale niestety nieważny - error Unauthorized - podaj poprawne dane!`);
return res.status(401).send("Unauthorized - use proper credentials");
}
*/
//req.userid = u.rows[0].user_id;
req.userid = tokeny[0].user_id; //PRISMA
//logger.info("znaleziony: "+ `${u.rows[0].user_id}`);
logger.info("PRISMA znaleziony: "+ `${tokeny[0].user_id}`);
return next();
});
// info kto używa aplikacji
app.use(async (req, res, next) => {
//const id = req.userid;
//const u = await client.query("select * from users where id = $1", [id]);
const users = await prisma.users.findMany({
where: {
id: req.userid,
},
})
if (users.length == 0)
{
logger.info("PRISMA -> nie znalazłem takiego użytkownika: " + `${req.userid}, error Unauthorized!`);
return res.status(401).send("PRISMA - Unauthorized - nie ma takiego użytkownika");
}
else
{
logger.info("PRISMA - jaki to user:");
logger.info(users);
}
//console.log(u.rows[0]);
return next();
});
fs.readdirSync("./routes").forEach((f) => {
app.use(require(`./routes/${f}`));
});
app.get("/secret", async (req, res) => {
logger.info("Sekcja ukryta!");
console.log("Accessing the secret section ...");
res.send("secret - OK");
});
app.get("/", async (req, res) => {
let date = new Date();
dd = formatData(date.getDate());
mm = formatData(date.getMonth() + 1);
yyyy = date.getFullYear();
HH = formatData(date.getHours());
hh = formatData(formatHour(date.getHours()));
MM = formatData(date.getMinutes());
SS = formatData(date.getSeconds());
console.log("Odpalone: " + `${mm}/${dd}/${yyyy} ${HH}:${MM}:${SS}`);
res.send("Pierwsza apka chmurowa! Odpalone query: " + `${mm}/${dd}/${yyyy} ${HH}:${MM}:${SS}`);
});
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`Server listening on port ${PORT}...`);
});