Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

User ticket view #31

Merged
merged 2 commits into from
May 3, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import configRoutes from "./routes/index.js";

import { fileURLToPath } from "url";
import { dirname } from "path";
import { pageView } from "./middleware.js";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

Expand Down Expand Up @@ -39,6 +40,8 @@ app.use(
})
);

app.use("/tickets/view/:id", pageView);

app.engine("handlebars", exphbs.engine({ defaultLayout: "main" }));
app.set("view engine", "handlebars");

Expand Down
39 changes: 33 additions & 6 deletions data/tickets.js
Original file line number Diff line number Diff line change
Expand Up @@ -145,14 +145,14 @@ const create = async (
};

//get all tickets
const getAll = async () => {
const getAll = async (isAdmin, userID) => {
const ticketCollection = await tickets();
let ticketList = await ticketCollection.find({}).toArray();
if (!ticketList) throw "Error: Could not get all tickets!";
ticketList = ticketList.map((element) => {
return toStringify(element);
});
return ticketList;
return filterResults(ticketList, isAdmin, userID);
};

//gets multiple tickets based on an array of ids
Expand Down Expand Up @@ -301,24 +301,51 @@ const update = async (
return toStringify(updatedInfo.value);
};

const search = async (query) => {
if (!query) return getAll();
const search = async (query, userID, isAdmin) => {
if (!query) return getAll(isAdmin, userID);
if (typeof query !== "string") throw `Error: Search Query must be a string!`;
query = query.trim();
if (query.length === 0) {
return getAll();
return getAll(isAdmin. userID);
}
userID = helpers.checkId(userID, "User ID");

const ticketCollection = await tickets();
return await ticketCollection
let foundTickets = await ticketCollection
.find(
{ $text: { $search: `${query}`, $caseSensitive: false } },
{ score: { $meta: "textScore" } }
)
.sort({ score: { $meta: "textScore" } })
.toArray();

foundTickets = foundTickets.map((element) => {
return toStringify(element);
});

return filterResults(foundTickets, isAdmin, userID);
};

const filterResults = async (inputTickets, isAdmin, userID) => {
let returnVal = [];

if(!isAdmin) {
for(let ticket of inputTickets) {
if(ticket.customerID === userID) {
returnVal.push(ticket);
}

if(ticket.owners.includes(userID)){
returnVal.push(ticket);
}
}
} else{
returnVal = inputTickets;
}

return returnVal;
}

const updateOwners = async (userCollection, ticketID, owners) => {
let updatedInfo;

Expand Down
17 changes: 17 additions & 0 deletions data/users.js
Original file line number Diff line number Diff line change
Expand Up @@ -222,6 +222,23 @@ const checkUser = async (email, password) => {
};
};

export const checkUserAccess = async (userID, ticketID) => {
userID = helpers.checkId(userID, "User ID");
ticketID = helpers.checkId(ticketID, "Ticket ID");
const userCollection = await users();
const user = await userCollection.findOne({ _id: new ObjectId(userID) });
if (user === null) throw "Error: No user found with that ID";
const stringifiedUser = toStringify(user);
let hasAccess = false;
for(let createdTicket of stringifiedUser.createdTickets) {
hasAccess = createdTicket === ticketID || hasAccess;
}
for(let workedOnTicket of stringifiedUser.ticketsBeingWorkedOn) {
hasAccess = workedOnTicket === ticketID || hasAccess;
}
return hasAccess;
}

const search = async (query) => {
if (!query) return getAll();
if (typeof query !== "string") throw `Error: Search Query must be a string!`;
Expand Down
22 changes: 22 additions & 0 deletions middleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { checkUserAccess } from "./data/users.js";

export async function pageView(req, res, next) {
if(req.method === 'GET') {
console.log(req.session)
if (req.session && req.session.user) {
if(req.session.user.role === 'admin'
|| (await checkUserAccess(req.session.user._id, req.params.id))){
return next();
} else if(req.session.user.role === 'user'){
return res.redirect('/');
} else {
throw "Error: Role set to invalid value.";
}
} else {
next();
return;
}
} else {
next();
}
}
1 change: 1 addition & 0 deletions routes/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ const constructorMethod = (app) => {
// res.status(404).json({error: 'Route Not found'});
res.status(404).render("404", {
title: "404 Page not found",
user_id: req.session.user._id,
msg: "Error 404: Page Not Found",
});
});
Expand Down
116 changes: 88 additions & 28 deletions routes/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,34 +2,81 @@ import { Router } from "express";
const router = Router();
import * as helpers from "../helpers.js";
import users from "../data/users.js";
import {ticketData} from '../data/index.js';

router
.route("/")
.get(
(req, res, next) => {
if (!req.session.user) {
req.method = "GET";
return res.redirect("/login");
}
next();
},
async (req, res) => {
//code here for GET
.route('/')
.get((req, res, next) => {
if (!req.session.user) {
req.method = "GET";
return res.redirect("/login");
}
next();
},
async (req, res) => {
let tickets;
try{
tickets = await ticketData.getAll(req.session.user.role === "admin", req.session.user._id);
}catch(e) {
console.log(e);
helpers.renderError(res, 404, 'Issue Retrieving tickets');
return;
}

try {
res.status(200).render("homepage", { title: "Tikit" });
} catch (e) {
res.status(500).render("error", {
title: "Error",
error: "internal server error",
code: "500",
});
}
for(let ticket of tickets){
ticket.createdOn = !ticket.createdOn ? "N/A" : new Date(ticket.createdOn).toLocaleDateString();
ticket.deadline = !ticket.deadline ? "N/A" : new Date(ticket.deadline).toLocaleDateString();
}

try {
res.status(200).render("allTicketsView", {
title: "Tickets View",
user_id: req.session.user._id,
tickets: tickets,
query: ""
});
}catch(e) {
helpers.renderError(res, 500, 'Internal Server Error');
}
//code here for GET
})
.post(async (req, res) => {
//code here for POST
let { searchTickets } = req.body;
let tickets;

try{

if(!searchTickets){
searchTickets = req.body.search;
}
)
.post(async (req, res) => {
//code here for POST
});

tickets = await ticketData.search(searchTickets,
req.session.user._id,
req.session.user.role === "admin");

for(let ticket of tickets){
ticket.createdOn = !ticket.createdOn ? "N/A" : new Date(ticket.createdOn).toLocaleDateString();
ticket.deadline = !ticket.deadline ? "N/A" : new Date(ticket.deadline).toLocaleDateString();
}


}catch(e) {
helpers.renderError(res, 404, 'Issue Retrieving ticket(s)');
return;
}

try {
res.status(200).render("allTicketsView", {
title: "Tickets View",
user_id: req.session.user._id,
tickets: tickets,
query: searchTickets
});
}catch(e) {
helpers.renderError(res, 500, 'Internal Server Error');
}
});

router
.route("/login")
Expand All @@ -45,7 +92,9 @@ router
async (req, res) => {
//code here for GET
try {
res.status(200).render("login", { title: "Login", loginPage: true });
res.status(200).render("login", {
title: "Login",
loginPage: true });
} catch (e) {
res.status(500).render("error", {
title: "Error",
Expand Down Expand Up @@ -74,7 +123,10 @@ router
}
}
} catch (e) {
res.status(400).render("login", { title: "Login", error: `${e}`, loginPage: true });
res.status(400).render("login", {
title: "Login",
user_id: req.session.user._id,
error: `${e}`, loginPage: true });
}
});

Expand Down Expand Up @@ -107,10 +159,14 @@ router
async (req, res) => {
//code here for GET
try {
res.status(200).render("register", { title: "Register", loginPage: true });
res.status(200).render("register", {
title: "Register",
user_id: req.session.user._id,
loginPage: true });
} catch (e) {
res.status(500).render("error", {
title: "Error",
user_id: req.session.user._id,
error: "internal server error",
code: "500",
});
Expand Down Expand Up @@ -163,7 +219,11 @@ router
}
} catch (e) {
// render form with 400 code
res.status(400).render("register", { title: "Register", error: `${e}`, loginPage: true });
res.status(400).render("register", {
title: "Register",
user_id: req.session.user._id,
error: `${e}`,
loginPage: true });
}
});

Expand Down
Loading