Skip to content

Commit

Permalink
Add user id to logs
Browse files Browse the repository at this point in the history
  • Loading branch information
Timothy-Gonzalez committed Oct 23, 2024
1 parent add3ebb commit 084db0c
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 4 deletions.
6 changes: 5 additions & 1 deletion src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import Config from "./common/config";
import database from "./middleware/database";
import corsSelector from "./middleware/cors-selector";
import { getOpenAPISpec, SWAGGER_UI_OPTIONS } from "./common/openapi";
import { tryGetAuthenticatedUser } from "./common/auth";

const app = express();

Expand All @@ -34,7 +35,10 @@ app.use(corsSelector);

// Enable request output when not a test
if (!Config.TEST) {
app.use(morgan("dev"));
morgan.token("id", function (req, _res) {
return tryGetAuthenticatedUser(req)?.id || "unauthenticated";
});
app.use(morgan(":status :method :url :id :response-time ms"));
}

// Automatically convert requests from json
Expand Down
5 changes: 2 additions & 3 deletions src/common/auth.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import ms from "ms";
import jsonwebtoken, { SignOptions } from "jsonwebtoken";
import { Request } from "express";
import { RequestHandler } from "express-serve-static-core";
import passport, { AuthenticateOptions, Profile } from "passport";

Expand Down Expand Up @@ -164,7 +163,7 @@ export function decodeJwtToken(token?: string): JwtPayload {
* @param req The request
* @returns User payload
*/
export function getAuthenticatedUser(req: Request): JwtPayload {
export function getAuthenticatedUser(req: IncomingMessage): JwtPayload {

Check failure on line 166 in src/common/auth.ts

View workflow job for this annotation

GitHub Actions / lint

Cannot find name 'IncomingMessage'.

Check failure on line 166 in src/common/auth.ts

View workflow job for this annotation

GitHub Actions / build

Cannot find name 'IncomingMessage'.
return decodeJwtToken(req.headers.authorization);
}

Expand All @@ -173,7 +172,7 @@ export function getAuthenticatedUser(req: Request): JwtPayload {
* @param req The request
* @returns User payload
*/
export function tryGetAuthenticatedUser(req: Request): JwtPayload | null {
export function tryGetAuthenticatedUser(req: IncomingMessage): JwtPayload | null {

Check failure on line 175 in src/common/auth.ts

View workflow job for this annotation

GitHub Actions / lint

Cannot find name 'IncomingMessage'.

Check failure on line 175 in src/common/auth.ts

View workflow job for this annotation

GitHub Actions / build

Cannot find name 'IncomingMessage'.
try {
return decodeJwtToken(req.headers.authorization);
} catch {
Expand Down

0 comments on commit 084db0c

Please sign in to comment.