const express = require('express') const sqlite3 = require('sqlite3').verbose() const path = require('path') const bcrypt = require('crypto') const app = express() const port = 3000 // Create a new SQLite database in memory const db = new sqlite3.Database('ruscodb') // Create a table to store data db.serialize(() => { db.get( `SELECT name FROM sqlite_master WHERE type='table' AND name='ruschi';`, (err, row) => { if (!row) { db.run( 'CREATE TABLE ruschi (id INTEGER PRIMARY KEY, type TEXT, name TEXT, description TEXT, image_url TEXT, latitude REAL, longitude REAL)' ) } } ) }) app.use(express.static(path.join(__dirname, 'public'))) app.use(express.json()) // app.get('/', (req, res) => { // res.sendFile('index.html') // }); // Insert a new item into the database app.post('/addRuschi', (req, res) => { const { name, description, imageUrl, latitude, longitude } = req.body const type = 'bho' db.run( 'INSERT INTO ruschi (type, name, description, image_url, latitude, longitude) VALUES (?, ?, ?, ?, ?, ?)', [type, name, description, imageUrl, latitude, longitude], function (err) { if (err) { return console.error(err.message) } console.log(`A row has been inserted with rowid ${this.lastID}`) res.send(`Item added with ID: ${this.lastID}`) } ) }) // Retrieve all items from the database app.get('/getRuschi', (req, res) => { db.all('SELECT * FROM ruschi', [], (err, rows) => { if (err) { return console.error(err.message) } let ruschi = [] rows.forEach(rusco => { const coordinates = { latitude: rusco.latitude, longitude: rusco.longitude } const marker = { type: "Feature", properties: { name: rusco.name, description: rusco.description, image_url: rusco.image_url, }, geometry: { type: rusco.type, coordinates: coordinates } } ruschi.push(marker) }) return res.json(ruschi) }) }) app.post('/login', (req, res) => { const username = req.body.username const password = req.body.password const hashedPassword = bcrypt .createHash('sha256') .update(password) .digest('base64') //.digest('base64'); db.all( 'SELECT * FROM users WHERE username = ? AND password = ?', [username, hashedPassword], (err, rows) => { if (err) { return console.error(err.message) } if (rows.length == 1) { return res.json('Logged in') } return res.json('Incorrect username or password') } ) }) app.post('/register', (req, res) => { console.log(req.body) const username = req.body.username const password = req.body.password const hashedPassword = bcrypt .createHash('sha256') .update(password) .digest('base64') //.digest('base64'); db.run( 'insert into users (username, password) VALUES (?, ?)', [username, hashedPassword], (err, rows) => { if (err) { return console.error(err.message) } res.json('OK') } ) }) // Start the server app.listen(port, () => { console.log(`Server is running on http://localhost:${port}`) })