Skip to content
Snippets Groups Projects
Commit 9a0fb1cc authored by Jan Olaf Storeng's avatar Jan Olaf Storeng
Browse files

server.js kommentering

parent 9f2c4692
No related branches found
No related tags found
No related merge requests found
/** /**
* Server.js * Server.js
* *
* Server.js include funnctions needed to perform backend tasks such as communicating with the sql-database.
* sql-database connected is 'prog2053-proj' on PORT 8081.
*
*
* Session is implemented and work (?), but not correctly. * Session is implemented and work (?), but not correctly.
* When 8081 is accessed directly there is no problem saving and recieving the userId saved on req.session.userId, but when accessed from frontend (8080) the session is not accessible. * When 8081 is accessed directly there is no problem saving and accessing the userId saved on req.session.userId, but when accessed from frontend (8080) the session is not accessible.
* The method we have chosen to use for implementing session was probably not the optimal and we dont know if it is an error with the implementation or a method not ment for this use. * The method we have chosen to use for implementing session was probably not the optimal and we dont know if it is an error with the implementation or that the method is not meant for this kind of use.
* throughout the code we therefore have changed req.session.userId with 1, to simulate each function as logged in with user 1. * throughout the code we therefore have changed req.session.userId with 1, to simulate each function as logged in with user "1".
* redirectLogin and redirectHome stillworks because it aparantly allow that req.session.userId is "undefined" insted of empty. * redirectLogin and redirectHome stillworks because it aparantly allow that req.session.userId is "undefined" insted of empty.
*/ */
"use strict"; "use strict";
import express from 'express'; import express from 'express';
...@@ -30,21 +32,10 @@ app.listen(PORT, () => { ...@@ -30,21 +32,10 @@ app.listen(PORT, () => {
// Add headers // Add headers
app.use(function (req, res, next) { app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8080'); res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8080');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE'); res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type'); res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true); res.setHeader('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
next(); next();
}); });
...@@ -54,7 +45,6 @@ app.use(express.urlencoded()); ...@@ -54,7 +45,6 @@ app.use(express.urlencoded());
app.use(express.json()); app.use(express.json());
app.use(bodyParser.json()); app.use(bodyParser.json());
const TWO_HOURS = 1000 * 60 * 60 * 2; const TWO_HOURS = 1000 * 60 * 60 * 2;
/** /**
* Session * Session
...@@ -62,16 +52,27 @@ const TWO_HOURS = 1000 * 60 * 60 * 2; ...@@ -62,16 +52,27 @@ const TWO_HOURS = 1000 * 60 * 60 * 2;
* implementation of session * implementation of session
*/ */
app.use(session({ app.use(session({
// name: 'session', name: 'session',
secret: 'secret', secret: 'secret',
resave: true, resave: false,
saveUninitialized: true, saveUninitialized: false,
name: 0,
cookie:{ cookie:{
maxAge: TWO_HOURS, maxAge: TWO_HOURS,
} }
})) }))
var db = mysql.createConnection({
host: "db",
user: "admin",
password: "password",
database: 'prog2053-proj'
});
db.connect(function (err) {
if (err) throw err;
console.log("Connected!");
});
/** /**
* redirectLogin * redirectLogin
* *
...@@ -101,32 +102,8 @@ const redirectHome = (req, res, next) => { ...@@ -101,32 +102,8 @@ const redirectHome = (req, res, next) => {
} }
} }
/**
* -temporary function to search for session
*/
app.get('/checkSession', function(req, res){
var loggedin;
if(req.session.userId){
res.send(loggedin = true);
}else{
res.send(loggedin = false);
}
})
var db = mysql.createConnection({
host: "db",
user: "admin",
password: "password",
database: 'prog2053-proj'
});
db.connect(function (err) {
if (err) throw err;
console.log("Connected!");
});
app.get('/', function(req, res){ app.get('/', function(req, res){
console.log("I /:" + req.session.userId); console.log("HERE: " + req.session.userId);
}); });
/** /**
* /getUser * /getUser
...@@ -150,31 +127,26 @@ app.get('/getUser/:uid', function (req, res){ //TODO: send user-information base ...@@ -150,31 +127,26 @@ app.get('/getUser/:uid', function (req, res){ //TODO: send user-information base
/** /**
* /createUser * /createUser
* *
* @brief Creates a user from user inserted values
*
* @param req.body.email * @param req.body.email
* @param req.body.password * @param req.body.password
* @param req.body.picture * @param req.body.picture
*
* Creates a user from user inserted values
*/ */
app.post('/createUser', redirectHome, function (req, res){ app.post('/createUser', redirectHome, function (req, res){
console.log(req.body.email);
var rows; var rows;
let sql = `SELECT email FROM users WHERE email = '${req.body.email}'`; let sql = `SELECT email FROM users WHERE email = '${req.body.email}'`;
db.query(sql, function (err, result) { db.query(sql, function (err, result) {
console.log(result);
if (err) { if (err) {
result.status(400).send('Error in database operation.'); result.status(400).send('Error in database operation.');
} else { } else {
if(result.length < 1){ if(result.length < 1){
console.log('Email is unique'); console.log('Email is unique');
db.query("SELECT COUNT(*) AS count FROM users", function(err, res){ db.query("SELECT COUNT(*) AS count FROM users", function(err, res){
console.log(res[0].count);
if(err) throw err; if(err) throw err;
rows = (res[0].count); rows = (res[0].count);
rows++; rows++;
console.log(rows);
}); });
console.log(rows);
var picture; var picture;
var values = [[rows, req.body.email, req.body.password, "user", req.body.picture]]; var values = [[rows, req.body.email, req.body.password, "user", req.body.picture]];
let sql = "INSERT INTO users (uid, email, password, userType, picture) VALUES ?"; let sql = "INSERT INTO users (uid, email, password, userType, picture) VALUES ?";
...@@ -185,7 +157,7 @@ app.post('/createUser', redirectHome, function (req, res){ ...@@ -185,7 +157,7 @@ app.post('/createUser', redirectHome, function (req, res){
} }
console.log("1 record in 'users' inserted"); console.log("1 record in 'users' inserted");
req.session.userId = rows; req.session.userId = rows;
res.redirect('http://localhost:8080'); //<-- går til index etter /createUser er ferdig res.redirect('http://localhost:8080');
}); });
}else{ }else{
var resEmail = result[0].email; var resEmail = result[0].email;
...@@ -215,10 +187,8 @@ app.post('/createUser', redirectHome, function (req, res){ ...@@ -215,10 +187,8 @@ app.post('/createUser', redirectHome, function (req, res){
app.post('/login', redirectHome, (req, res) => { app.post('/login', redirectHome, (req, res) => {
db.connect(function(err){ db.connect(function(err){
var sentpassword = req.body.password; var sentpassword = req.body.password;
console.log("Connected!");
db.query(`SELECT * FROM users WHERE email='${req.body.email}'`, function (err, result){ db.query(`SELECT * FROM users WHERE email='${req.body.email}'`, function (err, result){
if(err) throw err; if(err) throw err;
console.log(result);
if(result[0]){ if(result[0]){
if(sentpassword == result[0].password){ if(sentpassword == result[0].password){
console.log("logget Inn!"); console.log("logget Inn!");
...@@ -264,7 +234,6 @@ app.get('/createComment/:post', redirectLogin, function(req, res){ ...@@ -264,7 +234,6 @@ app.get('/createComment/:post', redirectLogin, function(req, res){
db.connect(function(err) { db.connect(function(err) {
db.query("SELECT COUNT(*) AS count FROM comments", function (err, res){ db.query("SELECT COUNT(*) AS count FROM comments", function (err, res){
if(err) throw err; if(err) throw err;
console.log(res);
rows = (res[0].count); rows = (res[0].count);
rows++; rows++;
}); });
...@@ -307,12 +276,9 @@ app.get('/getComments/:post', function(req, res){ ...@@ -307,12 +276,9 @@ app.get('/getComments/:post', function(req, res){
app.get('/createPost', redirectLogin, function(req, res){ app.get('/createPost', redirectLogin, function(req, res){
var rows; var rows;
db.connect(function(err) { db.connect(function(err) {
console.log("Connected!");
console.log(req.query);
//lengde av tabell //lengde av tabell
db.query("SELECT COUNT(*) AS count FROM posts", function (err, res){ db.query("SELECT COUNT(*) AS count FROM posts", function (err, res){
if(err) throw err; if(err) throw err;
console.log(res);
rows = (res[0].count); rows = (res[0].count);
rows++; rows++;
}); });
...@@ -351,7 +317,6 @@ app.get('/getPost/:pid', (req, res) => { ...@@ -351,7 +317,6 @@ app.get('/getPost/:pid', (req, res) => {
let sql = `SELECT * FROM posts WHERE pid = ${req.params.pid}`; let sql = `SELECT * FROM posts WHERE pid = ${req.params.pid}`;
db.query(sql, (err, res) => { db.query(sql, (err, res) => {
if(err) throw err; if(err) throw err;
console.log(res);
res.send(res); res.send(res);
}); });
}); });
...@@ -370,18 +335,19 @@ app.get('/getPostUser', function(req, res){ ...@@ -370,18 +335,19 @@ app.get('/getPostUser', function(req, res){
let sql = `SELECT * FROM posts WHERE user = 1 ORDER BY pid DESC`; //TODO req.session.userId; let sql = `SELECT * FROM posts WHERE user = 1 ORDER BY pid DESC`; //TODO req.session.userId;
db.query(sql, function(err, result){ db.query(sql, function(err, result){
if(err) throw err; if(err) throw err;
console.log(result);
res.send(result); res.send(result);
}); });
}); });
//Skal jeg fjærne disse tre funksjonene? eller skal jeg bare la dem ligge? /**
// | * last three functions are not in use on the frontend final itteration but kept to show how we would go aboute solving the situations.
// \/ */
/** /**
* Make admin * Make admin
* @param req.query.uid - uid of the user being changed
* @param req.session.userId - id of the user that is logged in
* *
* change a user from user to moderator-level * change a user from user to moderator-level
*/ */
...@@ -401,7 +367,13 @@ app.get('/makeAdmin', redirectLogin, (req, res) => { ...@@ -401,7 +367,13 @@ app.get('/makeAdmin', redirectLogin, (req, res) => {
}) })
}); });
//Delete Post /**
* /deletePost
*
* @param req.query.postid - postId of the post atempted to be deleted
*
* delete post based on given id
*/
app.get('/deletePost', redirectLogin, (req, res) => { app.get('/deletePost', redirectLogin, (req, res) => {
console.log(req.query.postid); console.log(req.query.postid);
let sql = `SELECT FROM posts WHERE pid =' ${req.query.postsid}`; let sql = `SELECT FROM posts WHERE pid =' ${req.query.postsid}`;
...@@ -421,7 +393,13 @@ app.get('/deletePost', redirectLogin, (req, res) => { ...@@ -421,7 +393,13 @@ app.get('/deletePost', redirectLogin, (req, res) => {
}) })
}); });
//Delete Comment /**
* /deleteComment
*
* @param req.query.cid - id of commend attemted to be deleted
*
* delete comment given id
*/
app.get('/deleteComment', (req, res) => { app.get('/deleteComment', (req, res) => {
let sql = `DELETE FROM comment WHERE cid = ${req.query.cid}`; let sql = `DELETE FROM comment WHERE cid = ${req.query.cid}`;
db.query(sql, function(err, result) { db.query(sql, function(err, result) {
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment