text: if (process.env.NODE_ENV !== "production") {
    require("dotenv").config();
  }
  const express = require("express");
  const path = require("path");
  const mongoose = require("mongoose");
  const engine = require("ejs-mate");
  const session = require("express-session");
  const flash = require("connect-flash");
  const methodOverride = require("method-override");
  const passport = require("passport");
  const LocalStrategy = require("passport-local");
  const mongoSanitize = require("express-mongo-sanitize");
  const helmet = require("helmet");
  
  const ExpressError = require("./utils/ExpressError");
  const campgroundsRoutes = require("./routes/campground");
  const reviewsRoutes = require("./routes/reviews");
  const userRoutes = require("./routes/user");
  
  const User = require("./models/user");
  
  const MongoStore = require("connect-mongo")(session);
  const dbUrl = process.env.DB_URL || "mongodb://localhost:27017/yelp-camp";
  
  mongoose.connect(dbUrl, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  });
  
  const db = mongoose.connection;
  db.on("error", console.error.bind(console, "Connection Error"));
  db.once("open", () => {
    console.log("Database connected");
  });
  
  const app = express();
  app.engine("ejs", engine);
  
  app.set("view engine", "ejs");
  app.set("views", path.join(__dirname, "views"));
  
  app.use(express.urlencoded({ extended: true })); // For express to be able to parse jsons into the body :)
  app.use(methodOverride("_method"));
  app.use(express.static(path.join(__dirname, "public")));
  app.use(mongoSanitize());
  
  const secret = process.env.SECRET || "thisIsAStringSecretKey";
  
  const store = new MongoStore({
    url: dbUrl,
    secret,
    touchAfter: 25 * 3600,
  });
  
  store.on("error", function (e) {
    console.log("Session error", e);
  });
  
  const sessionConfig = {
    store,
    name: "session",
    secret,
    resave: false,
    saveUninitialized: true,
    cookie: {
      httpOnly: true,
      expires: Date.now() + 1000 * 60 * 60 * 24, //Todays date + 1 day extra
      maxAge: 1000 * 60 * 60 * 24, //One day
    },
  };
  
  app.use(session(sessionConfig));
  app.use(flash());
  
  const scriptSrcUrls = [
    "https://stackpath.bootstrapcdn.com/",
    "https://api.tiles.mapbox.com/",
    "https://api.mapbox.com/",
    "https://kit.fontawesome.com/",
    "https://cdnjs.cloudflare.com/",
    "https://cdn.jsdelivr.net/",
    "https://res.cloudinary.com/dv5vm4sqh/",
  ];
  const styleSrcUrls = [
    "https://kit-free.fontawesome.com/",
    "https://stackpath.bootstrapcdn.com/",
    "https://api.mapbox.com/",
    "https://api.tiles.mapbox.com/",
    "https://fonts.googleapis.com/",
    "https://use.fontawesome.com/",
    "https://cdn.jsdelivr.net/",
    "https://res.cloudinary.com/dv5vm4sqh/",
  ];
  const connectSrcUrls = [
    "https://*.tiles.mapbox.com",
    "https://api.mapbox.com",
    "https://events.mapbox.com",
    `https://res.cloudinary.com/${process.env.CLOUDINARY_CLOUD_NAME}/`,
  ];
  
  const fontSrcUrls = [];
  
  app.use(
    helmet.contentSecurityPolicy({
      directives: {
        defaultSrc: [],
        connectSrc: ["'self'", ...connectSrcUrls],
        scriptSrc: ["'unsafe-inline'", "'self'", ...scriptSrcUrls],
        styleSrc: ["'self'", "'unsafe-inline'", ...styleSrcUrls],
        workerSrc: ["'self'", "blob:"],
        objectSrc: [],
        imgSrc: [
          "'self'",
          "blob:",
          "data:",
          `https://res.cloudinary.com/${process.env.CLOUDINARY_CLOUD_NAME}/`, //SHOULD MATCH YOUR CLOUDINARY ACCOUNT!
          "https://images.unsplash.com/",
        ],
        fontSrc: ["'self'", ...fontSrcUrls],
        mediaSrc: [
          `https://res.cloudinary.com/${process.env.CLOUDINARY_CLOUD_NAME}/`,
        ],
        childSrc: ["blob:"],
      },
    })
  );
  
  app.use(passport.initialize());
  app.use(passport.session());
  passport.use(new LocalStrategy(User.authenticate())); //Setting passport to use the local strategy to authenticate the user
  
  passport.serializeUser(User.serializeUser());
  passport.deserializeUser(User.deserializeUser());
  
  app.use((req, res, next) => {
    res.locals.currentUser = req.user;
    res.locals.success = req.flash("success");
    res.locals.error = req.flash("error");
    next();
  });
  
  app.use("/", userRoutes);
  app.use("/campgrounds", campgroundsRoutes);
  app.use("/campgrounds/:id/reviews", reviewsRoutes);
  
  app.get("/", (req, res) => {
    res.render("home");
  });
  
  app.all("*", (req, res, next) => {
    next(new ExpressError("Page not found", 404));
  });
  
  app.use((err, req, res, next) => {
    const { statusCode = 500 } = err;
    if (!err.message) err.message = "Oh no, something went wrong";
    res.status(statusCode).render("error", { err });
  });
  
  const port = process.env.PORT || 3000;
  app.listen(port, () => {
    console.log(`Serving on port ${port}`);
  });
  