Refactored schemas, naming, and instantiation files.

This commit is contained in:
Harrison Deng 2022-04-01 10:27:58 -05:00
parent 8231f9db67
commit 19bbca36ca
12 changed files with 77 additions and 99 deletions

View File

@ -1,11 +0,0 @@
const prod = {
env: "production",
api_host: ""
};
const dev = {
env: "development",
api_host: "http://localhost:5000", // web server localhost port
};
// export the appropriate environment
export default process.env.NODE_ENV === "production" ? prod : dev;

View File

@ -16,7 +16,7 @@
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"start": "NODE_ENV=development API_HOST=http://localhost:5000 react-scripts start",
"build": "../scripts/build.py",
"test": "react-scripts test",
"eject": "react-scripts eject"

View File

@ -1,15 +1,15 @@
import express from "express";
import { authenticationGuard } from "../middleware/Authority.js";
import { needDatabase } from "../middleware/Database.js";
import Match from "../schemas/Match.js";
import Sport from "../schemas/Sport.js";
import User from "../schemas/User.js";
import { authenticationGuard } from "../middleware/authority.js";
import { needDatabase } from "../middleware/database.js";
import matchModel from "../schemas/matchModel.js";
import sportModel from "../schemas/sportModel.js";
import userModel from "../schemas/userModel.js";
const MatchController = express.Router();
MatchController.get("/search/:sport", needDatabase, async (req, res) => {
try {
let sport = Sport.findByName(req.params.sport);
let query = Match.find({ sport: sport._id });
let sport = sportModel.findByName(req.params.sport);
let query = matchModel.find({ sport: sport._id });
query.where("dateTime").gte(Date.now); // We don't want to return any results of matches that have already occurred.
if (req.query.within) query.where("location").within({ center: req.query.location.split(","), radius: req.query.within });
if (req.query.minDifficulty) query.where("difficulty").gte(req.query.minDifficulty);
@ -28,19 +28,20 @@ MatchController.get("/search/:sport", needDatabase, async (req, res) => {
MatchController.post("/", needDatabase, authenticationGuard, async (req, res) => {
try {
const userId = req.session.userId;
const match = new Match({
const user = await userModel.findById(userId);
const match = new matchModel({
title: req.body.title,
dateTime: req.body.dateTime,
public: req.body.public,
location: req.body.location,
creator: userId,
difficulty: req.body.difficulty,
sport: await Sport.findByName(req.body.sport)
sport: await sportModel.findByName(req.body.sport),
participants: [user._id]
});
await match.save();
const user = await User.findById(userId);
user.createdMatches.push(match._id);
user.participatingMatches.value.push(match._id);
user.participatingMatches.push(match._id);
await user.save();
res.status(201).send(match);
} catch (error) {
@ -56,7 +57,7 @@ MatchController.get("/:matchId", needDatabase, async (req, res) => {
return;
}
try {
const match = await Match.findById(req.params.matchId);
const match = await matchModel.findById(req.params.matchId);
if (match) {
res.status(200).send(match);
} else {

View File

@ -1,19 +1,19 @@
import express from "express";
import { authenticationGuard } from "../middleware/Authority.js";
import { needDatabase } from "../middleware/Database.js";
import Sport from "../schemas/Sport.js";
import User from "../schemas/User.js";
import { authenticationGuard } from "../middleware/authority.js";
import { needDatabase } from "../middleware/database.js";
import sportModel from "../schemas/sportModel.js";
import userModel from "../schemas/userModel.js";
const SportController = express.Router();
SportController.post("/", needDatabase, authenticationGuard, async (req, res) => {
const user = await User.findById(req.session.userId);
const user = await userModel.findById(req.session.userId);
try {
if (user.accessLevel <= 2) {
res.status(403).send("Insufficient privileges.");
return;
}
const sport = new Sport({
const sport = new sportModel({
name: req.body.name,
maxPlayers: req.body.maxPlayers,
minPlayers: req.body.minPlayers,
@ -29,7 +29,7 @@ SportController.post("/", needDatabase, authenticationGuard, async (req, res) =>
SportController.get("/:sportId", needDatabase, async (req, res) => {
try {
res.status(200).send(await Sport.findById(req.params.sportId));
res.status(200).send(await sportModel.findById(req.params.sportId));
} catch (error) {
res.status(500).send("Internal server error.");
// TODO: Add proper error checking here.
@ -38,7 +38,7 @@ SportController.get("/:sportId", needDatabase, async (req, res) => {
SportController.get("/", needDatabase, async (req, res) => {
try {
res.status(200).send(await Sport.find());
res.status(200).send(await sportModel.find());
} catch (error) {
res.status(500).send("Internal server error.");
// TODO: Add proper error checking here.

View File

@ -1,7 +1,7 @@
import express from "express";
import { authenticationGuard } from "../middleware/Authority.js";
import { needDatabase } from "../middleware/Database.js";
import User from "../schemas/User.js";
import { authenticationGuard } from "../middleware/authority.js";
import { needDatabase } from "../middleware/database.js";
import User from "../schemas/userModel.js";
const UserController = express.Router();
UserController.post("/login", needDatabase, async (req, res) => {
@ -14,7 +14,7 @@ UserController.post("/login", needDatabase, async (req, res) => {
return;
} else {
req.session.userId = user._id;
req.session.email = user.email.value;
req.session.email = user.email;
res.status(200).send("Authenticated.");
}
} catch (error) {
@ -54,7 +54,7 @@ UserController.get("/email/:userId?", needDatabase, authenticationGuard, async (
const curUser = await User.findById(req.session.userId);
const selUser = req.session.userId === req.params.userId ? curUser : await User.findById(req.params.userId);
if (selUser.email.public || curUser._id === selUser._id || curUser.accessLevel > 2) {
res.status(200).send({ email: selUser.email.value });
res.status(200).send({ email: selUser.email });
} else {
res.status(401).send("Could not authenticate request.");
}
@ -65,7 +65,7 @@ UserController.get("/firstName/:userId?", needDatabase, authenticationGuard, asy
const curUser = await User.findById(req.session.userId);
const selUser = req.session.userId === req.params.userId ? curUser : await User.findById(req.params.userId);
if (selUser.firstName.public || curUser._id === selUser._id || curUser.accessLevel > 2) {
res.status(200).send({ firstName: selUser.firstName.value });
res.status(200).send({ firstName: selUser.firstName });
} else {
res.status(401).send("Could not authenticate request.");
}
@ -76,7 +76,7 @@ UserController.get("/lastName/:userId?", needDatabase, authenticationGuard, asyn
const curUser = await User.findById(req.session.userId);
const selUser = req.session.userId === req.params.userId ? curUser : await User.findById(req.params.userId);
if (selUser.lastName.public || curUser._id === selUser._id || curUser.accessLevel > 2) {
res.status(200).send({ email: selUser.lastName.value });
res.status(200).send({ email: selUser.lastName });
} else {
res.status(401).send("Could not authenticate request.");
}
@ -87,7 +87,7 @@ UserController.get("/phone/:userId?", needDatabase, authenticationGuard, async (
const curUser = await User.findById(req.session.userId);
const selUser = req.session.userId === req.params.userId ? curUser : await User.findById(req.params.userId);
if (selUser.phone.public || curUser._id === selUser._id || curUser.accessLevel > 2) {
res.status(200).send({ phone: selUser.phone.value });
res.status(200).send({ phone: selUser.phone });
} else {
res.status(401).send("Could not authenticate request.");
}
@ -95,10 +95,10 @@ UserController.get("/phone/:userId?", needDatabase, authenticationGuard, async (
UserController.get("/participatingMatches/:userId?", needDatabase, authenticationGuard, async (req, res) => {
if (!req.params.userId) req.params.userId = req.session.userId;
const curUser = await User.findById(req.session.userId).populate("participatingMatches.value");
const curUser = await User.findById(req.session.userId);
const selUser = req.session.userId === req.params.userId ? curUser : await User.findById(req.params.userId);
if (selUser.participatingMatches.public || curUser._id === selUser._id || curUser.accessLevel > 2) {
res.status(200).send({ participatingMatches: selUser.participatingMatches.value });
res.status(200).send({ participatingMatches: selUser.participatingMatches });
} else {
res.status(401).send("Could not authenticate request.");
}
@ -117,7 +117,7 @@ UserController.get("/joinDate/:userId?", needDatabase, authenticationGuard, asyn
UserController.get("/createdMatches/:userId?", needDatabase, authenticationGuard, async (req, res) => {
if (!req.params.userId) req.params.userId = req.session.userId;
const curUser = await User.findById(req.session.userId).populate("createdMatches");
const curUser = await User.findById(req.session.userId);
const selUser = req.session.userId === req.params.userId ? curUser : await User.findById(req.params.userId);
if (curUser._id === selUser._id || curUser.accessLevel > 2) {
res.status(200).send({ createdMatches: selUser.createdMatches });
@ -139,6 +139,7 @@ UserController.post("/", needDatabase, async (req, res) => {
});
await createdUser.save();
res.sendStatus(201);
return;
} catch (err) {
if (err.name === "TypeError" || err.name === "ValidationError") {
if (process.env.NODE_ENV === "development") {

View File

@ -1,16 +1,2 @@
import mongoose from "mongoose";
export const dbName = process.env.DB_NAME || "sm_db";
export const mongooseDbName = process.env.DB_NAME || "sm_db";
export const mongoURI = process.env.MONGODB_URI || "mongodb://127.0.0.1:27017";
// Connection documentation: https://mongoosejs.com/docs/connections.html
try {
mongoose.connect(mongoURI, {
useNewUrlParser: true,
useUnifiedTopology: true,
dbName: dbName,
});
} catch (error) {
console.error(error);
}
export { mongoose };

View File

@ -1,6 +1,6 @@
import MongoStore from "connect-mongo";
import session from "express-session";
import { dbName, mongoURI } from "../database/mongoose.js";
import { mongooseDbName, mongoURI } from "../database/mongoose.js";
const sessionConf = {
secret: process.env.SESSION_SECRET || "super duper secret string.",
cookie: {
@ -12,7 +12,7 @@ const sessionConf = {
};
if (process.env.NODE_ENV === "production") {
sessionConf.cookie.secure = true;
sessionConf.store = MongoStore.create({ mongoUrl: mongoURI, dbName: dbName });
sessionConf.store = MongoStore.create({ mongoUrl: mongoURI, dbName: mongooseDbName });
}
export const userSession = session(sessionConf);

View File

@ -1,4 +1,4 @@
import { mongoose } from "../database/mongoose.js";
import mongoose from "mongoose";
export function needDatabase(res, req, next) {
if (mongoose.connection.readyState != 1) {

View File

@ -7,7 +7,6 @@ const Types = mongoose.Schema.Types;
const userSchema = new mongoose.Schema({
email: {
value: {
type: String,
required: true,
minlength: 1,
@ -18,21 +17,10 @@ const userSchema = new mongoose.Schema({
message: "String not email.",
}
},
public: { type: Boolean, required: true, default: false }
},
firstName: {
value: { type: String, required: true, trim: true },
public: { type: Boolean, required: true, default: false }
},
lastName: {
value: { type: String, required: true, trim: true },
public: { type: Boolean, required: true, default: false }
},
firstName: { type: String, required: true, trim: true },
lastName: { type: String, required: true, trim: true },
joinDate: { type: Date, default: Date.now, required: true },
phone: {
value: { type: Number, required: false, min: 0 },
public: { type: Boolean, required: true, default: false }
},
phone: { type: Number, required: false, min: 0 },
password: {
type: String,
required: true,
@ -40,16 +28,17 @@ const userSchema = new mongoose.Schema({
// TODO: Custom validator for password requirements?
},
createdMatches: { type: [{ type: Types.ObjectId, ref: ModelNameRegister.Match }], required: true, default: [] },
participatingMatches: {
value: { type: [{ type: Types.ObjectId, ref: ModelNameRegister.Match }], required: true, default: [] },
public: { type: Boolean, required: true, default: false }
},
accessLevel: { type: Number, required: true, default: 0 }
participatingMatches: { type: [{ type: Types.ObjectId, ref: ModelNameRegister.Match }], required: true, default: [] },
emailPublicity: { type: Number, required: true, default: 0 },
bioPublicity: { type: Boolean, required: true, default: false },
phonePublicity: { type: Boolean, required: true, default: false },
participatingMatchesPublicity: { type: Boolean, required: true, default: false },
accessLevel: { type: Number, required: true, default: 0 },
});
userSchema.statics.credentialsExist = async function (email, password) {
let userModel = this;
let user = await userModel.findOne({ "email.value": email });
let user = await userModel.findOne({ email: email });
if (!user) {
return Promise.reject(new Error("Credentials do not exist."));
}

View File

@ -1,16 +1,28 @@
import express from "express";
import bodyParser from "body-parser";
import { mongoose } from "./database/mongoose.js";
import UserController from "./controllers/UserController.js";
import MatchController from "./controllers/MatchController.js";
import SportController from "./controllers/SportController.js";
import { userSession } from "./middleware/Authority.js";
import mongoose from "mongoose";
import UserController from "./controllers/userController.js";
import MatchController from "./controllers/matchController.js";
import SportController from "./controllers/sportController.js";
import { userSession } from "./middleware/authority.js";
import { mongooseDbName, mongoURI } from "./database/mongoose.js";
const server = express();
const port = process.env.PORT || 3000;
const port = process.env.PORT || 5000;
server.use(express.static("public")); // For all client files.
// Connection documentation: https://mongoosejs.com/docs/connections.html
try {
mongoose.connect(mongoURI, {
useNewUrlParser: true,
useUnifiedTopology: true,
dbName: mongooseDbName,
});
} catch (error) {
console.error(error);
}
if (process.env.NODE_ENV === "development") {
mongoose.set("bufferCommands", false); // We want to know if there are connection issues immediately for development. Disables globally.
}