Blob: main.cpp

Blob id: abad833b627c46b64cfae778ba877a24e20e0a21

Size: 9.8 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
#include "crow.h"
#include "crow/http_response.h"
#include "crow/middlewares/cookie_parser.h"
#include "crow/middlewares/session.h"
#include "crow/multipart_view.h"
#include "crow/mustache.h"
#include <pqxx/pqxx>
#include "bcrypt/BCrypt.hpp"

#include <vector>
#include <fstream>
#include <cstdlib>
#include <filesystem>
#include <time.h>

namespace utils
{
	// Katso onko kirjautumistiedot oikein
	bool logged_in(const std::string& name, const std::string& password) {
		const std::string salt = "whatsapp"; // Good enough
		try
		{
			pqxx::connection cx("dbname = postgres user = postgres password = 1234 \
		  hostaddr = 127.0.0.1 port = 5432");
			if (not cx.is_open())
			{
				CROW_LOG_CRITICAL << "Can't open database";
				return false;
			}
			// Connection established
			CROW_LOG_INFO << "Opened database successfully: " << cx.dbname();
			// Etsi kayttajan tiedot
			pqxx::work tx(cx);
			pqxx::result r = tx.exec(
				"SELECT * FROM kayttajat_table "
				"WHERE nimi='" + tx.esc(name) + "'"
				); // pqxx:params too difficult
			tx.commit();
			if (r.size() != 1) {
				CROW_LOG_ERROR << "Unexpected SQL query results";
				return false;
			}
			// Tarkista tiedot
			std::string dbPassword = r[0][2].as<std::string>();
			return BCrypt::validatePassword(password + salt, dbPassword);
		}
		catch (const std::exception &e)
		{
			CROW_LOG_ERROR << e.what();
			return false;
		}
		return true;
	}

	// Generoi satunnainen tiedosto nimi
	std::string fileName(const std::string& fileExtension) {
		const char allowed[] = "abcedfghijklmnopqrstuvwxyz1234567890";
		srand(time(NULL));
		std::string r;
		for (int i = 0; i < 20; ++i) {
			r += allowed[rand() % ((sizeof(allowed) / sizeof(*allowed) - 1) )];
		}
		r += fileExtension;
		return r;
	}
}

struct Asunto {
	const std::string osoite;
	const std::string kuvaPolku;
};

int main()
{
	// Typedef
	using Session = crow::SessionMiddleware<crow::FileStore>;

	// Crow App
	crow::App<crow::CookieParser, Session> app{Session{
		crow::FileStore{"./sessions"}}};
	// Asunnot lista
	std::vector<Asunto> asunnot;
	// "Tietoa meistä"
	std::string info;

	CROW_ROUTE(app, "/")
		.methods("GET"_method, "POST"_method)([&app, &asunnot, &info](const crow::request& req){
		auto& session = app.get_context<Session>(req);

		auto page = crow::mustache::load("index.html");
		crow::json::wvalue asunnotJson;
		for (int i = 0; i < asunnot.size(); ++i) {
			asunnotJson[i]["osoite"] = asunnot.at(i).osoite;
			asunnotJson[i]["kuva"] = asunnot.at(i).kuvaPolku;
		}
		crow::mustache::context ctx({{"asunnot", asunnotJson}, {"tieto", info}});
		// Login homma
		if (session.get("name","_NO_") == "_NO_") {
			ctx["link-text"] = "Kirjaudu";
			ctx["link-link"] = "login";
		} else {
			ctx["link-text"] = "Admin";
			ctx["link-link"] = "admin";
		}
		return page.render(ctx);
	});

	CROW_ROUTE(app, "/login")
		.methods("GET"_method, "POST"_method)([&app](const crow::request& req, crow::response& res){
		auto& session = app.get_context<Session>(req);

		if (req.method == "POST"_method) { // Jos POST request
			if (req.get_body_params().get("name") == nullptr or req.get_body_params().get("pass") == nullptr) {
				CROW_LOG_ERROR << "Incorrect parameters supplied to post request";
				res.redirect("/");
				res.end();
				return;
			}
			// Hanki params
			std::string reqName = req.get_body_params().get("name");
			std::string reqPass = req.get_body_params().get("pass");
			// Tarkista kirjautuminen
			if (utils::logged_in(reqName, reqPass)) {
				CROW_LOG_INFO << "Account: " << reqName << " logged in";
				// Aseta session muuttujat
				session.set("name", reqName);
				// Kun POST request ohi, redirect admin sivulle
				res.redirect("/");
				res.end();
				return;
			}
			else { // Kirjautuminen ei onnistunut
				CROW_LOG_INFO << "Account " << reqName <<  " failed login";
			}
		}
		crow::mustache::context ctx;
		auto page = crow::mustache::load("login.html");
		if (session.contains("name")) { // Näytä kirjautumistiedot jos kirjautunut
			ctx["name"] = session.get("name", "_HELP_");
		}
		res.body = page.render(ctx).body_;
		res.end();
	});

	CROW_ROUTE(app, "/admin")
		.methods("GET"_method, "POST"_method)([&app, &info](const crow::request& req, crow::response& res){
		auto& session = app.get_context<Session>(req);

		if (session.get("name","_NO_") == "_NO_") {
			// Jos ei kirjauduttu sisään, potki pois
			res.redirect("/");
			res.end();
			return;
		}
		// Jatka jos kirjautunut sisään
		if (req.method == "POST"_method) { // Jos POST request
			// Muuta "Tietoa meistä"
			info = req.get_body_params().get("info");
			// Kirjoita tieto info.txt tiedostoon
			std::ofstream infoTxt("info.txt", std::ios::out | std::ios::trunc);
			if (not infoTxt.is_open()) {
				CROW_LOG_ERROR << "Cannot open info.txt";
				res.redirect("/");
				res.code = 500;
				res.end();
				return;
			}
			// Kirjoita
			infoTxt << info + "\n";
			infoTxt.close();
			// Valmista ollaan
			res.redirect("/");
			res.end();
			return;
		}
		// Renderöi sivu
		auto page = crow::mustache::load("admin.html");
		crow::mustache::context ctx({{"info", info}});
		res.body = page.render(ctx).body_;
		res.end();
	});

	CROW_ROUTE(app, "/asunto")
		.methods("GET"_method, "POST"_method)([&app, &asunnot](const crow::request& req, crow::response& res){
		auto& session = app.get_context<Session>(req);

		if (session.get("name","_NO_") == "_NO_") {
			// Jos ei kirjauduttu sisään, potki pois
			res.code = 401;
			res.redirect("/");
			res.end();
			return;
		}
		// Jatka jos kirjautunut sisään
		std::string asuntoOsoite;
		std::string asuntoKuva;
		// Uusi asuntola
		crow::multipart::message_view file_message(req);
		// File upload
		for (const auto& part : file_message.part_map) {
			const auto& part_name = part.first;
			const auto& part_value = part.second;
			CROW_LOG_DEBUG << "Part: " << part_name;
			// Jos teksti
			if (part_name != "image") {
				CROW_LOG_DEBUG << "Value: " << part_value.body; // debug
				asuntoOsoite = part_value.body;
				continue;
			}
			// Jos kuva

			// Extract the file name
			auto headers_it = part_value.headers.find("Content-Disposition");
			if (headers_it == part_value.headers.end()) {
				CROW_LOG_ERROR << "No Content-Disposition found";
				res.code = 400;
				res.redirect("/");
				res.end();
				return;
			}
			auto params_it = headers_it->second.params.find("filename");
			if (params_it == headers_it->second.params.end()) {
				CROW_LOG_ERROR << "Part with name \"image\" should have a file";
				res.code = 400;
				res.redirect("/");
				res.end();
				return;
			}
			const std::filesystem::path reqFile = params_it->second;
			const std::string outfileName = utils::fileName(reqFile.extension());
			const std::filesystem::path outfilePath = "static/images/" + outfileName;
			// Debug info
			for (const auto& part_header : part_value.headers)	{
				const auto& part_header_name = part_header.first;
				const auto& part_header_val = part_header.second;
				CROW_LOG_DEBUG << "Header: " << part_header_name << '=' << part_header_val.value;

				for (const auto& param : part_header_val.params)
				{
					const auto& param_key = param.first;
					const auto& param_val = param.second;
					CROW_LOG_DEBUG << " Param: " << param_key << ',' << param_val;
				}
			}
			// Write file to hard drive
			std::ofstream file(outfilePath);
			if (not file.is_open()) {
				CROW_LOG_ERROR << "Cannot write file";
				res.code = 500;
				res.redirect("/");
				res.end();
				return;
			}
			file << part_value.body;
			file.close();
			CROW_LOG_INFO << "File written to " << outfilePath;
			// Tietokantaa varten
			asuntoKuva = outfileName;
		}
		// Tarkistus
		if (asuntoOsoite.empty() or asuntoKuva.empty()) {
			res.code = 400;
			res.redirect("/");
			res.end();
			return;
		}
		// Lisää SQL tietokantaan
		try
		{
			pqxx::connection cx("dbname = postgres user = postgres password = 1234 \
		  hostaddr = 127.0.0.1 port = 5432");
			if (not cx.is_open())
			{
				CROW_LOG_CRITICAL << "Can't open database";
				res.code = 500;
				res.redirect("/");
				res.end();
				return;
			}
			// Connection established
			CROW_LOG_INFO << "Opened database successfully: " << cx.dbname();
			// Do work
			pqxx::work tx(cx);

			pqxx::result r = tx.exec(
					"INSERT INTO public.asuntolat_table (osoite,kuva)"
					"VALUES ('" + tx.esc(asuntoOsoite) + "','" + tx.esc(asuntoKuva) + "');");
			CROW_LOG_INFO << "Record added to database";
			// Valmista ollaan, nyt vaan päivitetään ramissa olevaa listaa
			const struct Asunto asunto(asuntoOsoite, asuntoKuva);
			asunnot.push_back(asunto);
			tx.commit();
		}
		catch (const std::exception &e)
		{
			CROW_LOG_ERROR << e.what();
			res.code = 500;
			res.redirect("/");
			res.end();
			return;
		}
		// Valmis
		res.code = 200;
		res.redirect("/");
		res.end();
		return;
	});

	// Lue tietokannasta asunnot
	try
	{
		pqxx::connection cx("dbname = postgres user = postgres password = 1234 \
	  hostaddr = 127.0.0.1 port = 5432");
		if (not cx.is_open())
		{
			CROW_LOG_CRITICAL << "Can't open database";
			return EXIT_FAILURE;
		}
		// Connection established
		CROW_LOG_INFO << "Opened database successfully: " << cx.dbname();
		// Do work
		pqxx::work tx(cx);

		pqxx::result r = tx.exec("SELECT * FROM asuntolat_table");

		tx.commit();

		for (auto s : r) {
			const struct Asunto asunto(
				s[0].as<std::string>(),
				s[2].as<std::string>());
			//CROW_LOG_INFO << asunto.osoite << ":" << asunto.kuvaPolku << "\n";
			asunnot.push_back( asunto );
		}
	}
	catch (const std::exception &e)
	{
		CROW_LOG_ERROR << e.what();
		return EXIT_FAILURE;
	}
	// Lue tiedostosta "Tietoa meistä"
	std::ifstream infoTxt("info.txt", std::ios::in);
	if (not infoTxt.is_open()) {
		CROW_LOG_ERROR << "Unable to open info.txt";
		return EXIT_FAILURE;
	}
	std::string line;
	while (getline(infoTxt, line)) {
		info += line += "\n";
	}
	infoTxt.close();

	// :D
	//app.loglevel(crow::LogLevel::Debug);
	app.port(18080).multithreaded().run();
	return EXIT_SUCCESS;
}