Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
f15366e
created database
Agawaen May 5, 2024
57337b3
more sql functions
Agawaen May 5, 2024
83ec50f
Branch. Started implementing the frontend for login and registration.…
BakaOverflow May 6, 2024
75687b4
Update server.js
BakaOverflow May 6, 2024
2e68ae6
Merge branch 'main-Frontend-backend-user-registration-login' into fea…
BakaOverflow May 6, 2024
b5a23c3
Merge pull request #3 from BakaOverflow/feature/database
BakaOverflow May 6, 2024
eb2e475
Modified database to work with backend. Frontend and backend are able…
BakaOverflow May 6, 2024
5be4d1f
login function created
Agawaen May 6, 2024
257b43e
fix: removed redundancy
Agawaen May 6, 2024
07836ea
game route created
Agawaen May 6, 2024
c236e3c
Updated App.jsx file
BakaOverflow May 6, 2024
4db9d18
turned game into class
Agawaen May 6, 2024
a4afdf1
Merge branch 'main-Frontend-backend-user-registration-login' of https…
Agawaen May 6, 2024
da73745
updated package.json to work in heroku
BakaOverflow May 7, 2024
bf1dd90
Updated to prevent heroku build errors.
BakaOverflow May 7, 2024
9f59fc7
fixed routes
Agawaen May 7, 2024
9f08a6d
fix: home module not found
Agawaen May 7, 2024
e24a7fe
route fix
Agawaen May 7, 2024
f648e56
Update npm start script for heroku
BakaOverflow May 7, 2024
b68e0dc
added register button
Agawaen May 7, 2024
aeabe6a
Merge branch 'main-Frontend-backend-user-registration-login' of https…
Agawaen May 7, 2024
3f57ba6
route bugfix
Agawaen May 7, 2024
b39e97b
added test button to login
Agawaen May 7, 2024
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
8 changes: 5 additions & 3 deletions backend/.env
Original file line number Diff line number Diff line change
@@ -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
Expand Down
Binary file added backend/checkers.db
Binary file not shown.
12 changes: 4 additions & 8 deletions backend/config/connection.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,11 @@
// Import the necessary libraries
// Updated for use with sqlite database
// config/connection.js
const { Sequelize } = require('sequelize');


// Use dotenv to load the path from .env file
require('dotenv').config();

// Set up the SQLite database connection using Sequelize
const sequelize = new Sequelize({
dialect: 'sqlite',
storage: process.env.DB_PATH // Path to the SQLite file
dialect: 'sqlite',
storage: process.env.DB_PATH // Ensure your .env points to 'checkers.db'
});

module.exports = sequelize;
module.exports = sequelize;
40 changes: 34 additions & 6 deletions backend/models/user.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
// models/user.js
const { Model, DataTypes } = require('sequelize');
const sequelize = require('../config/connection'); // Ensure the connection path is correct
const sequelize = require('../config/connection'); // Adjust this path if necessary

class User extends Model {}

User.init({
// Assuming your user has these fields, adjust as necessary
// Make sure these field names match those in your database schema
username: {
type: DataTypes.STRING,
allowNull: false,
Expand All @@ -13,11 +14,38 @@ User.init({
password: {
type: DataTypes.STRING,
allowNull: false
},
// Add additional fields as per your project requirements
}
}, {
sequelize,
modelName: 'user'
modelName: 'user',
timestamps: false // Add this only if you do not want Sequelize to handle createdAt and updatedAt
});

module.exports = User;


// Old code if needed
/*
const { Model, DataTypes } = require('sequelize');
const sequelize = require('../config/connection');

class User extends Model {}

User.init({
username: {
type: DataTypes.STRING,
allowNull: false,
unique: true
},
password: {
type: DataTypes.STRING,
allowNull: false
}
}, {
sequelize,
modelName: 'user',
tableName: 'users' // Explicitly define table name to match your SQL schema
});

module.exports = User;
module.exports = User;
*/
103 changes: 50 additions & 53 deletions backend/routes/userRoutes.js
Original file line number Diff line number Diff line change
@@ -1,68 +1,65 @@
// routes/userRoutes.js
const express = require('express');
const router = express.Router();
const bcrypt = require('bcryptjs');
const User = require('../models/user'); // Make sure this path is correct
const User = require('../models/user');

const router = express.Router();

// Route for user registration
router.post('/register', async (req, res) => {
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;
79 changes: 56 additions & 23 deletions backend/server.js
Original file line number Diff line number Diff line change
@@ -1,49 +1,82 @@
// 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');
const http = require('http');
const socketIo = require('socket.io');
const path = require('path');
require('dotenv').config();
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 sqlite3 = require("sqlite3").verbose();

const app = express();
const PORT = process.env.PORT || 3000;
const server = http.createServer(app);
const io = socketIo(server, {
cors: {
origin: "*", // Adjust according to your frontend's actual deployment URL
methods: ["GET", "POST"],
credentials: true
}
});

// Middleware to parse JSON and urlencoded data
// CORS configuration to allow requests from the frontend URL
app.use(cors({
origin: "*", // Adjust according to your frontend's actual deployment URL
credentials: true
}));

// Middleware for parsing JSON and URL-encoded data
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// Enhanced session configuration
// Session configuration with enhanced security settings
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
// Initialize Passport middleware for user authentication
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!');
// 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.');
});

// 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');
});
});

// 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);

// 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}`);
});
}).catch((error) => {
console.error("Failed to sync database:", error);
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
46 changes: 29 additions & 17 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,42 +7,54 @@
"checkers"
],
"license": "MIT",
"engines": {
"node": "20.x",
"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": {
"name": "George Ambriz",
"email": "George@dodgeit.com"
},
"dependencies": {
"express": "^4.19.2",
"react": "^18.2.0",
"react-dom": "^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": {
"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"
},
"proxy": "http://localhost:3000",
"browserslist": {
"production": [
">0.2%",
Expand Down
Loading