diff --git a/backend/server.js b/backend/server.js index 80539c5..60563c2 100644 --- a/backend/server.js +++ b/backend/server.js @@ -4,6 +4,7 @@ const mongo = require("mongodb"); const mongoose = require("mongoose"); require('dotenv').config(); + const app = express() app.use(cors()) app.use(express.json()) @@ -11,14 +12,27 @@ 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!') @@ -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 @@ -68,4 +118,4 @@ const User = mongoose.model("users", UserSchema) // Classes -// TODO (Claire & Fahim): Create an endpoint to retrieve class data from the database \ No newline at end of file +// TODO (Claire & Fahim): Create an endpoint to retrieve class data from the database diff --git a/package-lock.json b/package-lock.json index 537ca8e..1fa3f01 100644 --- a/package-lock.json +++ b/package-lock.json @@ -8,6 +8,7 @@ "name": "dillar-academy", "version": "0.0.0", "dependencies": { + "axios": "^1.7.7", "react": "^18.3.1", "react-dom": "^18.3.1", "wouter": "^3.3.5" @@ -1523,6 +1524,11 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==" + }, "node_modules/autoprefixer": { "version": "10.4.20", "resolved": "https://registry.npmjs.org/autoprefixer/-/autoprefixer-10.4.20.tgz", @@ -1575,6 +1581,16 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/axios": { + "version": "1.7.7", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.7.7.tgz", + "integrity": "sha512-S4kL7XrjgBmvdGut0sN3yJxqYzrDOnivkBiN0OFs6hLiUam3UPvswUo0kqGyhqUZGEOytHyumEdXsAkgCOUf3Q==", + "dependencies": { + "follow-redirects": "^1.15.6", + "form-data": "^4.0.0", + "proxy-from-env": "^1.1.0" + } + }, "node_modules/balanced-match": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", @@ -1769,6 +1785,17 @@ "integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==", "dev": true }, + "node_modules/combined-stream": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, "node_modules/commander": { "version": "4.1.1", "resolved": "https://registry.npmjs.org/commander/-/commander-4.1.1.tgz", @@ -1930,6 +1957,14 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", + "engines": { + "node": ">=0.4.0" + } + }, "node_modules/didyoumean": { "version": "1.2.2", "resolved": "https://registry.npmjs.org/didyoumean/-/didyoumean-1.2.2.tgz", @@ -2584,6 +2619,25 @@ "integrity": "sha512-X8cqMLLie7KsNUDSdzeN8FYK9rEt4Dt67OsG/DNGnYTSDBG4uFAJFBnUeiV+zCVAvwFy56IjM9sH51jVaEhNxw==", "dev": true }, + "node_modules/follow-redirects": { + "version": "1.15.9", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.9.tgz", + "integrity": "sha512-gew4GsXizNgdoRyqmyfMHyAmXsZDk6mHkSxZFCzW9gwlbtOW44CDtYavM+y+72qD/Vq2l550kMF52DT8fOLJqQ==", + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/RubenVerborgh" + } + ], + "engines": { + "node": ">=4.0" + }, + "peerDependenciesMeta": { + "debug": { + "optional": true + } + } + }, "node_modules/for-each": { "version": "0.3.3", "resolved": "https://registry.npmjs.org/for-each/-/for-each-0.3.3.tgz", @@ -2609,6 +2663,19 @@ "url": "https://github.com/sponsors/isaacs" } }, + "node_modules/form-data": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.1.tgz", + "integrity": "sha512-tzN8e4TX8+kkxGPK8D5u0FNmjPUjw3lwC9lSLxxoB/+GtsJG91CO8bSWy73APlgAZzZbXEYZJuxjkHH2w+Ezhw==", + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "mime-types": "^2.1.12" + }, + "engines": { + "node": ">= 6" + } + }, "node_modules/fraction.js": { "version": "4.3.7", "resolved": "https://registry.npmjs.org/fraction.js/-/fraction.js-4.3.7.tgz", @@ -3535,6 +3602,25 @@ "node": ">=8.6" } }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, "node_modules/minimatch": { "version": "3.1.2", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", @@ -4080,6 +4166,11 @@ "react-is": "^16.13.1" } }, + "node_modules/proxy-from-env": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz", + "integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==" + }, "node_modules/punycode": { "version": "2.3.1", "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", diff --git a/package.json b/package.json index d8170bf..680f73b 100644 --- a/package.json +++ b/package.json @@ -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" diff --git a/src/pages/SignUp.jsx b/src/pages/SignUp.jsx index 00f1100..349b2d6 100644 --- a/src/pages/SignUp.jsx +++ b/src/pages/SignUp.jsx @@ -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.') + } + } } } @@ -37,8 +58,24 @@ export default function SignUp() {