First commit

This commit is contained in:
AndrewTrieu
2023-04-21 13:17:50 +03:00
commit c9f31e5c8a
26 changed files with 465 additions and 0 deletions

View File

@@ -0,0 +1,17 @@
const restrictedPaths = ["/index"];
const authMiddleware = async (context, next) => {
const user = await context.state.session.get("user");
if (
!user &&
restrictedPaths.some((path) =>
context.request.url.pathname.startsWith(path)
)
) {
context.response.redirect("/auth/login");
} else {
await next();
}
};
export { authMiddleware };

View File

@@ -0,0 +1,9 @@
const errorMiddleware = async (context, next) => {
try {
await next();
} catch (e) {
console.log(e);
}
};
export { errorMiddleware };

View File

@@ -0,0 +1,24 @@
import { configure, renderFile } from "../deps.js";
const renderMiddleware = async (context, next) => {
configure({
views: `${Deno.cwd()}/views/`,
});
context.render = async (file, data) => {
if (!data) {
data = {};
}
if (context.user) {
data.user = context.user;
}
context.response.headers.set("Content-Type", "text/html; charset=utf-8");
context.response.body = await renderFile(file, data);
};
await next();
};
export { renderMiddleware };

View File

@@ -0,0 +1,15 @@
import { send } from "../deps.js";
const serveStaticMiddleware = async (context, next) => {
if (context.request.url.pathname.startsWith("/static")) {
const path = context.request.url.pathname.substring(7);
await send(context, path, {
root: `${Deno.cwd()}/static`,
});
} else {
await next();
}
};
export { serveStaticMiddleware };

View File

@@ -0,0 +1,14 @@
import * as authService from "../services/authService.js";
const userMiddleware = async (context, next) => {
const user = await context.state.session.get("user");
if (user) {
const userFromDatabase = await authService.findUser(user.username);
context.user = userFromDatabase[0];
}
await next();
};
export { userMiddleware };