Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sign in connection #10 Tony/Spencer #20

Merged
merged 9 commits into from
Oct 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
74 changes: 62 additions & 12 deletions backend/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,35 @@ const mongo = require("mongodb");
const mongoose = require("mongoose");
require('dotenv').config();


const app = express()
app.use(cors())
app.use(express.json())

const PORT = process.env.PORT || 4000;

mongoose.connect(process.env.MONGODB_URI)
.then(() => {
app.listen(PORT, () => {
console.log(`Server listening on port ${PORT}`)
});
})
.catch((e) => {
console.log(e)
})
.then(() => {
console.log('Successfully connected to MongoDB database:', mongoose.connection.name);
const server = app.listen(PORT, () => {
console.log(`Server listening on port ${PORT}`);
}).on('error', (err) => {
if (err.code === 'EADDRINUSE') {
console.log(`Port ${PORT} is busy, trying ${PORT + 1}`);
server.listen(PORT + 1);
} else {
console.error('Server error:', err);
}
});
})
.catch((error) => {
console.error('MongoDB connection error:', error.message);
process.exit(1); // Exit if we can't connect to the database
});

mongoose.connection.on('error', (err) => {
console.error('MongoDB connection error:', err);
});

app.get('/', (req, res) => {
res.send('Server is running!')
Expand Down Expand Up @@ -52,9 +66,45 @@ const User = mongoose.model("users", UserSchema)
//------------------ ENDPOINTS ------------------//

// Sign up

// TODO (Spencer & Tony): Create an endpoint to receive and upload sign up data to the database

app.post('/api/users', async (req, res) => {
try {
const { firstName, lastName, username, email, password } = req.body;

// Check if user already exists
const existingUser = await User.findOne({
$or: [
{ email: email },
{ username: username }
]
});

if (existingUser) {
if (existingUser.email === email) {
return res.status(409).json({ message: 'Email already exists' });
}
if (existingUser.username === username) {
return res.status(409).json({ message: 'Username already exists' });
}
}

// Create new user with separate first/last name fields
const newUser = new User({
firstName,
lastName,
email,
password,
isAdmin: false,
username
});

await newUser.save();
res.status(201).json({ message: 'User created successfully' });

} catch (error) {
console.error('Error creating user:', error);
res.status(500).json({ message: 'Error creating user' });
}
});

// Login

Expand All @@ -68,4 +118,4 @@ const User = mongoose.model("users", UserSchema)

// Classes

// TODO (Claire & Fahim): Create an endpoint to retrieve class data from the database
// TODO (Claire & Fahim): Create an endpoint to retrieve class data from the database
91 changes: 91 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
"preview": "vite preview"
},
"dependencies": {
"axios": "^1.7.7",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"wouter": "^3.3.5"
Expand Down
51 changes: 44 additions & 7 deletions src/pages/SignUp.jsx
Original file line number Diff line number Diff line change
@@ -1,25 +1,46 @@
import { useState } from "react";
import { Link } from 'wouter'
import axios from "axios";


export default function SignUp() {
const [formData, setFormData] = useState({
username: '',
firstName: '',
lastName: '',
email: '',
username: '',
password: '',
retypedPassword: ''
})

const [error, setError] = useState('');
const [success, setSuccess] = useState('');
const handleChange = (e) => {
setFormData({ ...formData, [e.target.name]: e.target.value });
};

const handleSubmit = (e) => {
const handleSubmit = async (e) => {
e.preventDefault();
const { username, email, password, retypedPassword } = formData
const { username, email, password, retypedPassword} = formData
if (password != retypedPassword) {
alert(`Passwords do not match:\npassword: ${password}\nretyped password: ${retypedPassword}`)
} else {
alert(`Form submitted with\nusername: ${username}\nemail: ${email}\npassword: ${password}\nretyped password: ${retypedPassword}`)
try {
// Using environment variable for API URL
const response = await axios.post(`${import.meta.env.VITE_API_URL}/api/users`, formData);
if (response.status === 201) {
setSuccess('User created successfully!');
alert('User created successfully!');
setError('');
}
} catch (err) {
if (err.response && err.response.status === 409) {
setError('User already exists.');
alert('User already exists.');
} else {
setError('An error occurred while creating the user.');
alert('An error occurred while creating the user.')
}
}
}
}

Expand All @@ -37,8 +58,24 @@ export default function SignUp() {
<form method="POST" onSubmit={handleSubmit}>
<input
required
type="name"
name="name"
type="text"
name="firstName"
placeholder="First Name"
className="mt-2 w-10/12 ml-10 p-3 text-lg border-2 border-black border-opacity-20 h-10 rounded-lg"
onChange={handleChange}
/>
<input
required
type="text"
name="lastName"
placeholder="Last Name"
className="mt-2 w-10/12 ml-10 p-3 text-lg border-2 border-black border-opacity-20 h-10 rounded-lg"
onChange={handleChange}
/>
<input
required
type="text"
name="username"
placeholder="Username"
className="mt-2 w-10/12 ml-10 p-3 text-lg border-2 border-black border-opacity-20 h-10 rounded-lg"
onChange={handleChange}
Expand Down