define user
interface and publicUser for requests
This commit is contained in:
parent
c0bd6b9725
commit
72dbb36dbb
4 changed files with 17 additions and 6 deletions
13
src/auth.ts
13
src/auth.ts
|
@ -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();
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
|
@ -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);
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|
3
src/types/express.d.ts
vendored
3
src/types/express.d.ts
vendored
|
@ -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
5
src/types/user.d.ts
vendored
Normal file
|
@ -0,0 +1,5 @@
|
||||||
|
interface User {
|
||||||
|
password?: string,
|
||||||
|
username: string,
|
||||||
|
id: number
|
||||||
|
}
|
Loading…
Reference in a new issue