-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
205 lines (174 loc) · 5.66 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
// App.js
// This is the area that includes
// - App Setup
// - Express Framework
// - Middleware
// - Error Handling
// - Server Listening
// - Other Application Setup Code
// *APP SETUP*
//Importation of Modules
const express = require("express");
const { engine } = require("express-handlebars");
const path = require("path");
const sequelize = require('./database');
const { Sequelize, DataTypes} = require('sequelize');
const session = require('express-session');
//Generates Instance of Express Application
const app = express();
const PORT = process.env.PORT || 3005; //Creates the number the server will listen on
//Registers Handlebars engine with the Application
//Allows for .handlebars files
app.engine(
"handlebars",
engine({
partialsDir: path.join(__dirname, "views/partials"), //Where partial files are found (reusable files)
})
);
app.set("view engine", "handlebars"); //Sets Handlebars as the default veiw engine
app.set("views", path.join(__dirname, "views")); //Tells app where to find view directory
// *MIDDLEWARE*
//Serves static files (makes accesable to client)
app.use(express.static(path.join(__dirname, "public")));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// Define Property model
const Property = sequelize.define('Property', {
address: { type: DataTypes.STRING, allowNull: false },
suburb: { type: DataTypes.STRING, allowNull: false },
town_city: { type: DataTypes.STRING, allowNull: false },
description: { type: DataTypes.TEXT, allowNull: false },
list_price: { type: DataTypes.DECIMAL(10, 2), allowNull: false },
image_name: { type: DataTypes.STRING, allowNull: false },
bedrooms: { type: DataTypes.INTEGER, allowNull: false },
ensuite: { type: DataTypes.BOOLEAN, allowNull: false },
sold: { type: DataTypes.BOOLEAN, allowNull: false },
featured: { type: DataTypes.BOOLEAN, allowNull: false },
pool: { type: DataTypes.BOOLEAN, allowNull: false },
active: { type: DataTypes.BOOLEAN, allowNull: false },
created_at: { type: DataTypes.DATE, defaultValue: Sequelize.NOW },
updated_at: { type: DataTypes.DATE, defaultValue: Sequelize.NOW }
},
{
tableName: 'properties',
timestamps: false
});
const isAuthenticated = (req, res, next) => {
if (req.session.user) {
next();
} else {
res.redirect('/login');
}
};
// Home Page
app.get("/", async (req, res) => {
try {
const properties = await Property.findAll({
where: { active: true },
order: sequelize.random(),
limit: 21
});
const plainProperties = properties.map(prop => {
const property = prop.get({ plain: true });
property.image_url = `/images/houses/${property.image_name}`;
return property;
});
const suburbs = await Property.findAll({
attributes: [[Sequelize.fn('DISTINCT', Sequelize.col('suburb')), 'suburb']],
where: { active: true },
limit: 18
});
const plainSuburbs = suburbs.map(suburb => suburb.get({ plain: true }));
res.render("home", {
layout: "main",
title: "Home",
properties: plainProperties,
suburbs: plainSuburbs
});
} catch (error) {
console.error('Error fetching properties:', error);
res.status(500).send('Error');
}
});
// Route Subrub
app.get("/filter/:suburb", async (req, res) => {
try {
const suburbName = req.params.suburb;
let properties;
if (suburbName === "All") {
properties = await Property.findAll({
limit: 21
});
} else {
properties = await Property.findAll({
where: { suburb: suburbName },
limit: 21
});
}
const plainProperties = properties.map(prop => {
const property = prop.get({ plain: true });
property.image_url = `/images/houses/${property.image_name}`;
return property;
});
const suburbs = await Property.findAll({
attributes: [[Sequelize.fn('DISTINCT', Sequelize.col('suburb')), 'suburb']],
order: [['suburb', 'ASC']],
limit: 21
});
const plainSuburbs = [{ suburb: 'All' }, ...suburbs.map(suburb => suburb.get({ plain: true }))];
res.render("home", {
layout: "main",
title: "Home",
properties: plainProperties,
suburbs: plainSuburbs
});
} catch (error) {
console.error('Error filtering properties: ', error);
res.status(500).send('An error occurred while filtering properties');
}
});
// Route Login
app.get('/login', (req, res) => {
res.render('login',
{
layout: "main",
title: "Login"
});
});
app.use(session({
secret: 'mySecretKey',
resave: false,
saveUninitialized: true
}));
// Route Login
app.post('/login', (req, res) => {
const { username, password } = req.body;
if (username === 'admin' && password === 'password') {
req.session.user = username;
res.redirect('/dashboard');
} else {
res.render('login', {
layout: "main",
title: "Login",
error: "Invalid Login."
});
}
});
// Route Dashboard
app.get('/dashboard', isAuthenticated, (req, res) => {
res.render('dashboard', {
user: req.session.user,
layout: "main",
title: "Dashboard"
});
});
// Start the server
app.listen(PORT, async () => {
try {
await sequelize.authenticate();
console.log("Database connected successfully");
} catch (error) {
console.error("Unable to connect to the database:", error);
}
console.log(`Server is running on http://localhost:${PORT}`);
});