-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
86 lines (60 loc) · 1.85 KB
/
server.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
74
75
76
77
78
79
80
81
82
83
84
85
86
// server.js
// Rest of your code...
const express = require('express');
const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const cors = require('cors');
const bodyParser = require("body-parser");
// Rest of your code...
const app = express();
const port = 3000;
app.use(express.static("public"));
app.set('view engine', 'html');
app.engine('html', require('ejs').renderFile);
app.use(bodyParser.urlencoded({
extended: true
}));
// Middleware
app.use(cors());
app.use(express.json());
// Connect to MongoDB
mongoose.connect('mongodb://localhost/login-app', { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => {
console.log('Connected to MongoDB');
})
.catch((err) => {
console.error('Error connecting to MongoDB:', err);
});
// User model
const User = mongoose.model('User', new mongoose.Schema({
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
}));
app.get("/", function(req, res){
res.render("index.html");
})
// Login endpoint
app.post('/login', async (req, res) => {
const { email, password } = req.body;
try {
// Find the user by email
const user = await User.findOne({ email });
if (!user) {
return res.status(401).json({ message: 'Invalid credentials' });
}
// Compare the provided password with the stored password hash
const passwordMatch = await bcrypt.compare(password, user.password);
if (!passwordMatch) {
return res.status(401).json({ message: 'Invalid credentials' });
}
// Authentication successful
return res.status(200).json({ message: 'Login successful' });
} catch (error) {
console.error('Error during login:', error);
res.status(500).json({ message: 'Server error' });
}
});
// Start the server
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});