Optimized code and wrote documentation
This commit is contained in:
+22
-7
@@ -1,4 +1,4 @@
|
||||
import { FreshContext } from "$fresh/server.ts";
|
||||
import { FreshContext, MiddlewareHandler } from "$fresh/server.ts";
|
||||
import { getCookies } from "$std/http/cookie.ts";
|
||||
import { getJwtPayload, isJwtValid } from "@popov/jwt";
|
||||
import { CasContent, LoginJWT, State } from "$root/defaults/interfaces.ts";
|
||||
@@ -41,11 +41,17 @@ export function getKey(user: string): string {
|
||||
return jwtKeyCache[user];
|
||||
}
|
||||
|
||||
export const handler = [
|
||||
export const handler: MiddlewareHandler<State>[] = [
|
||||
/**
|
||||
* Check if user is authenticated and add session to context accordingly.
|
||||
* @param request The HTTP incomming request.
|
||||
* @param context The Fresh context object with custom `State`.
|
||||
* @returns The response from the next middleware.
|
||||
*/
|
||||
async function checkAuthentication(
|
||||
request: Request,
|
||||
context: FreshContext<State>,
|
||||
) {
|
||||
): Promise<Response> {
|
||||
const cookies = getCookies(request.headers);
|
||||
if (!cookies["sessionToken"]) {
|
||||
context.state.isAuthenticated = false;
|
||||
@@ -59,17 +65,26 @@ export const handler = [
|
||||
cookies["sessionToken"],
|
||||
key,
|
||||
);
|
||||
const session: CasContent =
|
||||
(getJwtPayload(cookies["sessionToken"]) as LoginJWT).user;
|
||||
|
||||
context.state.session = session;
|
||||
if (context.state.isAuthenticated) {
|
||||
const session: CasContent =
|
||||
(getJwtPayload(cookies["sessionToken"]) as LoginJWT).user;
|
||||
context.state.session = session;
|
||||
}
|
||||
|
||||
return await context.next();
|
||||
},
|
||||
/**
|
||||
* Check if page can be accessed with or without authentication.
|
||||
* Redirect if the page is private and the user isn't authenticated.
|
||||
* @param request The HTTP incomming request.
|
||||
* @param context The Fresh context object with `State` set up.
|
||||
* @returns The response from the next middleware or from the page.
|
||||
*/
|
||||
async function ensureAuthentication(
|
||||
request: Request,
|
||||
context: FreshContext<State>,
|
||||
) {
|
||||
): Promise<Response> {
|
||||
const url = new URL(request.url);
|
||||
|
||||
if (!isRoutePublic(url.pathname) && !context.state.isAuthenticated) {
|
||||
|
||||
Reference in New Issue
Block a user