define user interface and publicUser for requests

This commit is contained in:
hippoz 2022-04-06 12:29:11 +03:00
parent c0bd6b9725
commit 72dbb36dbb
Signed by: hippoz
GPG key ID: 7C52899193467641
4 changed files with 17 additions and 6 deletions

View file

@ -45,7 +45,7 @@ export function signToken(userId: number) {
}); });
} }
export function decodeToken(encoded: string): Promise<JwtPayload> { export function decodeToken(encoded: string): Promise<User> {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
verify( verify(
encoded, encoded,
@ -79,7 +79,7 @@ export function decodeToken(encoded: string): Promise<JwtPayload> {
}); });
} }
export async function decodeTokenOrNull(encoded: string): Promise<JwtPayload | undefined> { export async function decodeTokenOrNull(encoded: string): Promise<User | undefined> {
try { try {
const decoded = await decodeToken(encoded); const decoded = await decodeToken(encoded);
return decoded; return decoded;
@ -90,14 +90,19 @@ export async function decodeTokenOrNull(encoded: string): Promise<JwtPayload | u
export function authenticateRoute() { export function authenticateRoute() {
return async (req: Request, res: Response, next: NextFunction) => { return async (req: Request, res: Response, next: NextFunction) => {
const pass = (user: object | null = null) => { const pass = (user: User | null = null) => {
if (user === null) { if (!user) {
res.status(403).send({ res.status(403).send({
...errors.BAD_AUTH ...errors.BAD_AUTH
}); });
return; return;
} }
req.user = user; req.user = user;
req.publicUser = {...user};
if (req.publicUser.password) {
delete req.publicUser.password;
}
next(); next();
}; };

View file

@ -76,7 +76,7 @@ route.get(
"/self", "/self",
authenticateRoute(), authenticateRoute(),
(req, res) => { (req, res) => {
return res.status(200).send(req.user); return res.status(200).send(req.publicUser);
} }
); );

View file

@ -1,5 +1,6 @@
declare namespace Express { declare namespace Express {
export interface Request { export interface Request {
user: object | null user: User | null,
publicUser: User | null
} }
} }

5
src/types/user.d.ts vendored Normal file
View file

@ -0,0 +1,5 @@
interface User {
password?: string,
username: string,
id: number
}