-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.js
76 lines (73 loc) · 2.31 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const path = require('path'); // Add path module
// Create Express ap
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.set('view engine', 'ejs');
// Serve static files from the 'public' directory
app.use(express.static(path.join(__dirname, 'public')));
// Connect to MongoDB Atlas
mongoose.connect('mongodb+srv://arnav9368543702:[email protected]/?retryWrites=true&w=majority&appName=Cluster0', {
useNewUrlParser: true,
useUnifiedTopology: true
}).then(() => {
console.log('Connected to MongoDB Atlas');
}).catch((err) => {
console.error('Error connecting to MongoDB Atlas:', err.message);
});
// Define Mongoose schema and model
const userSchema = new mongoose.Schema({
email: String,
password: String
});
const User = mongoose.model('User', userSchema);
// Routes
app.get('/', (req, res) => {
res.render('index');
});
app.post('/users', async (req, res) => {
const { email, password } = req.body;
try {
// Check if user exists
const existingUser = await User.findOne({ email });
if (existingUser) {
console.log("User already exists");
res.redirect('/login.html'); // Redirect to login page if user exists
} else {
// If user does not exist, save new user
const newUser = new User(req.body);
await newUser.save();
console.log("User added");
res.redirect('/index.html');
}
} catch (err) {
console.error('Error saving user:', err.message);
res.redirect('/');
}
}
);
app.post('/login', async (req, res) => {
const { email, password } = req.body;
try {
// Check if user exists
const existingUser = await User.findOne({ email, password });
if (existingUser) {
console.log("User logged in");
res.redirect('/index.html'); // Redirect to index page upon successful login
} else {
// If user does not exist, redirect to signup page with an alert
console.log("User not found");
res.redirect('/signup.html');
}
} catch (err) {
console.error('Error logging in:', err.message);
res.redirect('/');
}
});
// Start the server
const PORT = process.env.PORT || 4044;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});