From f1c6217579c531d9019fa309e364eeace8a5ac75 Mon Sep 17 00:00:00 2001 From: Brad Cypert Date: Wed, 4 Dec 2024 19:49:05 -0500 Subject: [PATCH] start on user lookup middleware --- src/users/routes.ts | 19 +++++++++++++++++++ src/users/user-service.ts | 15 ++++++++------- 2 files changed, 27 insertions(+), 7 deletions(-) diff --git a/src/users/routes.ts b/src/users/routes.ts index 73689ee..82527ea 100644 --- a/src/users/routes.ts +++ b/src/users/routes.ts @@ -3,8 +3,27 @@ import { InvalidCredentialsError, UserService } from "./user-service.ts"; import { dustService } from "../../main.ts"; import { validateSignup } from "./validators/signup-validator.ts"; import { validateSignIn } from "./validators/signin-validator.ts"; +import { UserWithId } from "./user.ts"; + +interface Request { + user: UserWithId +} export const registerRoutes = (router: Router) => { + +router.use("/", async (ctx, next) => { + const userService = new UserService(dustService.database); + + const bearer = ctx.request.headers.get("authorization"); + const token = bearer?.split(" ")?.[1]; + if (token != null) { + const payload = await userService.validateJWT(token); + ctx.state.user = payload.user; + } + + next(); +}); + router.post("/auth", async (ctx) => { const userService = new UserService(dustService.database); try { diff --git a/src/users/user-service.ts b/src/users/user-service.ts index 637d553..bad2c67 100644 --- a/src/users/user-service.ts +++ b/src/users/user-service.ts @@ -1,6 +1,6 @@ import type { Database } from "../../database.ts"; import { addUser, getUserByEmail, createSession } from "./data.ts"; -import type { User } from "./user.ts"; +import type { User, UserWithId } from "./user.ts"; import { hash, verify } from "@ts-rex/bcrypt"; import * as jose from "https://deno.land/x/jose@v5.9.6/index.ts"; @@ -48,14 +48,15 @@ export class UserService { this.jwtSecretKey, { name: "HMAC", hash: "SHA-256" }, true, - ["sign"] + ["sign", "verify"] ); } - private async createJWTForUser(user: Omit): Promise { + private async createJWTForUser(user: Omit): Promise { const key = await this.getJWTSecret(); const token = await new jose.SignJWT({ user: { + id: user.id, email: user.email, displayName: user.displayName, }, @@ -70,13 +71,13 @@ export class UserService { return token; } - async validateJWT(token: SignedJWTToken): Promise<{user: {email: string, displayName: string}}> { + async validateJWT(token: SignedJWTToken): Promise<{user: {id: number, email: string, displayName: string}}> { const key = await this.getJWTSecret(); try { // verify token - const { payload, protectedHeader } = await jose.jwtVerify<{user: {email: string, displayName: string}}>(token, key, { - issuer: "dust-server", // issuer - audience: "dust-client", // audience + const { payload, protectedHeader } = await jose.jwtVerify<{user: {id: number, email: string, displayName: string}}>(token, key, { + issuer: "urn:dust:server", // issuer + audience: "urn:dust:client", // audience }); return payload;