From 72dbb36dbb1ffd5d9e5adab120d0ff846bc7a7ad Mon Sep 17 00:00:00 2001 From: hippoz <10706925-hippoz@users.noreply.gitlab.com> Date: Wed, 6 Apr 2022 12:29:11 +0300 Subject: [PATCH] define `user` interface and publicUser for requests --- src/auth.ts | 13 +++++++++---- src/routes/api/v1/users.ts | 2 +- src/types/express.d.ts | 3 ++- src/types/user.d.ts | 5 +++++ 4 files changed, 17 insertions(+), 6 deletions(-) create mode 100644 src/types/user.d.ts diff --git a/src/auth.ts b/src/auth.ts index d921f33..3ba9414 100644 --- a/src/auth.ts +++ b/src/auth.ts @@ -45,7 +45,7 @@ export function signToken(userId: number) { }); } -export function decodeToken(encoded: string): Promise { +export function decodeToken(encoded: string): Promise { return new Promise((resolve, reject) => { verify( encoded, @@ -79,7 +79,7 @@ export function decodeToken(encoded: string): Promise { }); } -export async function decodeTokenOrNull(encoded: string): Promise { +export async function decodeTokenOrNull(encoded: string): Promise { try { const decoded = await decodeToken(encoded); return decoded; @@ -90,14 +90,19 @@ export async function decodeTokenOrNull(encoded: string): Promise { - const pass = (user: object | null = null) => { - if (user === null) { + const pass = (user: User | null = null) => { + if (!user) { res.status(403).send({ ...errors.BAD_AUTH }); return; } + req.user = user; + req.publicUser = {...user}; + if (req.publicUser.password) { + delete req.publicUser.password; + } next(); }; diff --git a/src/routes/api/v1/users.ts b/src/routes/api/v1/users.ts index ded5bcf..e5462e5 100644 --- a/src/routes/api/v1/users.ts +++ b/src/routes/api/v1/users.ts @@ -76,7 +76,7 @@ route.get( "/self", authenticateRoute(), (req, res) => { - return res.status(200).send(req.user); + return res.status(200).send(req.publicUser); } ); diff --git a/src/types/express.d.ts b/src/types/express.d.ts index 2f03740..bbecf00 100644 --- a/src/types/express.d.ts +++ b/src/types/express.d.ts @@ -1,5 +1,6 @@ declare namespace Express { export interface Request { - user: object | null + user: User | null, + publicUser: User | null } } diff --git a/src/types/user.d.ts b/src/types/user.d.ts new file mode 100644 index 0000000..85cab31 --- /dev/null +++ b/src/types/user.d.ts @@ -0,0 +1,5 @@ +interface User { + password?: string, + username: string, + id: number +}