♻️ Refactor backend

This commit is contained in:
2022-11-16 19:03:32 +01:00
parent 3666492e90
commit 568bfb9782
5 changed files with 74 additions and 70 deletions

View File

@ -3,64 +3,69 @@ const prisma = new Prisma.PrismaClient();
import { log } from "../logs.js"; import { log } from "../logs.js";
export class Auth { async function login(req, res) {
constructor() {} // Check password
login = async (req, res) => { if (!req.body.password || req.body.password != process.env.AUTH_PASSWORD) {
if (!req.body.password) { res.redirect("/login");
res.redirect("/login"); return;
return; }
} else { // Create a new auth session
if (req.body.password == process.env.AUTH_PASSWORD) { const session = await prisma.session.create({
const session = await prisma.session.create({ data: {
data: { // Expires after 14 days of inactivity
validUntil: new Date(Date.now() + 1000 * 60 * 60 * 24 * 14), // Expires after 14 days validUntil: new Date(Date.now() + 1000 * 60 * 60 * 24 * 14),
}, },
}); });
res.cookie("session", session.token, { res.cookie("session", session.token, {
httpOnly: true, httpOnly: true,
expires: new Date(253402300000000), // Expire "never"
}); expires: new Date(253402300000000),
log("API / Auth", `New session: ${session.token}`); });
res.redirect("/"); log("API / Auth", `New session: ${session.token}`);
} else { res.redirect("/");
res.redirect("/login");
return;
}
}
};
checkLogin = async (req, res, next) => {
if (!process.env.AUTH_PASSWORD) {
next();
return;
}
if (!req.cookies.session) {
res.sendStatus(401);
return;
} else {
const session = await prisma.session.findUnique({
where: {
token: req.cookies.session,
},
});
if (!session) {
res.sendStatus(401);
return;
}
// Renew session expiration date
await prisma.session.update({
where: {
token: session.token,
},
data: {
validUntil: new Date(Date.now() + 1000 * 60 * 60 * 24 * 14),
},
});
}
next();
};
} }
// Check for expired sessions every hour async function checkLogin(req, res, next) {
// If AUTH_PASSWORD env variable is not present don't require any login
if (!process.env.AUTH_PASSWORD) {
next();
return;
}
// If no session cookie is set send 401 Unauthorized
// so the app redirects to the login page
if (!req.cookies.session) {
res.sendStatus(401);
return;
}
// Check the provided session cookie
const session = await prisma.session.findUnique({
where: {
token: req.cookies.session,
},
});
// If no session is found also send 401
if (!session) {
res.sendStatus(401);
return;
}
// Renew session expiration date
await prisma.session.update({
where: {
token: session.token,
},
data: {
validUntil: new Date(Date.now() + 1000 * 60 * 60 * 24 * 14),
},
});
next();
}
export default {
login,
checkLogin,
};
// Clean up expired sessions every hour
setInterval(async () => { setInterval(async () => {
const sessions = await prisma.session.findMany(); const sessions = await prisma.session.findMany();
for (const session of sessions) { for (const session of sessions) {

View File

@ -22,7 +22,7 @@ export async function getTimetable(req, res) {
}, },
}); });
if (!timetable) { if (!timetable) {
res.status(400).send({ res.status(404).send({
success: false, success: false,
error: "no_timetable", error: "no_timetable",
message: "No timetable was found for this class", message: "No timetable was found for this class",
@ -44,7 +44,7 @@ function convertToDate(dateQuery) {
if (dateQuery.match(/^[0-9]+$/) != null) date = parseInt(dateQuery); if (dateQuery.match(/^[0-9]+$/) != null) date = parseInt(dateQuery);
else date = dateQuery; else date = dateQuery;
date = new Date(date).setUTCHours(0, 0, 0, 0); date = new Date(date).setUTCHours(0, 0, 0, 0);
return date; return new Date(date);
} }
// Get substitutions API endpoint (/api/substitutions) // Get substitutions API endpoint (/api/substitutions)
@ -75,11 +75,11 @@ export async function getSubstitutions(req, res) {
// Choose which date to use in database query // Choose which date to use in database query
if (from && to) { if (from && to) {
prismaOptions.where.date = { prismaOptions.where.date = {
gte: new Date(from), gte: from,
lte: new Date(to), lte: to,
}; };
} else if (date) { } else if (date) {
prismaOptions.where.date = new Date(date); prismaOptions.where.date = date;
} else { } else {
// Default to all substitutions for today and in the future // Default to all substitutions for today and in the future
prismaOptions.where.date = { prismaOptions.where.date = {
@ -140,11 +140,11 @@ export async function getHistory(req, res) {
// Choose which date to use in database query // Choose which date to use in database query
if (from && to) { if (from && to) {
prismaOptions.where.substitution.date = { prismaOptions.where.substitution.date = {
gte: new Date(from), gte: from,
lte: new Date(to), lte: to,
}; };
} else if (date) { } else if (date) {
prismaOptions.where.substitution.date = new Date(date); prismaOptions.where.substitution.date = date;
} else { } else {
// Default to history of all substitutions for today and in the future // Default to history of all substitutions for today and in the future
prismaOptions.where.substitution.date = { prismaOptions.where.substitution.date = {
@ -173,7 +173,7 @@ export async function getHistory(req, res) {
// Get classes API endpoints (/api/classes) // Get classes API endpoints (/api/classes)
// Get all available classes where timetable and // Get all available classes where timetable and
// substitutions can be requested for // substitutions can be requested for
export async function getClasses(req, res) { export async function getClasses(_req, res) {
const classes = await prisma.class.findMany({ const classes = await prisma.class.findMany({
select: { select: {
name: true, name: true,

View File

@ -9,7 +9,7 @@ import {
getHistory, getHistory,
getClasses, getClasses,
} from "./api/index.js"; } from "./api/index.js";
import { Auth } from "./api/auth.js"; import auth from "./api/auth.js";
import { Parser } from "./parser/index.js"; import { Parser } from "./parser/index.js";
// Check DSB Mobile credentials are supplied // Check DSB Mobile credentials are supplied
@ -34,7 +34,6 @@ new Parser(
); );
// Create new Auth class to store sessions // Create new Auth class to store sessions
const auth = new Auth();
app.post("/login", auth.login); app.post("/login", auth.login);
// Check login for every API request // Check login for every API request
app.use("/api", auth.checkLogin); app.use("/api", auth.checkLogin);

View File

@ -5,7 +5,7 @@ export async function getAuthtoken(username, password) {
const response = await axios.get( const response = await axios.get(
`${baseUrl}/authid?user=${username}&password=${password}&bundleid&appversion&osversion&pushid` `${baseUrl}/authid?user=${username}&password=${password}&bundleid&appversion&osversion&pushid`
); );
if (response.data == "") throw "Wrong username or password"; if (response.data == "") throw "Wrong DSB username or password";
return response.data; return response.data;
} }

View File

@ -28,9 +28,9 @@ export class Parser {
const plans = []; const plans = [];
for (const entry of data) { for (const entry of data) {
// Download the substitution plan // Download the substitution plan
const data = await this.fetchFile(entry.url); const file = await this.fetchFile(entry.url);
// Parse the substitution plan // Parse the substitution plan
const parsed = parseSubstitutionPlan(data); const parsed = parseSubstitutionPlan(file);
plans.push(parsed); plans.push(parsed);
} }
// Create a new parse event // Create a new parse event