From f15366e5f3c0587bb95990ae89e162a77eb3a879 Mon Sep 17 00:00:00 2001 From: aaronnam79 Date: Sun, 5 May 2024 13:24:37 -0700 Subject: [PATCH 01/19] created database --- backend/checkers.db | Bin 0 -> 16384 bytes backend/sql_temp.js | 22 ++++++++++++++++++++++ package.json | 31 ++++++++++++++++--------------- 3 files changed, 38 insertions(+), 15 deletions(-) create mode 100644 backend/checkers.db create mode 100644 backend/sql_temp.js diff --git a/backend/checkers.db b/backend/checkers.db new file mode 100644 index 0000000000000000000000000000000000000000..5cc561314cd17b8ed8cfe3813930be1906601107 GIT binary patch literal 16384 zcmeI%!A`<37zgl{VTdM(7qe?QA&D_jUqCdCA)?W-gPfKkRhKXzZPDNj-@}W~=mXdm z7P1h00Q`Sp>-w$P_wBb+L-(PR8p)o=DiemClLJC2xnPVCQeGZ*@DbRv%jH4yi$BIP zIZ@wLyCB$qC$+Cy-3|x{KmY;|fB*y_009U<00I#BKLYbcPzf6i`dKxiKa?*blR9}# zwHd2fVN$+|cq`^CZe4abE8IFt2dsS;^J^Zl`>1`}ihAsZ_l{XMev`>)n)Rj17aX(6 zP|T!SPp9%pCfW#PSj-<|yU=IkXyE6~k5VNJLptxS8ueWS>y2$}Xi@t#Sv8#Zb5_W? z2fJSEhTQei6m(I$?rTrARN9|Ph1x!~v9`OLjO>G#ujl6zq4lDK+nd`>KLP>}fB*y_ z009U<00Izz00bZafh`tr`+r*dA@+xW00bZa0SG_<0uX=z1Rwwb2tZ(q1or3-*`{ + if (err) return console.error(err.message); +}); + +// sql = 'CREATE TABLE users(id INTEGER PRIMARY KEY, user_name TEXT, user_pass TEXT)'; +// db.run(sql); +// sql = 'CREATE TABLE games(id INTEGER PRIMARY KEY, player1_id INTEGER, player2_id INTEGER, game_state TEXT)'; +// db.run(sql); +// sql = 'CREATE TABLE games_history(id INTEGER PRIMARY KEY, move_number INTEGER, player_number INTEGER, piece_start TEXT, piece_end TEXT)'; +// db.run(sql); + +// sql = 'INSERT INTO games(id, player1_id, player2_id, game_state) VALUES (?, ?, ?, ?)'; +// db.run( +// sql, +// [1, 1, 2, "test"], +// (err) => { +// if (err) return console.error(err.message); +// } +// ) \ No newline at end of file diff --git a/package.json b/package.json index 0da580e..b0d683a 100644 --- a/package.json +++ b/package.json @@ -18,30 +18,31 @@ }, "dependencies": { "react": "^18.2.0", - "react-dom": "^18.2.0" + "react-dom": "^18.2.0", + "sqlite3": "^5.1.7" }, "devDependencies": { - "webpack": "^5.89.0", - "webpack-cli": "^5.1.4", - "webpack-dev-server": "^4.15.1", - "style-loader": "^3.3.3", - "css-loader": "^6.8.1", - "file-loader": "^6.2.0", - "html-loader": "^4.2.0", - "html-webpack-plugin": "^5.6.0", "@babel/core": "^7.23.6", - "babel-loader": "^9.1.3", "@babel/preset-env": "^7.23.6", "@babel/preset-react": "^7.23.3", - "react-horizontal-stacked-bar-chart": "^8.15.2", + "babel-loader": "^9.1.3", + "bootstrap": "^5.3.2", + "chai": "^5.0.0", + "css-loader": "^6.8.1", + "enzyme": "^3.11.0", "eslint": "^8.56.0", + "file-loader": "^6.2.0", + "html-loader": "^4.2.0", + "html-webpack-plugin": "^5.6.0", + "jest": "^29.7.0", "react-bootstrap": "^2.9.2", - "bootstrap": "^5.3.2", "react-bootstrap-icons": "^1.10.3", - "jest": "^29.7.0", + "react-horizontal-stacked-bar-chart": "^8.15.2", "react-test-renderer": "^18.2.0", - "enzyme": "^3.11.0", - "chai": "^5.0.0" + "style-loader": "^3.3.3", + "webpack": "^5.89.0", + "webpack-cli": "^5.1.4", + "webpack-dev-server": "^4.15.1" }, "browserslist": { "production": [ From 57337b3b7395766fb5c4081d974a52d979c823cb Mon Sep 17 00:00:00 2001 From: aaronnam79 Date: Sun, 5 May 2024 13:33:50 -0700 Subject: [PATCH 02/19] more sql functions --- backend/checkers.db | Bin 16384 -> 16384 bytes backend/server.js | 8 ++++++++ backend/sql_temp.js | 26 +++++++++++++++++++++++++- 3 files changed, 33 insertions(+), 1 deletion(-) diff --git a/backend/checkers.db b/backend/checkers.db index 5cc561314cd17b8ed8cfe3813930be1906601107..34f3c055cbd1cac12124cfb851076d5c682b5f1f 100644 GIT binary patch delta 48 zcmZo@U~Fh$oFL7}I#I@%k#%FjGI^Gd4E!HA3kp2v=jUZ)W#D9#W-3W7F3HSGUnC#^ E08Z}>NB{r; delta 45 zcmZo@U~Fh$oFL7}GEv5vk!54TGI^FS4E$d<3ktmA=iy>xW#D8KWhzN6E?FcX001V; B3{ + if (err) return console.error(err.message); +}); + // Middleware to parse JSON and urlencoded data app.use(express.json()); app.use(express.urlencoded({ extended: true })); diff --git a/backend/sql_temp.js b/backend/sql_temp.js index 8cfd114..73446a7 100644 --- a/backend/sql_temp.js +++ b/backend/sql_temp.js @@ -5,6 +5,7 @@ const db = new sqlite3.Database("./checkers.db", sqlite3.OPEN_READWRITE, (err) = if (err) return console.error(err.message); }); +// //create tables // sql = 'CREATE TABLE users(id INTEGER PRIMARY KEY, user_name TEXT, user_pass TEXT)'; // db.run(sql); // sql = 'CREATE TABLE games(id INTEGER PRIMARY KEY, player1_id INTEGER, player2_id INTEGER, game_state TEXT)'; @@ -12,6 +13,7 @@ const db = new sqlite3.Database("./checkers.db", sqlite3.OPEN_READWRITE, (err) = // sql = 'CREATE TABLE games_history(id INTEGER PRIMARY KEY, move_number INTEGER, player_number INTEGER, piece_start TEXT, piece_end TEXT)'; // db.run(sql); +// //insert data // sql = 'INSERT INTO games(id, player1_id, player2_id, game_state) VALUES (?, ?, ?, ?)'; // db.run( // sql, @@ -19,4 +21,26 @@ const db = new sqlite3.Database("./checkers.db", sqlite3.OPEN_READWRITE, (err) = // (err) => { // if (err) return console.error(err.message); // } -// ) \ No newline at end of file +// ) + +// //update data +// sql = 'UPDATE games SET game_state = ? WHERE id = ?'; +// db.run(sql, ["testing", 1], (err) => { +// if (err) return console.error(err.message); +// }); + +// //delete data +// sql = 'DELETE games WHERE WHERE id = ?'; +// db.run(sql, [1], (err) => { +// if (err) return console.error(err.message); +// }); + +//querying data, returns as dict +sql = 'SELECT * FROM games'; +db.all(sql, [], (err, rows) => { + if (err) return console.error(err.message); + rows.forEach((row) => { + console.log(row); + console.log(row["id"]); + }); +}); From 83ec50fdabd9f9478ecd8a2ccb558db330478f26 Mon Sep 17 00:00:00 2001 From: BakaOverflow Date: Mon, 6 May 2024 03:59:40 -0700 Subject: [PATCH 03/19] Branch. Started implementing the frontend for login and registration. Currently using temporary local storage to handle user/registration to handle fetch API calls for. This branch needs the sqlite database. --- backend/server.js | 34 ++++++++++---------- package.json | 1 + src/App.jsx | 76 ++++++++++++++++++++++++++++++++++++++++++++ src/Login.jsx | 50 +++++++++++++++++++++++++++++ src/Registration.jsx | 50 +++++++++++++++++++++++++++++ 5 files changed, 193 insertions(+), 18 deletions(-) create mode 100644 src/Login.jsx create mode 100644 src/Registration.jsx diff --git a/backend/server.js b/backend/server.js index 0d4257a..4715636 100644 --- a/backend/server.js +++ b/backend/server.js @@ -1,45 +1,43 @@ -// Import required libraries const express = require('express'); -require('dotenv').config(); // Load environment variables early -const sequelize = require('./config/connection'); // Adjust as needed for your DB +const cors = require('cors'); // Import CORS module +require('dotenv').config(); +const sequelize = require('./config/connection'); const session = require('express-session'); const passport = require('passport'); -require('./config/passportConfig'); // Make sure to configure Passport strategies here -const userRoutes = require('./routes/userRoutes'); // Ensure this file exists and is set up +require('./config/passportConfig'); +const userRoutes = require('./routes/userRoutes'); const app = express(); const PORT = process.env.PORT || 3000; -// Middleware to parse JSON and urlencoded data +// CORS configuration to allow requests from the frontend URL +app.use(cors({ + origin: 'http://localhost:9000', // This is the URL of your frontend application + credentials: true // Allows cookies to be sent and received +})); + +// Other middleware configurations app.use(express.json()); app.use(express.urlencoded({ extended: true })); - -// Enhanced session configuration app.use(session({ secret: process.env.SESSION_SECRET, resave: false, saveUninitialized: true, cookie: { - httpOnly: true, // Protects against client-side script accessing the cookie - secure: process.env.NODE_ENV === "production", // Cookies are sent only over HTTPS - sameSite: 'strict', // Strict sameSite setting to prevent sending the cookie along with cross-site requests - maxAge: 24 * 60 * 60 * 1000 // 24 hours + httpOnly: true, + secure: process.env.NODE_ENV === "production", + sameSite: 'strict', + maxAge: 24 * 60 * 60 * 1000 } })); -// Initialize Passport middleware app.use(passport.initialize()); app.use(passport.session()); - -// Basic route for testing server response app.get('/', (req, res) => { res.send('Checkers Game Backend is running!'); }); - -// Apply user authentication routes app.use('/api/users', userRoutes); -// Sync Sequelize models to the database, then start the server sequelize.sync({ force: false }).then(() => { app.listen(PORT, () => { console.log(`Server running on http://localhost:${PORT}`); diff --git a/package.json b/package.json index 0da580e..7523c4a 100644 --- a/package.json +++ b/package.json @@ -43,6 +43,7 @@ "enzyme": "^3.11.0", "chai": "^5.0.0" }, + "proxy": "http://localhost:3000", "browserslist": { "production": [ ">0.2%", diff --git a/src/App.jsx b/src/App.jsx index 4bbdce1..1cb226f 100644 --- a/src/App.jsx +++ b/src/App.jsx @@ -5,6 +5,81 @@ import Table from "./Table"; import PiecesCounterBar from "./PiecesCounterBar"; import * as appActions from "./AppActions"; import Settings from "./Settings"; +import Login from "./Login"; // Import the Login component +import Registration from "./Registration"; // Import the Registration component + +class App extends React.Component { + constructor(props) { + super(props); + this.state = { + table: [], + blackStarts: true, + whoPlay: "black", + tileSelected: null, + blackPieces: 12, + whitePieces: 12, + nexMoveInAnyDirection: false, + showMenu: false, + showLogin: true, // State to control login display + isAuthenticated: false // State to check if user is authenticated + }; + } + + componentDidMount() { + appActions.init(this); + } + + render() { + const { blackPieces, whitePieces, table, whoPlay, isAuthenticated, showLogin } = this.state; + if (!isAuthenticated) { + return ( +
+ {showLogin ? ( + + ) : ( + + )} + +
+ ); + } + + return ( +
+ +
+ +
{whoPlay} plays
+
+ appActions.onClick(this, evt)} /> +
+ +
+ {this.state.showMenu && } + + ); + } +} + +export default App; + + + +/* +Old App.jsx code kept in case things break: +import React from "react"; +import { List } from "react-bootstrap-icons"; +import { Button } from "react-bootstrap"; +import Table from "./Table"; +import PiecesCounterBar from "./PiecesCounterBar"; +import * as appActions from "./AppActions"; +import Settings from "./Settings"; class App extends React.Component { constructor(props) { @@ -52,3 +127,4 @@ class App extends React.Component { } export default App; +*/ \ No newline at end of file diff --git a/src/Login.jsx b/src/Login.jsx new file mode 100644 index 0000000..3b7e8a4 --- /dev/null +++ b/src/Login.jsx @@ -0,0 +1,50 @@ +import React, { useState } from 'react'; + +function Login() { + const [username, setUsername] = useState(''); + const [password, setPassword] = useState(''); + const [message, setMessage] = useState(''); + + + + const handleLogin = async (event) => { + event.preventDefault(); + try { + const response = await fetch('http://localhost:3000/api/users/login', { + method: 'POST', + headers: { + 'Content-Type': 'application/json' + }, + body: JSON.stringify({ username, password }) + }); + const data = await response.json(); + if (response.status === 200) { + setMessage('Login successful'); + } else { + setMessage(data.message || 'Login failed'); + } + } catch (error) { + setMessage('Failed to connect to the server'); + } + }; + + return ( +
+

Login

+
+ + + + +

{message}

+
+ ); +} + +export default Login; diff --git a/src/Registration.jsx b/src/Registration.jsx new file mode 100644 index 0000000..783d6d9 --- /dev/null +++ b/src/Registration.jsx @@ -0,0 +1,50 @@ +import React, { useState } from 'react'; + +function Register() { + const [username, setUsername] = useState(''); + const [password, setPassword] = useState(''); + const [message, setMessage] = useState(''); + + const handleRegister = async (event) => { + event.preventDefault(); + try { + const response = await fetch('http://localhost:3000/api/users/register', { + method: 'POST', + headers: { + 'Content-Type': 'application/json' + }, + body: JSON.stringify({ username, password }) + }); + const data = await response.json(); + if (response.status === 201) { + setMessage('Registration successful'); + } else { + throw new Error(data.message || 'Registration failed'); + } + } catch (error) { + // Assuming the error is due to server being down or unreachable + localStorage.setItem('user', JSON.stringify({username, password})); // Cache user data locally as fallback + setMessage('Failed to connect to the server, data cached locally'); + } + }; + + return ( +
+

Register

+
+ + + + +

{message}

+
+ ); +} + +export default Register; \ No newline at end of file From 75687b40956c450dfdbac8cd45174e7ed3d32d78 Mon Sep 17 00:00:00 2001 From: BakaOverflow <166342529+BakaOverflow@users.noreply.github.com> Date: Mon, 6 May 2024 10:21:40 -0700 Subject: [PATCH 04/19] Update server.js Resolving conflicts --- backend/server.js | 48 +++++++++++++++++++++++++++-------------------- 1 file changed, 28 insertions(+), 20 deletions(-) diff --git a/backend/server.js b/backend/server.js index 706917e..0c9dae6 100644 --- a/backend/server.js +++ b/backend/server.js @@ -1,49 +1,57 @@ const express = require('express'); +const cors = require('cors'); // Import CORS module require('dotenv').config(); // Load environment variables -const sequelize = require('./config/connection'); // Import the database connection - -// Passport and session management (placeholders for setup) const session = require('express-session'); const passport = require('passport'); +require('./config/passportConfig'); // Ensure Passport configuration is properly set up +const userRoutes = require('./routes/userRoutes'); // User authentication routes +const sqlite3 = require("sqlite3").verbose(); // SQLite for database interactions const app = express(); const PORT = process.env.PORT || 3000; -// Initalize SQLite -const sqlite3 = require("sqlite3").verbose(); -let sql; - -const db = new sqlite3.Database("./checkers.db", sqlite3.OPEN_READWRITE, (err) =>{ - if (err) return console.error(err.message); -}); +// CORS configuration to allow requests from the frontend URL +app.use(cors({ + origin: 'http://localhost:9000', // Adjust as needed if your frontend is at a different URL + credentials: true // Allows cookies to be sent and received +})); -// Middleware to parse JSON and urlencoded data +// Middleware for parsing JSON and URL-encoded data app.use(express.json()); app.use(express.urlencoded({ extended: true })); -// Session configuration (Adjust secret and other options as needed) +// Session configuration with enhanced security settings app.use(session({ - secret: 'super secret', // You should store this in an environment variable + secret: process.env.SESSION_SECRET, resave: false, saveUninitialized: true, + cookie: { + httpOnly: true, // Protects against client-side script accessing the cookie + secure: process.env.NODE_ENV === "production", // Ensures cookies are sent only over HTTPS + sameSite: 'strict', // Strict sameSite setting to prevent sending the cookie along with cross-site requests + maxAge: 24 * 60 * 60 * 1000 // Cookie expires in 24 hours + } })); -// Passport middleware +// Initialize Passport middleware for user authentication app.use(passport.initialize()); app.use(passport.session()); -// Import routes -const userRoutes = require('./routes/userRoutes'); // Placeholder for user authentication routes +// Initialize SQLite Database +const db = new sqlite3.Database("./checkers.db", sqlite3.OPEN_READWRITE, (err) => { + if (err) console.error(err.message); + console.log('Connected to the SQLite database.'); +}); -// Basic route for testing that the server is running +// Basic route for testing server response app.get('/', (req, res) => { res.send('Checkers Game Backend is running!'); }); -// Use routes -app.use('/api/users', userRoutes); // Placeholder for actual user route file +// Apply user authentication routes +app.use('/api/users', userRoutes); -// Sync Sequelize models to the database, then start the server +// Sync database models and start the server sequelize.sync({ force: false }).then(() => { app.listen(PORT, () => { console.log(`Server running on http://localhost:${PORT}`); From eb2e475c5f4bd326f644557e7337ed812f5136a5 Mon Sep 17 00:00:00 2001 From: BakaOverflow Date: Mon, 6 May 2024 14:28:44 -0700 Subject: [PATCH 05/19] Modified database to work with backend. Frontend and backend are able to interact with database. Need to fully implement frontend and backend that interacts with users information before starting checkers game. --- backend/.env | 8 ++- backend/checkers.db | Bin 16384 -> 24576 bytes backend/config/connection.js | 12 ++-- backend/models/user.js | 40 ++++++++++++-- backend/routes/userRoutes.js | 103 +++++++++++++++++------------------ backend/server.js | 11 ++-- backend/sql_temp.js | 46 ---------------- 7 files changed, 97 insertions(+), 123 deletions(-) delete mode 100644 backend/sql_temp.js diff --git a/backend/.env b/backend/.env index fd02fdb..d7847c4 100644 --- a/backend/.env +++ b/backend/.env @@ -1,7 +1,9 @@ SESSION_SECRET=your_super_secret -DB_PATH=./path_to_your_sqlite.db // Path to your SQLite database file -PORT=3000 # Optional as you use process.env.PORT || 3000 in server.js - +# Bug, path wasn't given correct path +# DB_PATH=./path_to_your_sqlite.db // Path to your SQLite database file +DB_PATH=./checkers.db +#PORT=3000 # Optional as you use process.env.PORT || 3000 in server.js +PORT=3000 # You can comment out these lines if you're switching from PostgreSQL to SQLite # DB_USER=your_database_user # DB_PASS=your_database_password diff --git a/backend/checkers.db b/backend/checkers.db index 34f3c055cbd1cac12124cfb851076d5c682b5f1f..32add3eef9de7113553ce4f69809590d9dc49d42 100644 GIT binary patch delta 452 zcmZo@U~D+RI6+#Fi-CcG4Tzb5m=VODsADY7#h_QTh?kFzfrYo3fnSlYoVS_(EdSY! zjl8@DjSMX8;^N|rjqxRkNja&d#i>QbV1m^-$kj2#RUyRD$;VXzETqAupfK5&U)%vm zg9P#tb5j*UTq8mh{QQA9)W=65)Xy_8)Kv$lpdhihxIDio1yuo;CjVT9!ikN!o6Gss z7+Ls#Fc?g1)X~>uWfQj*XJp9COG&LLF3ia+NsUh|Ey)M-=CRPUFM%I%2Tot246+;6RXP4wOJ+sQ9WWRz! zXAfWh(o}c-l2ViKuu#X~%EW;D9M`lEi}b`SLvxqxvNSUzpW=*sBTq(F23epfsl_EA zd!a`8W*NArRV12Zr3f;Dmb!cUo2I)OM^+g->zT`?`J`oJCA%3_x<@4E nXQu_a`GX>biT@1){}=u@KsP?%7hz`>W&}EriJMuL6J`Yf$UuM! delta 147 zcmZoTz}V2hI6+#Fm4ShQ1&CpQd7_T7Fe`&z(IQ@;5Hnvn1OHrpMZWUQi~_8Do6Gss z7_|}^*~P`h85 { - try { const { username, password } = req.body; - const salt = await bcrypt.genSalt(10); // Generate salt - const hash = await bcrypt.hash(password, salt); // Hash the password with the salt + try { + const salt = await bcrypt.genSalt(10); + const hash = await bcrypt.hash(password, salt); - // Create a new user with hashed password - const newUser = await User.create({ - username, - password: hash - }); + const newUser = await User.create({ + username, + password: hash + }); - res.status(201).json({ - success: true, - message: "User registered successfully", - data: newUser - }); - } catch (error) { - res.status(500).json({ - success: false, - message: "Error registering new user", - error: error.message - }); - } + res.status(201).json({ + success: true, + message: "User registered successfully", + data: newUser + }); + } catch (error) { + res.status(500).json({ + success: false, + message: "Error registering new user", + error: error.message + }); + } }); -// Route for user login router.post('/login', async (req, res) => { - try { - const { username, password } = req.body; - // Find user by username - const user = await User.findOne({ where: { username } }); - if (!user) { - return res.status(404).json({ - success: false, - message: "User not found" - }); - } + try { + const { username, password } = req.body; + const user = await User.findOne({ where: { username } }); + if (!user) { + return res.status(404).json({ + success: false, + message: "User not found" + }); + } - // Compare provided password with stored hashed password - const isMatch = await bcrypt.compare(password, user.password); - if (isMatch) { - res.json({ - success: true, - message: "Login successful" - }); - } else { - res.status(401).json({ - success: false, - message: "Incorrect password" - }); + const isMatch = await bcrypt.compare(password, user.password); + if (isMatch) { + res.json({ + success: true, + message: "Login successful" + }); + } else { + res.status(401).json({ + success: false, + message: "Incorrect password" + }); + } + } catch (error) { + res.status(500).json({ + success: false, + message: "Error logging in", + error: error.message + }); } - } catch (error) { - res.status(500).json({ - success: false, - message: "Error logging in", - error: error.message - }); - } }); module.exports = router; diff --git a/backend/server.js b/backend/server.js index 0c9dae6..c0a9656 100644 --- a/backend/server.js +++ b/backend/server.js @@ -51,11 +51,8 @@ app.get('/', (req, res) => { // Apply user authentication routes app.use('/api/users', userRoutes); -// Sync database models and start the server -sequelize.sync({ force: false }).then(() => { - app.listen(PORT, () => { - console.log(`Server running on http://localhost:${PORT}`); - }); -}).catch((error) => { - console.error("Failed to sync database:", error); +// Instead of Sequelize, maybe some other DB initialization or sync process +// For now, just start the server +app.listen(PORT, () => { + console.log(`Server running on http://localhost:${PORT}`); }); diff --git a/backend/sql_temp.js b/backend/sql_temp.js deleted file mode 100644 index 73446a7..0000000 --- a/backend/sql_temp.js +++ /dev/null @@ -1,46 +0,0 @@ -const sqlite3 = require("sqlite3").verbose(); -let sql; - -const db = new sqlite3.Database("./checkers.db", sqlite3.OPEN_READWRITE, (err) =>{ - if (err) return console.error(err.message); -}); - -// //create tables -// sql = 'CREATE TABLE users(id INTEGER PRIMARY KEY, user_name TEXT, user_pass TEXT)'; -// db.run(sql); -// sql = 'CREATE TABLE games(id INTEGER PRIMARY KEY, player1_id INTEGER, player2_id INTEGER, game_state TEXT)'; -// db.run(sql); -// sql = 'CREATE TABLE games_history(id INTEGER PRIMARY KEY, move_number INTEGER, player_number INTEGER, piece_start TEXT, piece_end TEXT)'; -// db.run(sql); - -// //insert data -// sql = 'INSERT INTO games(id, player1_id, player2_id, game_state) VALUES (?, ?, ?, ?)'; -// db.run( -// sql, -// [1, 1, 2, "test"], -// (err) => { -// if (err) return console.error(err.message); -// } -// ) - -// //update data -// sql = 'UPDATE games SET game_state = ? WHERE id = ?'; -// db.run(sql, ["testing", 1], (err) => { -// if (err) return console.error(err.message); -// }); - -// //delete data -// sql = 'DELETE games WHERE WHERE id = ?'; -// db.run(sql, [1], (err) => { -// if (err) return console.error(err.message); -// }); - -//querying data, returns as dict -sql = 'SELECT * FROM games'; -db.all(sql, [], (err, rows) => { - if (err) return console.error(err.message); - rows.forEach((row) => { - console.log(row); - console.log(row["id"]); - }); -}); From 5be4d1f2908bc0df83e64e8647edec5c59789d75 Mon Sep 17 00:00:00 2001 From: aaronnam79 Date: Mon, 6 May 2024 14:55:33 -0700 Subject: [PATCH 06/19] login function created --- src/App.jsx | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/src/App.jsx b/src/App.jsx index 1cb226f..c74119e 100644 --- a/src/App.jsx +++ b/src/App.jsx @@ -8,6 +8,42 @@ import Settings from "./Settings"; import Login from "./Login"; // Import the Login component import Registration from "./Registration"; // Import the Registration component +const API_URL = "http://localhost:3000/"; +const LOGIN_ENDPOINT = "api/users/"; + +// login function (should probably move to a better place) + +function userLogin(inputUser, inputPass) { + const sendLogin = { + username: inputUser, + password: inputPass, + }; + fetch(API_URL + LOGIN_ENDPOINT, { + method: 'POST', + headers: { + 'Content-Type': "application/json", + }, + body: JSON.stringify(sendLogin), + }) + .then((response) => { + if (!response.ok) { + throw new Error(response.status); + } + return response.json() + }) + .then(data => { + setAlertMessage("Logging in"); + setOpen(true); + localStorage.setItem('username', inputUser); + navigate("/"); + }) + .catch(error => { + console.error('Error', error); + setAlertMessage("Failed to login"); + setOpen(true); + }); +} + class App extends React.Component { constructor(props) { super(props); From 257b43ed80754ca8d1b366c4322daa6a86784f51 Mon Sep 17 00:00:00 2001 From: aaronnam79 Date: Mon, 6 May 2024 14:56:49 -0700 Subject: [PATCH 07/19] fix: removed redundancy --- src/App.jsx | 36 ------------------------------------ 1 file changed, 36 deletions(-) diff --git a/src/App.jsx b/src/App.jsx index c74119e..1cb226f 100644 --- a/src/App.jsx +++ b/src/App.jsx @@ -8,42 +8,6 @@ import Settings from "./Settings"; import Login from "./Login"; // Import the Login component import Registration from "./Registration"; // Import the Registration component -const API_URL = "http://localhost:3000/"; -const LOGIN_ENDPOINT = "api/users/"; - -// login function (should probably move to a better place) - -function userLogin(inputUser, inputPass) { - const sendLogin = { - username: inputUser, - password: inputPass, - }; - fetch(API_URL + LOGIN_ENDPOINT, { - method: 'POST', - headers: { - 'Content-Type': "application/json", - }, - body: JSON.stringify(sendLogin), - }) - .then((response) => { - if (!response.ok) { - throw new Error(response.status); - } - return response.json() - }) - .then(data => { - setAlertMessage("Logging in"); - setOpen(true); - localStorage.setItem('username', inputUser); - navigate("/"); - }) - .catch(error => { - console.error('Error', error); - setAlertMessage("Failed to login"); - setOpen(true); - }); -} - class App extends React.Component { constructor(props) { super(props); From 07836eafcfd150f21ce89c303c8cb3e576e0fd8c Mon Sep 17 00:00:00 2001 From: aaronnam79 Date: Mon, 6 May 2024 15:40:57 -0700 Subject: [PATCH 08/19] game route created --- src/Game.jsx | 45 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 src/Game.jsx diff --git a/src/Game.jsx b/src/Game.jsx new file mode 100644 index 0000000..b55ae34 --- /dev/null +++ b/src/Game.jsx @@ -0,0 +1,45 @@ +import { List } from "react-bootstrap-icons"; +import { Button } from "react-bootstrap"; +import { useNavigate } from 'react-router-dom'; +import Table from "./Table"; +import PiecesCounterBar from "./PiecesCounterBar"; +import * as appActions from "./AppActions"; +import Settings from "./Settings"; + +export default function Game() { + this.state = { + table: [], + blackStarts: true, + whoPlay: "black", + tileSelected: null, + blackPieces: 12, + whitePieces: 12, + nexMoveInAnyDirection: false, + showMenu: false, + showLogin: true, // State to control login display + isAuthenticated: false // State to check if user is authenticated + }; + + if (!isAuthenticated) { + useNavigate("/login") //change to proper route + } + + return ( +
+ +
+ +
{whoPlay} plays
+
+
appActions.onClick(this, evt)} /> +
+ +
+ {this.state.showMenu && } + + ); +} From c236e3c6e2cacebc4b5b712857af06f1ad8e13bf Mon Sep 17 00:00:00 2001 From: BakaOverflow Date: Mon, 6 May 2024 15:43:47 -0700 Subject: [PATCH 09/19] Updated App.jsx file --- src/App.jsx | 64 +++++++++++++++++++++++++++++++---------------------- 1 file changed, 37 insertions(+), 27 deletions(-) diff --git a/src/App.jsx b/src/App.jsx index 1cb226f..e6f45db 100644 --- a/src/App.jsx +++ b/src/App.jsx @@ -1,17 +1,20 @@ import React from "react"; -import { List } from "react-bootstrap-icons"; -import { Button } from "react-bootstrap"; +import { BrowserRouter as Router, Routes, Route } from 'react-router-dom'; +import io from "socket.io-client"; + import Table from "./Table"; import PiecesCounterBar from "./PiecesCounterBar"; import * as appActions from "./AppActions"; import Settings from "./Settings"; -import Login from "./Login"; // Import the Login component -import Registration from "./Registration"; // Import the Registration component +import Home from './routes/Home'; +import Login from './routes/Login'; +import Game from './routes/Game'; class App extends React.Component { constructor(props) { super(props); this.state = { + socket: null, table: [], blackStarts: true, whoPlay: "black", @@ -20,50 +23,56 @@ class App extends React.Component { whitePieces: 12, nexMoveInAnyDirection: false, showMenu: false, - showLogin: true, // State to control login display - isAuthenticated: false // State to check if user is authenticated + isAuthenticated: false // Assume authentication state can be derived from somewhere }; } componentDidMount() { + this.initSocket(); appActions.init(this); } - render() { - const { blackPieces, whitePieces, table, whoPlay, isAuthenticated, showLogin } = this.state; - if (!isAuthenticated) { - return ( -
- {showLogin ? ( - - ) : ( - - )} - -
- ); - } + initSocket = () => { + const socket = io('http://localhost:3000'); + socket.on('game update', (move) => { + console.log("Received game update", move); + // Here you would handle updating the game state based on the move received + }); + this.setState({ socket }); + }; + renderGame = () => { + const { blackPieces, whitePieces, table, whoPlay } = this.state; return (
- +
{whoPlay} plays
appActions.onClick(this, evt)} />
- +
{this.state.showMenu && } ); + }; + + render() { + return ( + + + } /> + } /> + + + + ); } } @@ -71,6 +80,7 @@ export default App; + /* Old App.jsx code kept in case things break: import React from "react"; From 4db9d1810a7ad5428596850f88f6fe2caade7609 Mon Sep 17 00:00:00 2001 From: aaronnam79 Date: Mon, 6 May 2024 16:36:09 -0700 Subject: [PATCH 10/19] turned game into class --- src/Game.jsx | 61 +++++++++++++++++++++++++++++++--------------------- 1 file changed, 37 insertions(+), 24 deletions(-) diff --git a/src/Game.jsx b/src/Game.jsx index b55ae34..5fd8a33 100644 --- a/src/Game.jsx +++ b/src/Game.jsx @@ -1,3 +1,4 @@ +import React from "react"; import { List } from "react-bootstrap-icons"; import { Button } from "react-bootstrap"; import { useNavigate } from 'react-router-dom'; @@ -6,8 +7,10 @@ import PiecesCounterBar from "./PiecesCounterBar"; import * as appActions from "./AppActions"; import Settings from "./Settings"; -export default function Game() { - this.state = { +class Game extends React.Component { + constructor(props) { + super(props); + this.state = { table: [], blackStarts: true, whoPlay: "black", @@ -16,30 +19,40 @@ export default function Game() { whitePieces: 12, nexMoveInAnyDirection: false, showMenu: false, - showLogin: true, // State to control login display isAuthenticated: false // State to check if user is authenticated - }; + }; + } - if (!isAuthenticated) { - useNavigate("/login") //change to proper route + componentDidMount() { + appActions.init(this); } - return ( -
- -
- -
{whoPlay} plays
-
-
appActions.onClick(this, evt)} /> -
- -
- {this.state.showMenu && } - - ); + render() { + const { blackPieces, whitePieces, table, whoPlay, isAuthenticated, showLogin } = this.state; + + if (!isAuthenticated) { + useNavigate("/login") //change to proper route + } + + return ( +
+ +
+ +
{whoPlay} plays
+
+
appActions.onClick(this, evt)} /> +
+ +
+ {this.state.showMenu && } + + ); + }; } + +export default Game; \ No newline at end of file From da7374541f52d284feb6f056433b6d11ca3ee15c Mon Sep 17 00:00:00 2001 From: BakaOverflow Date: Mon, 6 May 2024 17:04:41 -0700 Subject: [PATCH 11/19] updated package.json to work in heroku --- package.json | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/package.json b/package.json index 0983a26..456e84a 100644 --- a/package.json +++ b/package.json @@ -7,6 +7,10 @@ "checkers" ], "license": "MIT", + "engines": { + "node": "20.x", + "npm": "10.5.0" + }, "scripts": { "start": "webpack-dev-server", "build": "webpack --mode production", @@ -19,6 +23,9 @@ "dependencies": { "react": "^18.2.0", "react-dom": "^18.2.0", + "react-router-dom": "^6.23.0", + "socket.io": "^4.7.5", + "socket.io-client": "^4.7.5", "sqlite3": "^5.1.7" }, "devDependencies": { From bf1dd9073bb92c06b7672d1145ab49c0c4a8616a Mon Sep 17 00:00:00 2001 From: BakaOverflow Date: Mon, 6 May 2024 17:23:20 -0700 Subject: [PATCH 12/19] Updated to prevent heroku build errors. --- backend/server.js | 34 +++++++++++++++++++++++++++++----- src/routes/Game.jsx | 0 src/routes/Home.jsx | 0 src/routes/Login.jsx | 0 4 files changed, 29 insertions(+), 5 deletions(-) create mode 100644 src/routes/Game.jsx create mode 100644 src/routes/Home.jsx create mode 100644 src/routes/Login.jsx diff --git a/backend/server.js b/backend/server.js index c0a9656..bff0e33 100644 --- a/backend/server.js +++ b/backend/server.js @@ -1,5 +1,9 @@ +// Modified to allow websockets. + const express = require('express'); const cors = require('cors'); // Import CORS module +const http = require('http'); +const socketIo = require('socket.io'); require('dotenv').config(); // Load environment variables const session = require('express-session'); const passport = require('passport'); @@ -8,11 +12,18 @@ const userRoutes = require('./routes/userRoutes'); // User authentication routes const sqlite3 = require("sqlite3").verbose(); // SQLite for database interactions const app = express(); -const PORT = process.env.PORT || 3000; +const server = http.createServer(app); // Create HTTP server passing the Express app +const io = socketIo(server, { + cors: { + origin: 'http://localhost:9000', + methods: ["GET", "POST"], + credentials: true + } +}); // Initialize Socket.IO with the server instance // CORS configuration to allow requests from the frontend URL app.use(cors({ - origin: 'http://localhost:9000', // Adjust as needed if your frontend is at a different URL + origin: 'http://localhost:9000', credentials: true // Allows cookies to be sent and received })); @@ -43,6 +54,20 @@ const db = new sqlite3.Database("./checkers.db", sqlite3.OPEN_READWRITE, (err) = console.log('Connected to the SQLite database.'); }); +// WebSocket connection handler +io.on('connection', (socket) => { + console.log('New client connected'); + + socket.on('move', (data) => { + console.log('Move received:', data); + io.emit('move', data); // Broadcast move to all connected clients + }); + + socket.on('disconnect', () => { + console.log('Client disconnected'); + }); +}); + // Basic route for testing server response app.get('/', (req, res) => { res.send('Checkers Game Backend is running!'); @@ -51,8 +76,7 @@ app.get('/', (req, res) => { // Apply user authentication routes app.use('/api/users', userRoutes); -// Instead of Sequelize, maybe some other DB initialization or sync process -// For now, just start the server -app.listen(PORT, () => { +// Start both HTTP and WebSocket server on the same port +server.listen(PORT, () => { console.log(`Server running on http://localhost:${PORT}`); }); diff --git a/src/routes/Game.jsx b/src/routes/Game.jsx new file mode 100644 index 0000000..e69de29 diff --git a/src/routes/Home.jsx b/src/routes/Home.jsx new file mode 100644 index 0000000..e69de29 diff --git a/src/routes/Login.jsx b/src/routes/Login.jsx new file mode 100644 index 0000000..e69de29 From 9f59fc70fc49f10b033e54e4a38ff77650325da0 Mon Sep 17 00:00:00 2001 From: aaronnam79 Date: Mon, 6 May 2024 17:42:01 -0700 Subject: [PATCH 13/19] fixed routes --- src/App.jsx | 6 +++--- src/routes/Game.jsx | 0 src/routes/Home.jsx | 0 src/routes/Login.jsx | 0 4 files changed, 3 insertions(+), 3 deletions(-) delete mode 100644 src/routes/Game.jsx delete mode 100644 src/routes/Home.jsx delete mode 100644 src/routes/Login.jsx diff --git a/src/App.jsx b/src/App.jsx index e6f45db..75e95be 100644 --- a/src/App.jsx +++ b/src/App.jsx @@ -6,9 +6,9 @@ import Table from "./Table"; import PiecesCounterBar from "./PiecesCounterBar"; import * as appActions from "./AppActions"; import Settings from "./Settings"; -import Home from './routes/Home'; -import Login from './routes/Login'; -import Game from './routes/Game'; +import Home from './Home'; +import Login from './Login'; +import Game from './Game'; class App extends React.Component { constructor(props) { diff --git a/src/routes/Game.jsx b/src/routes/Game.jsx deleted file mode 100644 index e69de29..0000000 diff --git a/src/routes/Home.jsx b/src/routes/Home.jsx deleted file mode 100644 index e69de29..0000000 diff --git a/src/routes/Login.jsx b/src/routes/Login.jsx deleted file mode 100644 index e69de29..0000000 From 9f08a6dedf9b63093a6c4e3e46c049b7ab09a795 Mon Sep 17 00:00:00 2001 From: aaronnam79 Date: Mon, 6 May 2024 18:01:11 -0700 Subject: [PATCH 14/19] fix: home module not found --- src/App.jsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/App.jsx b/src/App.jsx index 75e95be..24bfbc6 100644 --- a/src/App.jsx +++ b/src/App.jsx @@ -6,7 +6,7 @@ import Table from "./Table"; import PiecesCounterBar from "./PiecesCounterBar"; import * as appActions from "./AppActions"; import Settings from "./Settings"; -import Home from './Home'; +//import Home from './Home'; import Login from './Login'; import Game from './Game'; From e24a7fe13ed3ab37631403792e3b18ee422585b6 Mon Sep 17 00:00:00 2001 From: aaronnam79 Date: Mon, 6 May 2024 18:07:51 -0700 Subject: [PATCH 15/19] route fix --- src/App.jsx | 135 +++++++++++++++++++++++++++----------------------- src/index.jsx | 1 + 2 files changed, 74 insertions(+), 62 deletions(-) diff --git a/src/App.jsx b/src/App.jsx index 24bfbc6..92b7212 100644 --- a/src/App.jsx +++ b/src/App.jsx @@ -10,73 +10,84 @@ import Settings from "./Settings"; import Login from './Login'; import Game from './Game'; -class App extends React.Component { - constructor(props) { - super(props); - this.state = { - socket: null, - table: [], - blackStarts: true, - whoPlay: "black", - tileSelected: null, - blackPieces: 12, - whitePieces: 12, - nexMoveInAnyDirection: false, - showMenu: false, - isAuthenticated: false // Assume authentication state can be derived from somewhere - }; - } +export default function App() { + return ( + + + } /> + } /> + + + ); +} - componentDidMount() { - this.initSocket(); - appActions.init(this); - } +// class App extends React.Component { +// constructor(props) { +// super(props); +// this.state = { +// socket: null, +// table: [], +// blackStarts: true, +// whoPlay: "black", +// tileSelected: null, +// blackPieces: 12, +// whitePieces: 12, +// nexMoveInAnyDirection: false, +// showMenu: false, +// isAuthenticated: false // Assume authentication state can be derived from somewhere +// }; +// } - initSocket = () => { - const socket = io('http://localhost:3000'); - socket.on('game update', (move) => { - console.log("Received game update", move); - // Here you would handle updating the game state based on the move received - }); - this.setState({ socket }); - }; +// componentDidMount() { +// this.initSocket(); +// appActions.init(this); +// } - renderGame = () => { - const { blackPieces, whitePieces, table, whoPlay } = this.state; - return ( -
- -
- -
{whoPlay} plays
-
-
appActions.onClick(this, evt)} /> -
- -
- {this.state.showMenu && } - - ); - }; +// initSocket = () => { +// const socket = io('http://localhost:3000'); +// socket.on('game update', (move) => { +// console.log("Received game update", move); +// // Here you would handle updating the game state based on the move received +// }); +// this.setState({ socket }); +// }; - render() { - return ( - - - } /> - } /> - - - - ); - } -} +// renderGame = () => { +// const { blackPieces, whitePieces, table, whoPlay } = this.state; +// return ( +//
+// +//
+// +//
{whoPlay} plays
+//
+//
appActions.onClick(this, evt)} /> +//
+// +//
+// {this.state.showMenu && } +// +// ); +// }; -export default App; +// render() { +// return ( +// +// +// } /> +// } /> +// +// +// +// ); +// } +// } + +// export default App; diff --git a/src/index.jsx b/src/index.jsx index 252d875..6ffb94f 100644 --- a/src/index.jsx +++ b/src/index.jsx @@ -1,4 +1,5 @@ import React from "react"; +import ReactDOM from 'react-dom/client'; import { createRoot } from "react-dom/client"; import App from "./App"; import "bootstrap/dist/css/bootstrap.min.css"; From f648e568cfbd5850d085694e35da208d7528e48f Mon Sep 17 00:00:00 2001 From: BakaOverflow Date: Mon, 6 May 2024 18:36:02 -0700 Subject: [PATCH 16/19] Update npm start script for heroku --- backend/server.js | 44 ++++++++++++++++++++++---------------------- package.json | 7 +++++-- 2 files changed, 27 insertions(+), 24 deletions(-) diff --git a/backend/server.js b/backend/server.js index bff0e33..359215f 100644 --- a/backend/server.js +++ b/backend/server.js @@ -1,30 +1,29 @@ -// Modified to allow websockets. - const express = require('express'); -const cors = require('cors'); // Import CORS module +const cors = require('cors'); const http = require('http'); const socketIo = require('socket.io'); -require('dotenv').config(); // Load environment variables +const path = require('path'); +require('dotenv').config(); const session = require('express-session'); const passport = require('passport'); -require('./config/passportConfig'); // Ensure Passport configuration is properly set up -const userRoutes = require('./routes/userRoutes'); // User authentication routes -const sqlite3 = require("sqlite3").verbose(); // SQLite for database interactions +require('./config/passportConfig'); +const userRoutes = require('./routes/userRoutes'); +const sqlite3 = require("sqlite3").verbose(); const app = express(); -const server = http.createServer(app); // Create HTTP server passing the Express app +const server = http.createServer(app); const io = socketIo(server, { cors: { - origin: 'http://localhost:9000', + origin: "*", // Adjust according to your frontend's actual deployment URL methods: ["GET", "POST"], credentials: true } -}); // Initialize Socket.IO with the server instance +}); // CORS configuration to allow requests from the frontend URL app.use(cors({ - origin: 'http://localhost:9000', - credentials: true // Allows cookies to be sent and received + origin: "*", // Adjust according to your frontend's actual deployment URL + credentials: true })); // Middleware for parsing JSON and URL-encoded data @@ -37,10 +36,10 @@ app.use(session({ resave: false, saveUninitialized: true, cookie: { - httpOnly: true, // Protects against client-side script accessing the cookie - secure: process.env.NODE_ENV === "production", // Ensures cookies are sent only over HTTPS - sameSite: 'strict', // Strict sameSite setting to prevent sending the cookie along with cross-site requests - maxAge: 24 * 60 * 60 * 1000 // Cookie expires in 24 hours + httpOnly: true, + secure: process.env.NODE_ENV === "production", + sameSite: 'strict', + maxAge: 24 * 60 * 60 * 1000 } })); @@ -57,26 +56,27 @@ const db = new sqlite3.Database("./checkers.db", sqlite3.OPEN_READWRITE, (err) = // WebSocket connection handler io.on('connection', (socket) => { console.log('New client connected'); - socket.on('move', (data) => { console.log('Move received:', data); io.emit('move', data); // Broadcast move to all connected clients }); - socket.on('disconnect', () => { console.log('Client disconnected'); }); }); -// Basic route for testing server response -app.get('/', (req, res) => { - res.send('Checkers Game Backend is running!'); +// Serve static files from the React app +app.use(express.static(path.join(__dirname, '../build'))); + +// The "catchall" handler: for any request that doesn't match one above, send back React's index.html file. +app.get('*', (req, res) => { + res.sendFile(path.join(__dirname, '../build/index.html')); }); // Apply user authentication routes app.use('/api/users', userRoutes); -// Start both HTTP and WebSocket server on the same port +const PORT = process.env.PORT || 3000; server.listen(PORT, () => { console.log(`Server running on http://localhost:${PORT}`); }); diff --git a/package.json b/package.json index 456e84a..eed6b1c 100644 --- a/package.json +++ b/package.json @@ -12,8 +12,10 @@ "npm": "10.5.0" }, "scripts": { - "start": "webpack-dev-server", - "build": "webpack --mode production", + "start": "node backend/server.js", + "dev": "webpack-dev-server", + "build": "react-scripts build", + "heroku-postbuild": "npm run build", "test": "jest" }, "author": { @@ -21,6 +23,7 @@ "email": "George@dodgeit.com" }, "dependencies": { + "express": "^4.19.2", "react": "^18.2.0", "react-dom": "^18.2.0", "react-router-dom": "^6.23.0", From b68e0dce2b92a1ffa0cb3b658807cd5f6476d628 Mon Sep 17 00:00:00 2001 From: aaronnam79 Date: Mon, 6 May 2024 18:37:20 -0700 Subject: [PATCH 17/19] added register button --- src/App.jsx | 2 ++ src/Game.jsx | 2 +- src/Login.jsx | 9 ++++++++- src/Registration.jsx | 7 +++++++ 4 files changed, 18 insertions(+), 2 deletions(-) diff --git a/src/App.jsx b/src/App.jsx index 92b7212..3d9951b 100644 --- a/src/App.jsx +++ b/src/App.jsx @@ -8,6 +8,7 @@ import * as appActions from "./AppActions"; import Settings from "./Settings"; //import Home from './Home'; import Login from './Login'; +import Registration from './Registration'; import Game from './Game'; export default function App() { @@ -15,6 +16,7 @@ export default function App() { } /> + } /> } /> diff --git a/src/Game.jsx b/src/Game.jsx index 5fd8a33..2c95ab3 100644 --- a/src/Game.jsx +++ b/src/Game.jsx @@ -31,7 +31,7 @@ class Game extends React.Component { const { blackPieces, whitePieces, table, whoPlay, isAuthenticated, showLogin } = this.state; if (!isAuthenticated) { - useNavigate("/login") //change to proper route + useNavigate("/") //change to proper route } return ( diff --git a/src/Login.jsx b/src/Login.jsx index 3b7e8a4..08bb8e4 100644 --- a/src/Login.jsx +++ b/src/Login.jsx @@ -1,13 +1,19 @@ import React, { useState } from 'react'; +import { useNavigate } from 'react-router-dom'; function Login() { const [username, setUsername] = useState(''); const [password, setPassword] = useState(''); const [message, setMessage] = useState(''); + const navigate = useNavigate(); - + const handleRegisterClick = () => { + navigate("/register"); + }; const handleLogin = async (event) => { + + event.preventDefault(); try { const response = await fetch('http://localhost:3000/api/users/login', { @@ -43,6 +49,7 @@ function Login() {

{message}

+ ); } diff --git a/src/Registration.jsx b/src/Registration.jsx index 783d6d9..553ab82 100644 --- a/src/Registration.jsx +++ b/src/Registration.jsx @@ -1,9 +1,15 @@ import React, { useState } from 'react'; +import { useNavigate } from 'react-router-dom'; function Register() { const [username, setUsername] = useState(''); const [password, setPassword] = useState(''); const [message, setMessage] = useState(''); + const navigate = useNavigate(); + + const handleLoginClick = () => { + navigate("/"); + }; const handleRegister = async (event) => { event.preventDefault(); @@ -43,6 +49,7 @@ function Register() {

{message}

+ ); } From 3f57ba6df280ec83cbb885353e6726701677c07f Mon Sep 17 00:00:00 2001 From: aaronnam79 Date: Mon, 6 May 2024 18:41:15 -0700 Subject: [PATCH 18/19] route bugfix --- src/Game.jsx | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/Game.jsx b/src/Game.jsx index 2c95ab3..fa5650a 100644 --- a/src/Game.jsx +++ b/src/Game.jsx @@ -7,6 +7,7 @@ import PiecesCounterBar from "./PiecesCounterBar"; import * as appActions from "./AppActions"; import Settings from "./Settings"; + class Game extends React.Component { constructor(props) { super(props); @@ -29,9 +30,10 @@ class Game extends React.Component { render() { const { blackPieces, whitePieces, table, whoPlay, isAuthenticated, showLogin } = this.state; + const navigate = useNavigate(); if (!isAuthenticated) { - useNavigate("/") //change to proper route + navigate("/") //change to proper route } return ( From b39e97b9363bb8cfe3e7bfd1d918afe1441dadee Mon Sep 17 00:00:00 2001 From: aaronnam79 Date: Mon, 6 May 2024 18:54:54 -0700 Subject: [PATCH 19/19] added test button to login --- src/Game.jsx | 7 +++---- src/Login.jsx | 5 +++++ 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/src/Game.jsx b/src/Game.jsx index fa5650a..5f8a8d2 100644 --- a/src/Game.jsx +++ b/src/Game.jsx @@ -30,11 +30,10 @@ class Game extends React.Component { render() { const { blackPieces, whitePieces, table, whoPlay, isAuthenticated, showLogin } = this.state; - const navigate = useNavigate(); - if (!isAuthenticated) { - navigate("/") //change to proper route - } + // if (!isAuthenticated) { + // navigate("/") //change to proper route + // } return (
diff --git a/src/Login.jsx b/src/Login.jsx index 08bb8e4..b2ff2b7 100644 --- a/src/Login.jsx +++ b/src/Login.jsx @@ -11,6 +11,10 @@ function Login() { navigate("/register"); }; + const testButton = () => { + navigate("/game"); + }; + const handleLogin = async (event) => { @@ -50,6 +54,7 @@ function Login() {

{message}

+
); }