Skip to content

Commit

Permalink
Merge pull request #4 from TeaghanEveleigh/master
Browse files Browse the repository at this point in the history
removed : removed cert file
  • Loading branch information
TeaghanEveleigh authored Aug 6, 2024
2 parents a199024 + 0294d14 commit 6f69547
Show file tree
Hide file tree
Showing 6 changed files with 135 additions and 41 deletions.
25 changes: 0 additions & 25 deletions backend/src/certs/ca.crt

This file was deleted.

41 changes: 35 additions & 6 deletions backend/src/config/createTables.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,22 @@
const pool = require('./db');

// Query to check if users table exists

const checkUsersTableQuery = `
SELECT EXISTS (
SELECT FROM information_schema.tables
WHERE table_schema = 'public'
AND table_name = 'users'
);
`;
const checkTransactionsTableQuery = `
SELECT EXISTS (
SELECT FROM information_schema.tables
WHERE table_schema = 'public'
AND table_name = 'transactions'
);
`;


// Query to create users table
const createUserTableQuery = `
CREATE TABLE IF NOT EXISTS users (
id SERIAL PRIMARY KEY,
Expand All @@ -21,6 +28,21 @@ const createUserTableQuery = `
);
`;

const createTransactionTableQuery = `
CREATE TABLE IF NOT EXISTS transactions (\
id SERIAL PRIMARY KEY,
user_id INTEGER NOT NULL,
title VARCHAR(255) NOT NULL ,
amount NUMERIC(10,2) NOT NULL,
description TEXT ,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
)
`

async function createTables() {
try {
// Check if users table exists
Expand All @@ -32,12 +54,19 @@ async function createTables() {
} else {
console.log('Users table already exists');
}

// Check if transactions table exists
const { rows: transactionsTableExists } = await pool.query(checkTransactionsTableQuery);
if (!transactionsTableExists[0].exists) {
// Create transactions table
await pool.query(createTransactionTableQuery);
console.log('Transactions table created successfully');
} else {
console.log('Transactions table already exists');
}
} catch (error) {
console.error('Error creating tables:', error);
} finally {

pool.end();
}
}
}

module.exports = createTables;
3 changes: 2 additions & 1 deletion backend/src/middleware/autMiddleware.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
const jwt = require('jsonwebtoken');
function isAuthenticated(req, res, next) {
const authHeader = req.headers['authorization'];
console.log("Authorization Header:", authHeader);
Expand All @@ -19,4 +20,4 @@ function isAuthenticated(req, res, next) {
}
}

module.exports = isAuthenticated;
module.exports = { isAuthenticated };
34 changes: 28 additions & 6 deletions backend/src/routes/userRoutes.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
const express = require('express');
const { checkEmailExists, checkPasswordCorrect, createUser , getUserID} = require('../services/userService');
const { isAuthenticated } = require('../middleware/autMiddleware');
const { checkEmailExists, checkPasswordCorrect, createUser , getUserID, makeTransaction , getBalance, getUserTransactionsByPage} = require('../services/userService');
const {isAuthenticated} = require('../middleware/autMiddleware')
const router = express.Router();
const jwt = require('jsonwebtoken');

Expand Down Expand Up @@ -72,16 +72,38 @@ router.post('/signup', async (req, res) => {
res.status(500).send({ success: false, error: error.message });
}
});
router.get('/getBalance', isAuthenticated, async (req, res) => {
const userID = req.user.id;
try {
const result = await getBalance(userID);
res.send({ result: result });
} catch (error) {
console.error('Error getting balance:', error);
res.status(500).send({ success: false, error: error.message });
}
});
router.post('/makeTransaction', isAuthenticated, async (req, res) => {
const {amount,title,description} = req.body;



router.get('/logout', async (req, res) => {
const userID = req.user.id;
try {
req.session.destroy();
await makeTransaction(userID , amount , title , description );
res.send({ success: true });
} catch (error) {
console.error('Error making transactions', error);
res.status(500).send({ success: false, error: error.message });
}
});
router.post('/getTransactionByPage' , isAuthenticated , async(req , res) =>{
const {pageNumber} = req.body;
const userID = req.user.id;
try{
const result = await getUserTransactionsByPage(userID , pageNumber);
res.status(200).send({sucess : true , result : result})
}catch{
console.error('Error when getting transactions' , error);
res.status(500).send({ success: false, error: error.message });
}
})

module.exports = router;
5 changes: 3 additions & 2 deletions backend/src/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ const isAuthenticated = require("./middleware/autMiddleware.js");


const app = express();

app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cors({
origin: function (origin, callback) {
if (!origin || allowedOrigins.indexOf(origin) !== -1) {
Expand Down Expand Up @@ -41,7 +42,7 @@ pool.connect((err) => {
}
});

app.use('/user', isAuthenticated , userRoutes);
app.use('/user', userRoutes);

const port = 4000

Expand Down
68 changes: 67 additions & 1 deletion backend/src/services/userService.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
const { system } = require('nodemon/lib/config');
const pool = require('../config/db');
const { hashPassword, comparePasswords } = require('./securePassword');
const { use } = require('../routes/userRoutes');


const getUserID = async (email) => {
Expand Down Expand Up @@ -70,7 +71,69 @@ const createUser = async (email, password) => {
throw error;
}
}
const makeTransaction = async ( userID , amount , title , description) => {
try {
const addTransactionQuery = {
text: 'INSERT INTO transactions (user_id , amount , title , description) VALUES ($1, $2, $3, $4)'
,
values : [ userID, amount , title , description ]
}
const changeBalanceQuery = {
text : 'UPDATE users SET balance = balance + $1 WHERE id = $2',
values: [amount , userID]
}
try {
const result = await pool.query(addTransactionQuery);
const result2 = await pool.query(changeBalanceQuery);
console.log(`succesfuly made transaction user_id : ${userID} , amount : ${amount} , title : ${title} , description : ${description}`)
} catch(error){
console.error('Error updating balance:', error);
}
} catch(error){
console.error("problem with decrease balance function",error);
}
}
const getBalance = async (userID) => {
try {
const query = {
text: 'SELECT balance FROM users WHERE id = $1' ,
values : [userID]
}
try {
const result = await pool.query(query);
return result.rows[0];
} catch (error){
console.error ("problem when fetching balance" , error);
}
}catch{
console.error("problem before query", error);
}
}
const getUserTransactionsByPage = async(userID , pageNumber) => {

const pageSize = 10;
const offset = (pageNumber - 1) * pageSize;
try {
const query = {
text: `
SELECT * FROM transactions
WHERE user_id = $1
ORDER BY created_at ASC
LIMIT $2
OFFSET $3
`,
values: [userID, pageSize, offset]
};
try {
const result = await pool.query(query);
return result.rows;
} catch{
console.error("error when getting transactions" , error);
}
}catch {
console.error("error in function start" , error);
}
}



Expand All @@ -80,5 +143,8 @@ module.exports = {
checkEmailExists,
checkPasswordCorrect,
createUser,
getUserID
getUserID,
makeTransaction,
getBalance,
getUserTransactionsByPage
};

0 comments on commit 6f69547

Please sign in to comment.