Skip to content
Open
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
33 changes: 33 additions & 0 deletions Starteryou/backend/models/User.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
// backend/models/User.js
const mongoose = require("mongoose");
const bcrypt = require("bcryptjs");

const userSchema = new mongoose.Schema({
username: {
type: String,
required: true,
unique: true,
},
password: {
type: String,
required: true,
},
isAdmin: {
type: Boolean,
default: false,
},
});

// Hash password before saving
userSchema.pre("save", async function (next) {
if (!this.isModified("password")) return next();
this.password = await bcrypt.hash(this.password, 10);
next();
});

// Method to compare passwords
userSchema.methods.comparePassword = async function (candidatePassword) {
return await bcrypt.compare(candidatePassword, this.password);
};

module.exports = mongoose.model("User", userSchema);
6,182 changes: 3,144 additions & 3,038 deletions Starteryou/backend/package-lock.json

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions Starteryou/backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,12 @@
"start": "node server.js"
},
"dependencies": {
"bcryptjs": "^2.4.3",
"cors": "^2.8.5",
"dotenv": "^10.0.0",
"express": "^4.21.1",
"gridfs-stream": "^1.1.1",
"jsonwebtoken": "^9.0.2",
"mongodb": "^5.9.1",
"mongoose": "^6.0.0",
"multer": "^1.4.2",
Expand Down
45 changes: 45 additions & 0 deletions Starteryou/backend/routes/authRoutes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
// backend/routes/authRoutes.js
const express = require("express");
const router = express.Router();
const User = require("../models/User");
const jwt = require("jsonwebtoken");

// Login route
router.post("/login", async (req, res) => {
try {
const {username, password} = req.body;

// Find user
const user = await User.findOne({username});
if (!user) {
return res.status(401).json({message: "Invalid credentials"});
}

// Check password
const isMatch = await user.comparePassword(password);
if (!isMatch) {
return res.status(401).json({message: "Invalid credentials"});
}

// Create JWT token
const token = jwt.sign(
{userId: user._id, isAdmin: user.isAdmin},
process.env.JWT_SECRET,
{expiresIn: "24h"}
);

res.json({
token,
user: {
id: user._id,
username: user.username,
isAdmin: user.isAdmin,
},
});
} catch (error) {
console.error("Login error:", error);
res.status(500).json({message: "Server error"});
}
});

module.exports = router;
39 changes: 39 additions & 0 deletions Starteryou/backend/scripts/createAdmin.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
const mongoose = require("mongoose");
const bcrypt = require("bcryptjs");
const User = require("../models/User");
require("dotenv").config(); // Add this at the very top

mongoose.set("strictQuery", false);
const mongoURI =
"mongodb://starteryouadmin:StarteryouAdmin2024@localhost:27017/starteryou?authSource=admin"; // Add database name 'starteryou'

const createAdminUser = async () => {
try {
await mongoose.connect(mongoURI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});

const existingAdmin = await User.findOne({username: "admin"});
if (existingAdmin) {
console.log("Admin user already exists");
return;
}

const hashedPassword = await bcrypt.hash("admin123", 10);
const adminUser = new User({
username: "admin",
password: hashedPassword,
isAdmin: true,
});

await adminUser.save();
console.log("Admin user created successfully");
} catch (error) {
console.error("Error creating admin user:", error);
} finally {
await mongoose.connection.close();
}
};

createAdminUser();
54 changes: 30 additions & 24 deletions Starteryou/backend/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,48 +6,53 @@ const connectDB = require("./config/db");
const fileRoutes = require("./routes/fileRoutes");
const cors = require("cors");
const mongoose = require("mongoose");
const authRoutes = require("./routes/authRoutes");

const app = express();

// Set mongoose options
mongoose.set("strictQuery", false);

// Auth routes
app.use("/api/auth", authRoutes);

// MongoDB Connection with status messages
mongoose.connect(process.env.MONGODB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => {
console.log('✅ MongoDB Connected Successfully!');
console.log(`📊 Database: ${mongoose.connection.name}`);
console.log(`🔌 Host: ${mongoose.connection.host}`);
})
.catch((error) => {
console.error('❌ MongoDB Connection Error:', error);
process.exit(1); // Exit process with failure
});
mongoose
.connect(process.env.MONGODB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => {
console.log("✅ MongoDB Connected Successfully!");
console.log(`📊 Database: ${mongoose.connection.name}`);
console.log(`🔌 Host: ${mongoose.connection.host}`);
})
.catch((error) => {
console.error("❌ MongoDB Connection Error:", error);
process.exit(1); // Exit process with failure
});

// Monitor MongoDB connection
mongoose.connection.on('disconnected', () => {
console.log('❌ MongoDB Disconnected');
mongoose.connection.on("disconnected", () => {
console.log("❌ MongoDB Disconnected");
});

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

// CORS configuration for production
// In server.js
// CORS configuration with credentials
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', req.headers.origin);
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
res.header('Access-Control-Allow-Credentials', true);
res.header("Access-Control-Allow-Origin", req.headers.origin);
res.header("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,OPTIONS");
res.header("Access-Control-Allow-Headers", "Content-Type, Authorization");
res.header("Access-Control-Allow-Credentials", true);
next();
});

app.options('*', (req, res) => {
app.options("*", (req, res) => {
res.sendStatus(200);
});

Expand Down Expand Up @@ -76,7 +81,8 @@ app.get("/health", (req, res) => {
status: "OK",
message: "Server is running",
environment: process.env.NODE_ENV,
mongodb: mongoose.connection.readyState === 1 ? 'Connected' : 'Disconnected'
mongodb:
mongoose.connection.readyState === 1 ? "Connected" : "Disconnected",
});
});

Expand All @@ -101,4 +107,4 @@ process.on("SIGTERM", () => {
process.exit(0);
});
});
});
});
154 changes: 154 additions & 0 deletions Starteryou/backend/utils/mongoTester.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
// backend/utils/mongoTester.js
const mongoose = require("mongoose");

class MongoTester {
constructor(uri) {
this.uri = uri || process.env.MONGODB_URI;
this.isConnected = false;
}

async testConnection() {
console.log("\n🔍 Testing MongoDB Connection...");
console.log("URI:", this.uri);

try {
const conn = await mongoose.connect(this.uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
serverSelectionTimeoutMS: 5000,
connectTimeoutMS: 10000,
});

this.isConnected = true;

// Connection info
console.log("\n✅ Connection Successful!");
console.log("MongoDB Version:", conn.connection.version);
console.log("Database:", conn.connection.name);
console.log("Host:", conn.connection.host);
console.log("Port:", conn.connection.port);

// Test basic operations
await this.testDatabaseOperations();

return {
success: true,
details: {
version: conn.connection.version,
database: conn.connection.name,
host: conn.connection.host,
port: conn.connection.port,
},
};
} catch (error) {
console.error("\n❌ Connection Failed!");
console.error("Error:", error.message);

this.printTroubleshootingGuide(error);

return {
success: false,
error: error.message,
};
} finally {
if (this.isConnected) {
await mongoose.connection.close();
console.log("\nConnection closed");
}
}
}

async testDatabaseOperations() {
try {
// Create temporary collection
const TestModel = mongoose.model(
"TestConnection",
new mongoose.Schema({
test: String,
timestamp: Date,
})
);

// Test write
await TestModel.create({test: "connection_test", timestamp: new Date()});
console.log("✅ Write operation successful");

// Test read
await TestModel.findOne({test: "connection_test"});
console.log("✅ Read operation successful");

// Cleanup
await mongoose.connection.dropCollection("testconnections");
console.log("✅ Cleanup successful");
} catch (error) {
console.error("❌ Database operation failed:", error.message);
throw error;
}
}

async testNetworkConnectivity() {
try {
const url = new URL(this.uri);
const host = url.hostname;
const port = url.port || "27017";

return new Promise((resolve) => {
const net = require("net");
const socket = new net.Socket();

socket.setTimeout(5000);

socket.on("connect", () => {
socket.destroy();
resolve({
success: true,
message: `Port ${port} is reachable on ${host}`,
});
});

socket.on("timeout", () => {
socket.destroy();
resolve({
success: false,
message: `Connection to ${host}:${port} timed out`,
});
});

socket.on("error", (error) => {
resolve({
success: false,
message: error.message,
});
});

socket.connect(port, host);
});
} catch (error) {
return {
success: false,
message: `Invalid URI format: ${error.message}`,
};
}
}

printTroubleshootingGuide(error) {
console.log("\n🔧 Troubleshooting Guide:");

if (error.name === "MongoServerSelectionError") {
console.log("1. Check if MongoDB server is running");
console.log("2. Verify the connection string is correct");
console.log("3. Ensure network connectivity to the database");
console.log("4. Check if any firewalls are blocking the connection");
} else if (error.name === "MongoParseError") {
console.log("1. Check the connection string format");
console.log("2. Verify credentials are properly encoded");
console.log("3. Ensure all required connection parameters are present");
} else if (error.name === "MongooseError") {
console.log("1. Check if the database name is correct");
console.log("2. Verify authentication credentials");
console.log("3. Ensure proper access permissions");
}
}
}

module.exports = MongoTester;
13 changes: 13 additions & 0 deletions Starteryou/backend/utils/testMongo.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
// testMongo.js
const MongoTester = require("./mongoTester");

async function runTest() {
// Replace with your MongoDB URI
const uri =
"mongodb://starteryouadmin:StarteryouAdmin2024@localhost:27017/?authSource=admin";

const tester = new MongoTester(uri);
await tester.testConnection();
}

runTest().catch(console.error);
Loading