Skip to content
Snippets Groups Projects
Commit 9dbbbce7 authored by Rickard Loland's avatar Rickard Loland
Browse files

Merge branch 'master' of https://git.gvk.idi.ntnu.no/sindre0830/xyz-project into master

parents f4a9f7c6 ef44d71a
No related branches found
No related tags found
No related merge requests found
/**
* Server.js
*
* 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.
* 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.
* 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.
*/
"use strict";
import express from 'express';
......@@ -7,13 +19,10 @@ import parse from 'querystring';
import session from 'express-session';
import bodyParser from 'body-parser';
import cookieParser from 'cookie-parser';
//import mongoose from 'mongoose';
const router = express.Router();
const app = express();
const PORT = process.env.port || 8081;
//const bcrypt = require('bcrypt'); //<-- npm i bcrypt
//$ npm i passport passport-local express-session express-flash
app.listen(PORT, () => {
console.log('Running...');
......@@ -43,14 +52,15 @@ app.use(cookieParser());
app.use(express.static(path.resolve() + '/server'));
app.use(express.urlencoded());
app.use(express.json());
//app.use(express.static(__dirname + '/views'));
app.use(bodyParser.json());
//app.use(session({secret: 'ssshhhh',saveUninitialized: true,resave: true}));
//app.use(passport.initialize())
//app.use(passport.session());
const TWO_HOURS = 1000 * 60 * 60 * 2;
const TWO_HOURS = 1000 * 60 * 60 * 2;
/**
* Session
*
* implementation of session
*/
app.use(session({
// name: 'session',
secret: 'secret',
......@@ -62,13 +72,11 @@ app.use(session({
}
}))
/*app.use(cookieSession({
name: 'session',
keys: 'key1',
secret: 'secret',
}))
/**
* redirectLogin
*
* if there is a session the user is redirected to login
*/
const redirectLogin = (req, res, next) => {
const {cookies} = req;
if(!req.session.userId){
......@@ -79,6 +87,11 @@ const redirectLogin = (req, res, next) => {
}
}
/**
* redirect Home
*
* if the user has a session, he will be redirected to the index
*/
const redirectHome = (req, res, next) => {
if(req.session.userId){
res.redirect('http://localhost:8080')
......@@ -88,6 +101,18 @@ 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",
......@@ -103,7 +128,13 @@ db.connect(function (err) {
app.get('/', function(req, res){
console.log("I /:" + req.session.userId);
});
/**
* /getUser
*
* @param req.params.uid
*
* @brief the function takes the id of a user as a parameter and returns sql-table of the user with the uid
*/
app.get('/getUser/:uid', function (req, res){ //TODO: send user-information based on session-data.
if(req.params.uid > 0){
let sql = `SELECT uid, email, userType, picture FROM comments WHERE uid = ${req.params.uid}`; //henter nå fra url
......@@ -117,45 +148,15 @@ app.get('/getUser/:uid', function (req, res){ //TODO: send user-information base
});
/**
* /createUser
*
* @brief Creates a user from user inserted values
*
* @param req.body.email
* @param req.body.password
* @param req.body.picture
*/
app.post('/createUser', redirectHome, function (req, res){
/* //const crypPassword = await bcrypt.hash(req.body.password, 10); //<-- krypterer passord
var rows;
console.log("Connected!");
let sql = `SELECT email FROM users WHERE email = '${req.body.email}'`;
db.query(sql, function(err, res){
console.log(res[0].email);
console.log(req.body.email);
if(res[0].email == res.body.email){
console.log('Email already exist');
//res.redirect('http://localhost:8080');
}else{
console.log('Email is unique');
db.query("SELECT COUNT(*) AS count FROM users", function(err, res){
console.log(res[0].count);
if(err) throw err;
rows = (res[0].count);
rows++;
console.log(rows);
});
console.log(rows);
var values = [[rows, req.body.email, req.body.password, "user", req.body.picture]];
let sql = "INSERT INTO users (uid, email, password, userType, picture) VALUES ?";
db.query(sql, [values], function (err, result) {
if(err){
res.redirect('http://localhost:8080/login');
throw err;
}
console.log("1 record in 'users' inserted");
req.session.userId = rows;
res.redirect('http://localhost:8080'); //<-- går til index etter /createUser er ferdig
});
}
})*/
console.log(req.body.email);
var rows;
let sql = `SELECT email FROM users WHERE email = '${req.body.email}'`;
......@@ -201,6 +202,16 @@ app.post('/createUser', redirectHome, function (req, res){
});
});
/**
* /login
*
* @param req.body.password - password sent by user
* @param req.body.email - email sent by user
*
* takes parameter and compare them with content of sql
* if the content match up, log inn the user.
*/
app.post('/login', redirectHome, (req, res) => {
db.connect(function(err){
var sentpassword = req.body.password;
......@@ -236,29 +247,21 @@ app.get('/logout', redirectLogin, (req, res) => {
res.redirect('http://localhost:8080');
})
app.get('/checkSession', function(req, res){
var loggedin;
if(req.session.userId){
res.send(loggedin = true);
}else{
res.send(loggedin = false);
}
})
/**
* @brief Creates a comment from user inserted values
*
* @param cid
* @param postnr
* @param userid
* @param comment
* @param req.params.postnr - postId
* @param req.params.comment - user-created content of the comment
*
* if the user does not have a session he is redirected to the login-page
* The function takes the parameters and puts the content into the sql-database.
*
* TODO: for now the function is simpulated to create a post for user "1" because session is not properly implemented. req.session.userId shuld be the correct value.
*/
app.get('/createComment/:post', redirectLogin, function(req, res){
var rows;
db.connect(function(err) {
console.log("Connected!");
console.log(req.query);
//lengde av tabell
db.query("SELECT COUNT(*) AS count FROM comments", function (err, res){
if(err) throw err;
console.log(res);
......@@ -275,6 +278,13 @@ app.get('/createComment/:post', redirectLogin, function(req, res){
res.redirect('http://localhost:8080');
});
/**
* /getComments
*
* @param req.params.post - post id
*
* takes the id of a post and return comments allocated to the post.
*/
app.get('/getComments/:post', function(req, res){
let sql = `SELECT * FROM comments WHERE post = ${req.params.post}`; //henter nå fra url
db.query(sql, function(err, result){
......@@ -284,13 +294,15 @@ app.get('/getComments/:post', function(req, res){
})
/**
* createPost
* - legger til en ny post i databasen som inneholder gitte parametere
* /createPost
*
* @param req.query.title - user-created title of the post
* @param req.query.content - user-created content of the post
*
* @param pid
* @param userid
* @param title
* @param content
* if the user does not have a session, he is redirected to the login-page
* the function calculates a new pid for the post, the parameters, pid and userId are inserted into the sql-database.
*
* TODO: the userId of the post is currently simulated to create a post for user 1, when session is correctly implemented it will get the Id by; req.session.userId
*/
app.get('/createPost', redirectLogin, function(req, res){
var rows;
......@@ -317,8 +329,8 @@ app.get('/createPost', redirectLogin, function(req, res){
/**
* /getPosts
* all posts
* @param {*} cid
*
* function return all of the posts in the posts-table.
*/
app.get('/getPosts', function (req, res) {
let sql = 'SELECT * FROM posts ORDER BY pid DESC';
......@@ -330,8 +342,10 @@ app.get('/getPosts', function (req, res) {
/**
* getPost
* specific post
* @param {*} cid
*
* @param pid - post id
*
* function return a specific post based on post id gaven as parameter
*/
app.get('/getPost/:pid', (req, res) => {
let sql = `SELECT * FROM posts WHERE pid = ${req.params.pid}`;
......@@ -342,7 +356,17 @@ app.get('/getPost/:pid', (req, res) => {
});
});
app.get('/getPostUser', function(req, res){
/**
* /getPostUser
*
* @param req.session.userId
*
* function return all of the posts of the user that currently has a session.
*
* TODO the function is simulated as user "1" is the logged in user. when session is implemented req.session.userId should retrieve the correct Id.
*/
app.get('/getPostUser', redirectLogin, function(req, res){
let sql = `SELECT * FROM posts WHERE user = 1 ORDER BY pid DESC`; //TODO req.session.userId;
db.query(sql, function(err, result){
if(err) throw err;
......@@ -351,6 +375,11 @@ app.get('/getPostUser', function(req, res){
});
});
//Skal jeg fjærne disse tre funksjonene? eller skal jeg bare la dem ligge?
// |
// \/
/**
* Make admin
*
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment