initial commit, boilerplate stuff
This commit is contained in:
50
api/middleware/auth.ts
Normal file
50
api/middleware/auth.ts
Normal file
@@ -0,0 +1,50 @@
|
||||
import { Context, Next, State } from "@oak/oak";
|
||||
import { verifyJWT } from "../lib/jwt.ts";
|
||||
import {
|
||||
APIErrorCode,
|
||||
APIException,
|
||||
type AuthPayload,
|
||||
} from "../model/interfaces.ts";
|
||||
|
||||
export interface AuthContext extends Context {
|
||||
state: AuthState;
|
||||
}
|
||||
|
||||
export interface AuthState extends State {
|
||||
user: AuthPayload;
|
||||
}
|
||||
|
||||
export async function authMiddleware(ctx: AuthContext, next: Next) {
|
||||
const authHeader = ctx.request.headers.get("Authorization");
|
||||
|
||||
if (!authHeader || !authHeader.startsWith("Bearer ")) {
|
||||
throw new APIException(
|
||||
APIErrorCode.UNAUTHORIZED,
|
||||
401,
|
||||
"Missing or invalid token",
|
||||
);
|
||||
}
|
||||
|
||||
const token = authHeader.substring(7);
|
||||
const payload = await verifyJWT(token);
|
||||
|
||||
if (!payload) {
|
||||
throw new APIException(APIErrorCode.UNAUTHORIZED, 401, "Invalid token");
|
||||
}
|
||||
|
||||
ctx.state.user = payload;
|
||||
|
||||
await next();
|
||||
}
|
||||
|
||||
export async function adminOnlyMiddleware(ctx: AuthContext, next: Next) {
|
||||
if (!ctx.state.user?.isAdmin) {
|
||||
throw new APIException(
|
||||
APIErrorCode.UNAUTHORIZED,
|
||||
403,
|
||||
"Admin access required",
|
||||
);
|
||||
}
|
||||
|
||||
await next();
|
||||
}
|
||||
37
api/middleware/error.ts
Normal file
37
api/middleware/error.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
import { Context, Next } from "@oak/oak";
|
||||
|
||||
import { APIErrorCode, APIException, APIFailure } from "../model/interfaces.ts";
|
||||
|
||||
export async function errorMiddleware(ctx: Context, next: Next) {
|
||||
try {
|
||||
await next();
|
||||
} catch (err) {
|
||||
if (err instanceof APIException) {
|
||||
const responseBody: APIFailure = {
|
||||
success: false,
|
||||
error: {
|
||||
code: err.code,
|
||||
message: err.message,
|
||||
},
|
||||
};
|
||||
|
||||
ctx.response.status = err.status;
|
||||
ctx.response.body = responseBody;
|
||||
|
||||
console.log(responseBody);
|
||||
} else {
|
||||
console.error(err);
|
||||
|
||||
const responseBody: APIFailure = {
|
||||
success: false,
|
||||
error: {
|
||||
code: APIErrorCode.SERVER_ERROR,
|
||||
message: "Unexpected server error",
|
||||
},
|
||||
};
|
||||
|
||||
ctx.response.status = 500;
|
||||
ctx.response.body = responseBody;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user