Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
node_modules/
.env
nohup.out
logfile
logfile
/redis-stable
redis-stable.tar.gz
tester.psql
.DS_Store
config.js
14 changes: 13 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ Steps for reinstallation / running on a new machine:

----------------------------------
References:
<b>Understanding Google Maps API</b>
<b>Understanding Google Maps API</b>
<b> LINKS USED: </b>
* https://developers.google.com/maps/documentation/javascript/adding-a-google-map

Expand All @@ -66,6 +66,18 @@ because i had no idea what to do 90% of the time
<b> LINKS USED: </b>
* https://www.w3schools.com/js/js_cookies.asp

<b> Resources for refactoring </b>
<b> LINKS USED: </b>
* https://node-postgres.com/guides/project-structure
* https://blog.logrocket.com/setting-up-a-restful-api-with-node-js-and-postgresql-d96d6fc892d8/

<b> Security stuff: </b>
<b> LINKS USED: </b>
* Bcrypt https://www.npmjs.com/package/bcrypt




<b>Other things I learned</b>
* run ```ps aux | grep node``` to kill ports when the same port error comes up
* working on a new branch
Expand Down
151 changes: 1 addition & 150 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,163 +5,14 @@ const env = require('dotenv').config();
var bodyParser = require('body-parser');
const path = require('path'); //this helps the google maps api show up
const db = require('./db');

////////////for login session//////////
const redis = require('redis');
const redisStore = require('connect-redis')(session);
const client = redis.createClient();
var parseurl = require('parseurl')

//////////url parsing//////////
const http = require('http');
const url = require('url');
///////cookies for sessions////////
var cookieParser = require('cookie-parser');
//////////////////////////////

const app = express();
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: false })); // support encoded bodies
app.use(cookieParser());

mountRoutes(app)

app.use(session({
secret: 'ssshhhhh',
// create new redis store.
store: new redisStore({ host: 'localhost', port: 6379, client: client,ttl : 260}),
saveUninitialized: false,
resave: true //originally F but unsure
}));
mountRoutes(app) //this helps generate the map

app.get('/', (req, res) => {
res.sendFile(path.join(__dirname + '/resources/html/map.html'));
});

//no use for admin page .. YET
app.get('/admin',(req,res) => {
if(req.session.email) {
res.write(`<h1>Hello ${req.session.email} </h1><br>`);
res.end('<a href='+'/logout'+'>Logout</a>');
}
else {
res.write('<h1>Please login first.</h1>');
res.end('<a href='+'/login'+'>Login</a>');
}
});

app.use('/logout', async (req,res) => {
console.log(objectUsersInfo.username + ' is ready to logout');
req.session.destroy((err) => {
if(err) {
return console.log(err);
}
//it will clear the userData cookie
res.clearCookie('userData');
res.send('user logout successful');
});
});

// redirects user to HTML form to enter their information
app.get('/registration', (req, res) => {
res.sendFile(path.join(__dirname + '/resources/html/registration.html'));
})

app.post('/register', async (req, res) => {
const userid = req.body.userid
const email = req.body.email
const pass = req.body.password
const myQuery = `SELECT insert_user('${userid}', '${email}', '${pass}')`
await db.query(myQuery)
console.log(userid, "has been sucessfully registered")
res.send("Success boyo")
})

//JSON object to be added to cookie (GLOBAL VARIABLE) referenced throughout project
let objectUsersInfo = {}

//first you /setUser via res.cookie, then you redirect the user to their personalized page
app.get('/welcome', (req, res)=>{
res.cookie("userData", JSON.stringify(objectUsersInfo));
console.log("setting user ", objectUsersInfo, " = usersInfo")
res.sendFile(path.join(__dirname + '/resources/html/usermap.html'));
// res.end('<a href='+'/users/' + objectUsersInfo.id +'>View your collection</a>'); //to add a button later on?
});

//Iterate users data from cookie (shows username, email, pw)
app.get(
'/getuser', (req, res)=>{
res.send(req.cookies);
});

app.get('/login', async (req, res) => {
res.render('logindex.ejs')
})

////// USER LOGS IN TO SEE WHAT THEY HAVE AND WHAT THEY DONT HAVE \\\\\\
app.post('/loginsession', async (req, res) => {
var o = {} //empty object
key = 'loggeduser';
o[key] = []; //empty array to push values into
req.session.email = req.body.email
req.session.pass = req.body.password
const queryUserData = `SELECT EXISTS (SELECT 1 FROM users WHERE email = '${req.session.email}' AND pass = '${req.session.pass}')`
const userExistenceInfo = await db.query(queryUserData)

// parse user's information if they exist in the db and add info to session cookies
if (userExistenceInfo.rows[0].exists) {
var htmlMessage = 'Hello:' + req.session.email + 'you successfully logged in';
console.log("post received: %s %s", req.session.email, req.session.pass);
// res.send(htmlMessage)
const userIDQuery = `SELECT * FROM users WHERE email = '${req.session.email}' AND pass = '${req.session.pass}'` //for the logged in user's info
const userIDResult = await db.query(userIDQuery)
const currentUserID = userIDResult.rows[0].id
const currentUsername = userIDResult.rows[0].user_name
req.session.currentID = currentUserID
req.session.username = currentUsername
objectUsersInfo = {
username : req.session.username,
id : req.session.currentID
};
o[key].push(objectUsersInfo);
JSON.stringify(o);
//now write all the user data into the global cookie (formerly /setUser instead of /welcome)
res.writeHead(301,{Location: 'http://localhost:3000/welcome'});
res.end();
} else {
res.send("Login not successful")
}
})


//please ignonre /collect and /coininsert. it may or may not be used in the final project
app.get('/collect', (req, res) => {
res.render('collectcoin.ejs')
})
app.post('/coininsert', async (req, res) => {
const machine = req.body.machine
const coin = req.body.coin
const email = req.body.email

const idQuery = `SELECT * FROM users WHERE email = '${email}'` //for the logged in user's info
const idResult = await db.query(idQuery)
const currentID = idResult.rows[0].id

const machineQuery = `SELECT * FROM coins LEFT JOIN machines ON machines.id = coins.fk_machine_id LEFT JOIN locations ON locations.fk_machine_id = machines.id WHERE machinename = '${machine}'`
const machineResult = await db.query(machineQuery)
const machineID = machineResult.rows[0].fk_machine_id
console.log(machineID, "is the machineid")
const coinQuery = `SELECT * FROM coins WHERE fk_machine_id = '${machineID}' AND coinname = '${coin}'`
const coinResult = await db.query(coinQuery)
const coinID = coinResult.rows[0].id
console.log(coinID, "is the coinid for ", coin)

// const myQuery = `SELECT insert_coin_entry('${userid}', '${email}', '${pass}');`
//// (fk_user INT, fk_coins INT, input_year INT)
var htmlData = 'Hello:' + email + ' u want to insert' + coin + 'to' + machine;
res.send(htmlData)
})

const port = process.env.PORT || 3000;
const server = app.listen(port, () => console.log(`Listening on port ${port}`)).on("error", console.log);

Expand Down
23 changes: 19 additions & 4 deletions db/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ const {
Client
} = require('pg')

// this const pool is required to access database on heroku
// also had to delete .env file (local) because it might have overwritten heroku's .env file
//// this const pool is required to access database on heroku
//// also had to delete .env file (local) because it might have overwritten heroku's .env file

// const pool = new Pool({
// user: 'njolazjolmpfjq',
Expand Down Expand Up @@ -43,10 +43,25 @@ const client = new Client({
// connectionString: 'var/run/postgresql',
});


client.connect()

//supposed to log our queries when executed
module.exports = {
query: (text, params, callback) => {
return pool.query(text, params, callback)
const start = Date.now()
return pool.query(text, params, callback, (err, res) => {
const duration = Date.now() - start
console.log('executed query', { text, duration, rows: res.rowCount })
callback(err, res)
})
}
}
}


// module.exports = {
// query: (text, params, callback) => {
// return pool.query(text, params, callback)
// }
// }

Loading