Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions custom.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { TokenPayload } from "./src/shared/modules/auth/types/TokenPayload.js";

declare module "express-serve-static-core" {
export interface Request {
tokenPayload: TokenPayload;
}
}
15 changes: 15 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@
"got": "^14.6.6",
"http-status-codes": "^2.3.0",
"inversify": "^6.0.1",
"jose": "^4.15.4",
"mime-types": "3.0.2",
"mongoose": "^7.5.3",
"multer": "2.1.1",
Expand Down
2 changes: 2 additions & 0 deletions src/main.rest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,15 @@ import { createRestContainer } from './rest/rest.container.js';
import { createUserContainer } from './shared/modules/user/user.container.js';
import { createOfferContainer } from './shared/modules/offer/offer.container.js';
import { createCommentContainer } from './shared/modules/comment/comment.container.js';
import { createAuthContainer } from './shared/modules/auth/auth-container.js';

async function bootstrap() {
const appContainer = Container.merge(
createRestContainer(),
createUserContainer(),
createOfferContainer(),
createCommentContainer(),
createAuthContainer(),
);

const application = appContainer.get<RestApplication>(
Expand Down
13 changes: 13 additions & 0 deletions src/rest/rest.application.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { getMongoUri } from '../shared/helpers/database-client.js';
import express, { Express } from 'express';
import { Controller } from '../shared/libs/rest/controller/controller.interface.js';
import { ExceptionFilter } from '../shared/libs/rest/exception-filter/exception-filter.interface.js';
import { ParseTokenMiddleware } from '../shared/libs/rest/middleware/parse-token.middleware.js';

@injectable()
export class RestApplication {
Expand All @@ -25,6 +26,8 @@ export class RestApplication {
private readonly exceptionFilter: ExceptionFilter,
@inject(Component.CommentController)
private readonly commentController: Controller,
@inject(Component.AuthExceptionFilter)
private readonly authExceptionFilter: ExceptionFilter,
) {
this.server = express();
}
Expand All @@ -42,6 +45,13 @@ export class RestApplication {
}

private async _initMiddleware() {
const authenticateMiddleware = new ParseTokenMiddleware(
this.config.get('JWT_SECRET'),
);

this.server.use(
authenticateMiddleware.execute.bind(authenticateMiddleware),
);
this.server.use(express.json());
this.server.use(
'/upload',
Expand All @@ -61,6 +71,9 @@ export class RestApplication {
}

private async __initExceptionFilters() {
this.server.use(
this.authExceptionFilter.catch.bind(this.authExceptionFilter),
);
this.server.use(this.exceptionFilter.catch.bind(this.exceptionFilter));
}

Expand Down
7 changes: 7 additions & 0 deletions src/shared/libs/config/rest.config.schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ export type RestSchema = {
DB_PORT: string;
DB_NAME: string;
UPLOAD_FILE_DIRECTORY: string;
JWT_SECRET: string;
};

convict.addFormats(validator);
Expand Down Expand Up @@ -63,4 +64,10 @@ export const restSchema = convict<RestSchema>({
env: 'UPLOAD_FILE_DIRECTORY',
default: null,
},
JWT_SECRET: {
doc: 'JWT secret',
format: String,
env: 'JWT_SECRET',
default: null,
},
});
61 changes: 61 additions & 0 deletions src/shared/libs/rest/middleware/parse-token.middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import { NextFunction, Request, Response } from 'express';
import { Middleware } from '../index.js';
import crypto from 'node:crypto';
import { jwtVerify } from 'jose';
import { HttpError } from '../errors/index.js';
import { StatusCodes } from 'http-status-codes';
import { TokenPayload } from '../../../modules/auth/types/TokenPayload.js';

function isTokenPayload(payload: unknown): payload is TokenPayload {
return (
typeof payload === 'object' &&
payload !== null &&
'email' in payload &&
typeof payload.email === 'string' &&
'name' in payload &&
typeof payload.name === 'string' &&
'id' in payload &&
typeof payload.id === 'string'
);
}

export class ParseTokenMiddleware implements Middleware {
constructor(private readonly jwtSecret: string) {}

async execute(
req: Request,
_res: Response,
next: NextFunction,
): Promise<void> {
const authorizationHeader = req.headers?.authorization?.split(' ');

if (
!authorizationHeader ||
authorizationHeader?.[0] !== 'Bearer' ||
!authorizationHeader?.[1]
) {
return next();
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Нет проверки что схема была реально Bearer , из-за этого возможны лишние вызовы jwtVerify на undefined значение


const [, token] = authorizationHeader;
try {
const { payload } = await jwtVerify(
token,
crypto.createSecretKey(this.jwtSecret, 'utf-8'),
);

if (isTokenPayload(payload)) {
req.tokenPayload = { ...payload };
}
return next();
} catch (err) {
return next(
new HttpError(
StatusCodes.UNAUTHORIZED,
'Invalid token',
'AuthenticateMiddleware',
),
);
}
}
}
18 changes: 18 additions & 0 deletions src/shared/libs/rest/middleware/private-route.middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { NextFunction, Request, Response } from 'express';
import { Middleware } from '../index.js';
import { HttpError } from '../errors/index.js';
import { StatusCodes } from 'http-status-codes';

export class PrivateRouteMiddleware implements Middleware {
execute(req: Request, _res: Response, next: NextFunction): void {
if (!req.tokenPayload) {
throw new HttpError(
StatusCodes.UNAUTHORIZED,
'Unauthorized',
'PrivateRouteMiddleware',
);
}

return next();
}
}
19 changes: 19 additions & 0 deletions src/shared/modules/auth/auth-container.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { Container } from 'inversify';
import { Component } from '../../types/container.js';
import { DefaultAuthService } from './auth-service.js';
import { AuthExceptionFilter } from './auth.exception-filter.js';

export function createAuthContainer() {
const authContainer = new Container();

authContainer
.bind(Component.AuthService)
.to(DefaultAuthService)
.inSingletonScope();
authContainer
.bind(Component.AuthExceptionFilter)
.to(AuthExceptionFilter)
.inSingletonScope();

return authContainer;
}
6 changes: 6 additions & 0 deletions src/shared/modules/auth/auth-service.interface.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { LoginUserDTO, UserEntity } from '../user/index.js';

export interface AuthServiceInterface {
authenticate(user: UserEntity): Promise<string>;
verify(dto: LoginUserDTO): Promise<UserEntity | null>;
}
59 changes: 59 additions & 0 deletions src/shared/modules/auth/auth-service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { inject, injectable } from 'inversify';
import { LoginUserDTO, UserEntity } from '../user/index.js';
import { AuthServiceInterface } from './auth-service.interface.js';
import { Component } from '../../types/container.js';
import { Logger } from '../../libs/logger/index.js';
import { UserService } from '../user/user-service.js';
import { Config, RestSchema } from '../../libs/config/index.js';
import * as crypto from 'node:crypto';
import { TokenPayload } from './types/TokenPayload.js';
import { SignJWT } from 'jose';
import { JWT_ALGORITHM, JWT_EXPIRED } from './auth.constant.js';
import {
UserNotFoundException,
UserPasswordIncorrectException,
} from './errors/index.js';

@injectable()
export class DefaultAuthService implements AuthServiceInterface {
constructor(
@inject(Component.Logger) private readonly logger: Logger,
@inject(Component.UserService) private readonly userService: UserService,
@inject(Component.Config) private readonly config: Config<RestSchema>,
) {}

public async authenticate(user: UserEntity): Promise<string> {
const secret = this.config.get('JWT_SECRET');
const secretKey = crypto.createSecretKey(secret, 'utf-8');

const tokenPayload: TokenPayload = {
email: user.email,
name: user.name,
id: user._id.toString(),
};

this.logger.info(`Create token for ${user.email}`);

return new SignJWT(tokenPayload)
.setProtectedHeader({ alg: JWT_ALGORITHM })
.setIssuedAt()
.setExpirationTime(JWT_EXPIRED)
.sign(secretKey);
}

public async verify(dto: LoginUserDTO): Promise<UserEntity | null> {
const user = await this.userService.findByEmail(dto.email);

if (!user) {
this.logger.warn(`User with ${dto.email} not found`);
throw new UserNotFoundException();
}

if (!user.verifyPassword(dto.password, this.config.get('SALT'))) {
this.logger.warn(`Incorrect password for user ${dto.email}`);
throw new UserPasswordIncorrectException();
}

return user;
}
}
2 changes: 2 additions & 0 deletions src/shared/modules/auth/auth.constant.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export const JWT_ALGORITHM = 'HS256';
export const JWT_EXPIRED = '2d';
31 changes: 31 additions & 0 deletions src/shared/modules/auth/auth.exception-filter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { NextFunction, Request, Response } from 'express';
import { ExceptionFilter } from '../../libs/rest/exception-filter/exception-filter.interface.js';
import { BaseUserException } from './index.js';
import { Logger } from '../../libs/logger/index.js';
import { Component } from '../../types/container.js';
import { inject, injectable } from 'inversify';

@injectable()
export class AuthExceptionFilter implements ExceptionFilter {
constructor(@inject(Component.Logger) private readonly logger: Logger) {
this.logger.info('AuthExceptionFilter was created');
}

public catch(
error: unknown,
_req: Request,
res: Response,
next: NextFunction,
): void {
if (!(error instanceof BaseUserException)) {
return next(error);
}

this.logger.error(`[AuthModule] ${error.message}`, error);

res.status(error.httpStatusCode).json({
type: 'AUTHORIZATION',
error: error.message,
});
}
}
7 changes: 7 additions & 0 deletions src/shared/modules/auth/errors/base-user.exception.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { HttpError } from '../../../libs/rest/errors/index.js';

export class BaseUserException extends HttpError {
constructor(httpStatusCode: number, message: string) {
super(httpStatusCode, message);
}
}
3 changes: 3 additions & 0 deletions src/shared/modules/auth/errors/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export * from './base-user.exception.js';
export * from './user-password-incorrect.exception.js';
export * from './user-not-found.exception.js';
8 changes: 8 additions & 0 deletions src/shared/modules/auth/errors/user-not-found.exception.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { StatusCodes } from 'http-status-codes';
import { BaseUserException } from './base-user.exception.js';

export class UserNotFoundException extends BaseUserException {
constructor() {
super(StatusCodes.NOT_FOUND, 'User not found');
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { StatusCodes } from 'http-status-codes';
import { BaseUserException } from './base-user.exception.js';

export class UserPasswordIncorrectException extends BaseUserException {
constructor() {
super(StatusCodes.UNAUTHORIZED, 'User password incorrect');
}
}
3 changes: 3 additions & 0 deletions src/shared/modules/auth/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export * from './auth-container.js';
export * from './auth-service.interface.js';
export * from './errors/index.js';
5 changes: 5 additions & 0 deletions src/shared/modules/auth/types/TokenPayload.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export type TokenPayload = {
email: string;
name: string;
id: string;
};
6 changes: 5 additions & 1 deletion src/shared/modules/comment/comment-controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { Request, Response } from 'express';
import { CommentRDO } from './rdo/comment-rdo.js';
import { CommentDto } from './dto/comment-dto.js';
import { ValidateDTOMiddleware } from '../../libs/rest/middleware/validate-object.middleware.js';
import { PrivateRouteMiddleware } from '../../libs/rest/middleware/private-route.middleware.js';

export class CommentController extends BaseController {
constructor(
Expand All @@ -22,7 +23,10 @@ export class CommentController extends BaseController {
path: '/',
method: HttpMethod.Post,
handler: this.create,
middlewares: [new ValidateDTOMiddleware(CommentDto)],
middlewares: [
new ValidateDTOMiddleware(CommentDto),
new PrivateRouteMiddleware(),
],
});
}

Expand Down
Loading
Loading