Repository navigation
Посторонним вход запрещён #11
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
keksobot
merged 3 commits into
htmlacademy-nodejs-api:master
from
Vladimir-456:module8-task1
May 14, 2026
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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; | ||
| } | ||
| } |
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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(); | ||
| } | ||
|
|
||
| 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
18
src/shared/libs/rest/middleware/private-route.middleware.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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(); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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>; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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; | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,2 @@ | ||
| export const JWT_ALGORITHM = 'HS256'; | ||
| export const JWT_EXPIRED = '2d'; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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, | ||
| }); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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'; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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'); | ||
| } | ||
| } |
8 changes: 8 additions & 0 deletions
8
src/shared/modules/auth/errors/user-password-incorrect.exception.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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'); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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'; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| export type TokenPayload = { | ||
| email: string; | ||
| name: string; | ||
| id: string; | ||
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Нет проверки что схема была реально Bearer , из-за этого возможны лишние вызовы jwtVerify на undefined значение