Skip to content

Commit 6aea215

Browse files
committedApr 26, 2024
add new files
0 parents  commit 6aea215

File tree

956 files changed

+136315
-0
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

956 files changed

+136315
-0
lines changed
 

‎app.js

+244
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,244 @@
1+
var express = require('express');
2+
var bodyParser = require('body-parser');
3+
var mysql = require('mysql2');
4+
var path = require('path');
5+
var session = require('express-session');
6+
7+
var app = express();
8+
9+
// Set up the database connection details
10+
var connection = mysql.createConnection({
11+
host: '34.70.101.192',
12+
user: 'sxianyu2',
13+
password: '88888888',
14+
database: '411_Smaller'
15+
});
16+
17+
// Connect to the database
18+
connection.connect(function(err) {
19+
if (err) {
20+
console.error('error: ' + err.message);
21+
process.exit(1); // Terminate the application with an error code
22+
}
23+
console.log('Connected to the MySQL server.');
24+
});
25+
26+
app.set('view engine', 'ejs');
27+
app.set('views', path.join(__dirname, 'views'));
28+
29+
// Middleware
30+
app.use(bodyParser.urlencoded({ extended: true }));
31+
app.use(bodyParser.json());
32+
app.use(session({
33+
secret: 'secret',
34+
resave: false,
35+
saveUninitialized: false
36+
}));
37+
38+
app.use((req, res, next) => {
39+
res.locals.loggedin = req.session.loggedin || false;
40+
res.locals.username = req.session.username || '';
41+
res.locals.userId = req.session.userId || ''; // Ensure this line exists
42+
next();
43+
});
44+
45+
46+
// Routes
47+
app.get('/', (req, res) => {
48+
// Check if user is logged in
49+
if (req.session.loggedin) {
50+
res.render('index', { recipes: null, message: 'Welcome back, ' + req.session.username });
51+
} else {
52+
res.render('index', { recipes: null, message: '' });
53+
}
54+
});
55+
56+
app.get('/my-likes', function(req, res) {
57+
if (!req.session.loggedin || !req.session.userId) {
58+
res.redirect('/login'); // Redirect to login if not logged in
59+
return;
60+
}
61+
62+
const userId = req.session.userId;
63+
const sql = `
64+
SELECT Recipes.recipe_id, Recipes.recipe_name
65+
FROM Recipes
66+
JOIN UserLikeRecipe ON Recipes.recipe_id = UserLikeRecipe.recipe_id
67+
WHERE UserLikeRecipe.user_id = ?`;
68+
69+
connection.query(sql, [userId], function(err, results) {
70+
if (err) {
71+
console.error("Error fetching liked recipes:", err);
72+
res.render('index', { recipes: null, message: "Error fetching your liked recipes" });
73+
return;
74+
}
75+
// Pass an additional variable to indicate no buttons should be displayed
76+
res.render('index', { recipes: results, message: "", displayButtons: false });
77+
});
78+
});
79+
80+
81+
82+
app.post('/search-by-recipe', (req, res) => {
83+
const keywords = req.body.keyword.split(',').map(k => k.trim());
84+
let query = 'SELECT recipe_id, recipe_name FROM Recipes WHERE';
85+
const conditions = keywords.map((keyword, index) => {
86+
return ` recipe_name LIKE ?`;
87+
}).join(' OR ');
88+
89+
query += conditions;
90+
const params = keywords.map(keyword => `%${keyword}%`);
91+
92+
connection.query(query, params, (err, results) => {
93+
if (err) {
94+
console.error(err);
95+
res.status(500).send('Database error occurred.');
96+
return;
97+
}
98+
res.render('index', { recipes: results, message: '', displayButtons: true }); // Include message as an empty string
99+
});
100+
});
101+
102+
app.post('/search-by-ingredient', (req, res) => {
103+
const ingredients = req.body.ingredient.split(',').map(ingredient => ingredient.trim());
104+
let query = `
105+
SELECT DISTINCT Recipes.recipe_id, Recipes.recipe_name
106+
FROM Recipes
107+
JOIN RecipeIncludesIngredients ON Recipes.recipe_id = RecipeIncludesIngredients.recipe_id
108+
JOIN Ingredients ON RecipeIncludesIngredients.ingredient_id = Ingredients.ingredient_id
109+
WHERE`;
110+
const conditions = ingredients.map(ingredient => {
111+
return ` Ingredients.ingredient_name LIKE ?`;
112+
}).join(' OR ');
113+
114+
query += conditions;
115+
const params = ingredients.map(ingredient => `%${ingredient}%`);
116+
117+
connection.query(query, params, (err, results) => {
118+
if (err) {
119+
console.error(err);
120+
res.status(500).send('Database error occurred.');
121+
return;
122+
}
123+
res.render('index', { recipes: results, message: '', displayButtons: true });
124+
});
125+
});
126+
127+
app.post('/login', (req, res) => {
128+
const { useremail, password } = req.body;
129+
130+
connection.query('SELECT user_id, user_name FROM Users WHERE user_email = ? AND password = ?', [useremail, password], function(error, results) {
131+
if (error) {
132+
console.error('Database error:', error);
133+
res.render('index', { recipes: null, message: 'Database error during login.' });
134+
return;
135+
}
136+
137+
if (results.length > 0) {
138+
req.session.loggedin = true;
139+
req.session.userId = results[0].user_id; // Storing user_id in the session
140+
req.session.username = results[0].user_name; // Storing username in the session
141+
res.render('index', { recipes: null, message: 'Login successful!', loggedin: true });
142+
} else {
143+
res.render('index', { recipes: null, message: 'Incorrect Username and/or Password!', loggedin: false });
144+
}
145+
});
146+
});
147+
148+
149+
app.post('/register', (req, res) => {
150+
const { useremail, username, password } = req.body;
151+
152+
connection.query('SELECT user_name FROM Users WHERE user_email = ?', useremail, function(error, results) {
153+
if (error) {
154+
console.error('Database error:', error);
155+
res.render('index', { recipes: null, message: 'Database error during register.' });
156+
return;
157+
}
158+
159+
if (results.length > 0) {
160+
// User email already exists
161+
res.render('index', { recipes: null, message: 'Email already exists. Please login or use another email.' });
162+
} else {
163+
//Get maximum user id in the data base (INT)
164+
connection.query('SELECT MAX(user_id) as max_id FROM Users', function(error, result){
165+
if (error) {
166+
console.error('Database error:', error);
167+
res.render('index', { recipes: null, message: 'Database error during register.' });
168+
return;
169+
}
170+
const maxId = result[0].max_id; // || 0; // Handle the case where there are no users
171+
const newUserId = maxId + 1;
172+
173+
connection.query('INSERT INTO Users (user_id, user_email, user_name, password) VALUES (?, ?, ?, ?)',
174+
[newUserId, useremail, username, password], function(insertError, insertResult) {
175+
if (insertError) {
176+
console.error('Database error when inserting new user:', insertError);
177+
res.render('index', { recipes: null, message: 'Failed to create account. Please try again.' });
178+
return;
179+
}
180+
// Successfully created the user
181+
res.render('index', { recipes: null, message: 'Account created successfully! Please log in.' });
182+
})
183+
})
184+
}
185+
});
186+
});
187+
188+
app.post('/like-recipe', function(req, res) {
189+
if (req.session.loggedin && req.session.userId) {
190+
const userId = req.session.userId; // Use the userId from the session
191+
const recipeId = req.body.recipeId;
192+
193+
// First, check if the like already exists
194+
const checkSql = "SELECT * FROM UserLikeRecipe WHERE user_id = ? AND recipe_id = ?";
195+
connection.query(checkSql, [userId, recipeId], function(checkErr, checkResults) {
196+
if (checkErr) {
197+
console.error("Error checking existing likes:", checkErr);
198+
res.render('index', { recipes: null, message: "Error checking likes" });
199+
return;
200+
}
201+
202+
if (checkResults.length > 0) {
203+
// If the like already exists, don't insert and send a message back
204+
res.render('index', { recipes: null, message: "You have already liked this recipe" });
205+
} else {
206+
// Like does not exist, proceed with insertion
207+
const insertSql = "INSERT INTO UserLikeRecipe (user_id, recipe_id) VALUES (?, ?)";
208+
connection.query(insertSql, [userId, recipeId], function(insertErr, insertResult) {
209+
if (insertErr) {
210+
console.error("Error inserting into UserLikeRecipe:", insertErr);
211+
res.render('index', { recipes: null, message: "Error processing your like" });
212+
} else {
213+
console.log("Successfully inserted like into database");
214+
res.render('index', { recipes: null, message: "Recipe liked successfully!" });
215+
}
216+
});
217+
}
218+
});
219+
} else {
220+
res.render('index', { recipes: null, message: "Please log in to like recipes" });
221+
}
222+
});
223+
224+
225+
226+
227+
228+
229+
// Logout route
230+
app.get('/logout', (req, res) => {
231+
req.session.destroy(err => {
232+
if (err) {
233+
return console.log(err);
234+
}
235+
res.redirect('/');
236+
});
237+
});
238+
239+
// Server setup
240+
var port = process.env.PORT || 80;
241+
app.listen(port, () => {
242+
console.log(`Server running on port ${port}`);
243+
});
244+

‎bin/www

+90
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
#!/usr/bin/env node
2+
3+
/**
4+
* Module dependencies.
5+
*/
6+
7+
var app = require('../app');
8+
var debug = require('debug')('myproj:server');
9+
var http = require('http');
10+
11+
/**
12+
* Get port from environment and store in Express.
13+
*/
14+
15+
var port = normalizePort(process.env.PORT || '3000');
16+
app.set('port', port);
17+
18+
/**
19+
* Create HTTP server.
20+
*/
21+
22+
var server = http.createServer(app);
23+
24+
/**
25+
* Listen on provided port, on all network interfaces.
26+
*/
27+
28+
server.listen(port);
29+
server.on('error', onError);
30+
server.on('listening', onListening);
31+
32+
/**
33+
* Normalize a port into a number, string, or false.
34+
*/
35+
36+
function normalizePort(val) {
37+
var port = parseInt(val, 10);
38+
39+
if (isNaN(port)) {
40+
// named pipe
41+
return val;
42+
}
43+
44+
if (port >= 0) {
45+
// port number
46+
return port;
47+
}
48+
49+
return false;
50+
}
51+
52+
/**
53+
* Event listener for HTTP server "error" event.
54+
*/
55+
56+
function onError(error) {
57+
if (error.syscall !== 'listen') {
58+
throw error;
59+
}
60+
61+
var bind = typeof port === 'string'
62+
? 'Pipe ' + port
63+
: 'Port ' + port;
64+
65+
// handle specific listen errors with friendly messages
66+
switch (error.code) {
67+
case 'EACCES':
68+
console.error(bind + ' requires elevated privileges');
69+
process.exit(1);
70+
break;
71+
case 'EADDRINUSE':
72+
console.error(bind + ' is already in use');
73+
process.exit(1);
74+
break;
75+
default:
76+
throw error;
77+
}
78+
}
79+
80+
/**
81+
* Event listener for HTTP server "listening" event.
82+
*/
83+
84+
function onListening() {
85+
var addr = server.address();
86+
var bind = typeof addr === 'string'
87+
? 'pipe ' + addr
88+
: 'port ' + addr.port;
89+
debug('Listening on ' + bind);
90+
}

0 commit comments

Comments
 (0)
Please sign in to comment.