Skip to content

Commit c1f5b1f

Browse files
committed
Add structure
1 parent 5e14f5a commit c1f5b1f

24 files changed

+6051
-0
lines changed

.gitignore

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
# Dependency directory
2+
node_modules/
3+
4+
# Debug log from npm
5+
npm-debug.log
6+
7+
# Environment Variables should NEVER be published
8+
.env

app.js

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
// ℹ️ Gets access to environment variables/settings
2+
// https://www.npmjs.com/package/dotenv
3+
require("dotenv").config();
4+
5+
// ℹ️ Connects to the database
6+
require("./db");
7+
8+
// Handles http requests (express is node js framework)
9+
// https://www.npmjs.com/package/express
10+
const express = require("express");
11+
12+
// Handles the handlebars
13+
// https://www.npmjs.com/package/hbs
14+
const hbs = require("hbs");
15+
16+
const app = express();
17+
18+
// ℹ️ This function is getting exported from the config folder. It runs most pieces of middleware
19+
require("./config")(app);
20+
21+
const capitalize = require("./utils/capitalize");
22+
const projectName = "app";
23+
24+
app.locals.appTitle = `${capitalize(projectName)} created with IronLauncher`;
25+
26+
// 👇 Start handling routes here
27+
const indexRoutes = require("./routes/index.routes");
28+
app.use("/", indexRoutes);
29+
30+
const authRoutes = require("./routes/auth.routes");
31+
app.use("/auth", authRoutes);
32+
33+
// ❗ To handle errors. Routes that don't exist or errors that you handle in specific routes
34+
require("./error-handling")(app);
35+
36+
module.exports = app;

config/index.js

+65
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
// We reuse this import in order to have access to the `body` property in requests
2+
const express = require("express");
3+
4+
// ℹ️ Responsible for the messages you see in the terminal as requests are coming in
5+
// https://www.npmjs.com/package/morgan
6+
const logger = require("morgan");
7+
8+
// ℹ️ Needed when we deal with cookies (we will when dealing with authentication)
9+
// https://www.npmjs.com/package/cookie-parser
10+
const cookieParser = require("cookie-parser");
11+
12+
// ℹ️ Serves a custom favicon on each request
13+
// https://www.npmjs.com/package/serve-favicon
14+
const favicon = require("serve-favicon");
15+
16+
// ℹ️ global package used to `normalize` paths amongst different operating systems
17+
// https://www.npmjs.com/package/path
18+
const path = require("path");
19+
20+
// ℹ️ Session middleware for authentication
21+
// https://www.npmjs.com/package/express-session
22+
const session = require("express-session");
23+
24+
// ℹ️ MongoStore in order to save the user session in the database
25+
// https://www.npmjs.com/package/connect-mongo
26+
const MongoStore = require("connect-mongo");
27+
28+
// Connects the mongo uri to maintain the same naming structure
29+
const MONGO_URI =
30+
process.env.MONGODB_URI || "mongodb://127.0.0.1:27017/app";
31+
32+
// Middleware configuration
33+
module.exports = (app) => {
34+
// In development environment the app logs
35+
app.use(logger("dev"));
36+
37+
// To have access to `body` property in the request
38+
app.use(express.json());
39+
app.use(express.urlencoded({ extended: false }));
40+
app.use(cookieParser());
41+
42+
// Normalizes the path to the views folder
43+
app.set("views", path.join(__dirname, "..", "views"));
44+
// Sets the view engine to handlebars
45+
app.set("view engine", "hbs");
46+
// AHandles access to the public folder
47+
app.use(express.static(path.join(__dirname, "..", "public")));
48+
49+
// Handles access to the favicon
50+
app.use(
51+
favicon(path.join(__dirname, "..", "public", "images", "favicon.ico"))
52+
);
53+
54+
// ℹ️ Middleware that adds a "req.session" information and later to check that you are who you say you are 😅
55+
app.use(
56+
session({
57+
secret: process.env.SESSION_SECRET || "super hyper secret key",
58+
resave: false,
59+
saveUninitialized: false,
60+
store: MongoStore.create({
61+
mongoUrl: MONGO_URI,
62+
}),
63+
})
64+
);
65+
};

db/index.js

+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
// ℹ️ package responsible to make the connection with mongodb
2+
// https://www.npmjs.com/package/mongoose
3+
const mongoose = require("mongoose");
4+
5+
// ℹ️ Sets the MongoDB URI for our app to have access to it.
6+
// If no env has been set, we dynamically set it to whatever the folder name was upon the creation of the app
7+
8+
const MONGO_URI =
9+
process.env.MONGODB_URI || "mongodb://127.0.0.1:27017/app";
10+
11+
mongoose
12+
.connect(MONGO_URI)
13+
.then((x) => {
14+
const databaseName = x.connections[0].name;
15+
console.log(`Connected to Mongo! Database name: "${databaseName}"`);
16+
})
17+
.catch((err) => {
18+
console.error("Error connecting to mongo: ", err);
19+
});

error-handling/index.js

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
module.exports = (app) => {
2+
app.use((req, res, next) => {
3+
// this middleware runs whenever requested page is not available
4+
res.status(404).render("not-found");
5+
});
6+
7+
app.use((err, req, res, next) => {
8+
// whenever you call next(err), this middleware will handle the error
9+
// always logs the error
10+
console.error("ERROR: ", req.method, req.path, err);
11+
12+
// only render if the error ocurred before sending the response
13+
if (!res.headersSent) {
14+
res.status(500).render("error");
15+
}
16+
});
17+
};

middleware/isLoggedIn.js

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
module.exports = (req, res, next) => {
2+
// checks if the user is logged in when trying to access a specific page
3+
if (!req.session.currentUser) {
4+
return res.redirect("/auth/login");
5+
}
6+
7+
next();
8+
};

middleware/isLoggedOut.js

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
module.exports = (req, res, next) => {
2+
// if an already logged in user tries to access the login page it
3+
// redirects the user to the home page
4+
if (req.session.currentUser) {
5+
return res.redirect("/");
6+
}
7+
next();
8+
};

models/User.model.js

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
const { Schema, model } = require("mongoose");
2+
3+
// TODO: Please make sure you edit the User model to whatever makes sense in this case
4+
const userSchema = new Schema(
5+
{
6+
username: {
7+
type: String,
8+
required: false,
9+
unique: true,
10+
trim: true,
11+
},
12+
email: {
13+
type: String,
14+
required: true,
15+
unique: true,
16+
trim: true,
17+
lowercase: true,
18+
},
19+
password: {
20+
type: String,
21+
required: true,
22+
},
23+
},
24+
{
25+
// this second object adds extra properties: `createdAt` and `updatedAt`
26+
timestamps: true,
27+
}
28+
);
29+
30+
const User = model("User", userSchema);
31+
32+
module.exports = User;

0 commit comments

Comments
 (0)