diff --git a/apis/authCommand/dockerfile b/apis/authCommand/dockerfile index 5272196..18612da 100644 --- a/apis/authCommand/dockerfile +++ b/apis/authCommand/dockerfile @@ -21,5 +21,5 @@ COPY --from=build /app/package.json /app/yarn.lock* ./ RUN yarn install --production --frozen-lockfile COPY --from=build /app/dist ./dist -EXPOSE 3000 -CMD ["node", "dist/index.js"] +EXPOSE 5000 +CMD ["node", "dist/server.js"] diff --git a/apis/authCommand/package.json b/apis/authCommand/package.json index 7492aa1..ae16c2c 100644 --- a/apis/authCommand/package.json +++ b/apis/authCommand/package.json @@ -3,9 +3,9 @@ "version": "1.0.0", "main": "server.js", "scripts": { - "start": "tsc && node dist/server.js", + "start": "node dist/server.js", "dev": "nodemon src/server.ts", - "build": "tsc", + "build": "rm -rf ./dist && tsc", "lint": "eslint .", "lint:fix": "eslint . --fix", "prettier": "prettier --write .", diff --git a/apis/authCommand/server.ts b/apis/authCommand/server.ts index 7b942b2..c833ce5 100644 --- a/apis/authCommand/server.ts +++ b/apis/authCommand/server.ts @@ -26,13 +26,13 @@ app.use((req: Request, res: Response, next: NextFunction) => { next(); }); -app.get("/", (req, res) => { - res.send("Hello, TypeScript Node Express!"); +app.get("/", (req: Request, res: Response) => { + res.send("Hello, TypeScript Node Express! Auth Command"); }); app.use("/doc", swaggerUi.serve, swaggerUi.setup(swaggerSpec)); -app.use("/auth", authRoutes); +app.use("/", authRoutes); app.use(errorHandler()); diff --git a/apis/authQuery/dockerfile b/apis/authQuery/dockerfile index 5272196..18612da 100644 --- a/apis/authQuery/dockerfile +++ b/apis/authQuery/dockerfile @@ -21,5 +21,5 @@ COPY --from=build /app/package.json /app/yarn.lock* ./ RUN yarn install --production --frozen-lockfile COPY --from=build /app/dist ./dist -EXPOSE 3000 -CMD ["node", "dist/index.js"] +EXPOSE 5000 +CMD ["node", "dist/server.js"] diff --git a/apis/authQuery/server.ts b/apis/authQuery/server.ts index 7b942b2..3c055bf 100644 --- a/apis/authQuery/server.ts +++ b/apis/authQuery/server.ts @@ -26,13 +26,13 @@ app.use((req: Request, res: Response, next: NextFunction) => { next(); }); -app.get("/", (req, res) => { - res.send("Hello, TypeScript Node Express!"); +app.get("/", (req: Request, res: Response) => { + res.send("Hello, TypeScript Node Express! Auth Query"); }); app.use("/doc", swaggerUi.serve, swaggerUi.setup(swaggerSpec)); -app.use("/auth", authRoutes); +app.use("/", authRoutes); app.use(errorHandler()); diff --git a/apis/gateway/Interface/controllers/auth/sign-up.controller.ts b/apis/gateway/Interface/controllers/auth/sign-up.controller.ts deleted file mode 100644 index f5b1bf5..0000000 --- a/apis/gateway/Interface/controllers/auth/sign-up.controller.ts +++ /dev/null @@ -1,75 +0,0 @@ -import { Request, Response, NextFunction } from "express"; -import { RegisterUseCase } from '../../../application/usecases/auth/register.usecase'; -import { config } from "dotenv"; -import { TokenHelper } from "../../../shared/helpers/token.helper"; -import connectDB from "../../../infrastructure/databases/database"; -import { RepositoryError } from "../../../application/errors/repository-error"; -import { BadRequestError } from "../../../application/errors"; - -config(); -if (!process.env.DB_TYPE) { - throw new RepositoryError(); // DB_TYPE environment variable is not defined -} -const database = await connectDB(process.env.DB_TYPE); -const userRepo = database && 'userRepository' in database ? await database.userRepository : null; -const tokenService = new TokenHelper(); -if (!userRepo) { - throw new RepositoryError(); // User repository is not available -} -const registerUseCase = new RegisterUseCase(userRepo, tokenService); - -export class SignUpController { - /** - * @swagger - * /auth/register: - * post: - * summary: Register a new user - * tags: [Auth] - * requestBody: - * required: true - * content: - * application/json: - * schema: - * type: object - * required: - * - email - * - password - * properties: - * email: - * type: string - * description: The user's email - * password: - * type: string - * description: The user's password - * responses: - * 201: - * description: The created user - * content: - * application/json: - * schema: - * $ref: '#/components/schemas/User' - * 400: - * description: Email and password are required - * 409: - * description: Email already exists - * 500: - * description: Internal server error - */ - async register(req: Request, res: Response): Promise { - try { - if (!req.body || !req.body.email || !req.body.password) { - res.status(400); - throw new BadRequestError(); // Email and password are required - } - - const token = await registerUseCase.execute(req.body); - return res.json({token}); - - } catch (error) { - if (!res.statusCode) { - res.status(500); - } - return res; - } - } -} \ No newline at end of file diff --git a/apis/gateway/Interface/docs/swagger.ts b/apis/gateway/Interface/docs/swagger.ts deleted file mode 100644 index 7faddca..0000000 --- a/apis/gateway/Interface/docs/swagger.ts +++ /dev/null @@ -1,73 +0,0 @@ -import { config } from "dotenv"; -import swaggerJsdoc from "swagger-jsdoc"; - -config(); -interface SwaggerOptions { - definition: { - openapi: string; - info: { - title: string; - version: string; - description: string; - }; - components: { - securitySchemes: { - bearerAuth: { - type: string; - scheme: string; - bearerFormat: string; - }; - }; - }; - security: { bearerAuth: string[] }[]; - servers: { - url: string; - description: string; - }[]; - }; - apis: string[]; -} - -const hostname: string = process.env.API_HOST || "localhost"; -const port: string | number = process.env.API_PORT || 5000; - -const swaggerOptions: SwaggerOptions = { - definition: { - openapi: "3.0.0", - info: { - title: "E-commerce API", - version: "0.1.0", - description: "E-commerce API documentation", - }, - components: { - securitySchemes: { - bearerAuth: { - type: "http", - scheme: "bearer", - bearerFormat: "JWT", - }, - }, - }, - security: [ - { - bearerAuth: [], - }, - ], - servers: [ - { - url: `http://${hostname || "localhost"}:${port || 5000}`, - description: "Development server", - }, - ], - }, - apis: ["src/controllers/*.ts", "src/services/mongoose/schema/*.ts"], -}; - -const swaggerSpec = swaggerJsdoc(swaggerOptions); -if (!swaggerSpec) { - throw new Error( - "Erreur lors de la configuration de Swagger : swaggerSpec est undefined." - ); -} - -export default swaggerSpec; diff --git a/apis/gateway/Interface/middlewares/bcrypt.ts b/apis/gateway/Interface/middlewares/bcrypt.ts deleted file mode 100644 index a607ad6..0000000 --- a/apis/gateway/Interface/middlewares/bcrypt.ts +++ /dev/null @@ -1,31 +0,0 @@ -import bcrypt from "bcryptjs"; -import { Logger } from "../../config/logger"; - -const logger = Logger.get(); - -export class Bcrypt { - private saltRounds: number; - - constructor(saltRounds: number = 10) { - this.saltRounds = saltRounds; - } - - async hashPassword(password: string): Promise { - try { - const salt = bcrypt.genSaltSync(this.saltRounds); - return bcrypt.hashSync(password, salt); - } catch (error) { - logger.error(new Error(`Error hashing password: ${error}`)); - throw new Error("Erreur lors du hachage du mot de passe"); - } - } - - async comparePassword(password: string, hash: string): Promise { - try { - return bcrypt.compareSync(password, hash); - } catch (error) { - logger.error(new Error(`Error comparing password: ${error}`)); - throw new Error("Erreur lors de la comparaison des mots de passe"); - } - } -} diff --git a/apis/gateway/Interface/middlewares/errorHandler.ts b/apis/gateway/Interface/middlewares/errorHandler.ts deleted file mode 100644 index a448552..0000000 --- a/apis/gateway/Interface/middlewares/errorHandler.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { NextFunction, Request, Response } from "express"; -import { Logger } from "../../config/logger"; - -const logger = Logger.get(); - -const errorHandler = () => { - return (err: any, req: Request, res: Response, next: NextFunction) => { - const statusCode = res.statusCode; - if (statusCode === 500) { - logger.error( - new Error( - `${statusCode}: ${req.method} ${req.url} - clientIP: ${req.ip}, errorStack: ${err.stack}, url: ${req.originalUrl}, method: ${req.method}, ip: ${req.ip}` - ) - ); - } - if ([400, 401, 403, 404, 409].includes(statusCode)) { - logger.warn( - `${statusCode}: ${req.method} ${req.url} - clientIP: ${req.ip}, errorMessage: ${err.message}, url: ${req.originalUrl}, method: ${req.method}, ip: ${req.ip}` - ); - } - - res.status(statusCode).json({ - message: err.message, - ...(process.env.MODE_ENV === "production" ? null : { stack: err.stack }), - }); - }; -}; - -export default errorHandler; diff --git a/apis/gateway/Interface/middlewares/jwt.ts b/apis/gateway/Interface/middlewares/jwt.ts deleted file mode 100644 index eebc123..0000000 --- a/apis/gateway/Interface/middlewares/jwt.ts +++ /dev/null @@ -1,57 +0,0 @@ -import { config } from "dotenv"; -import { NextFunction, Request, Response } from "express"; -import jwt from "jsonwebtoken"; -import { Logger } from "../../config/logger"; - -config(); -const logger = Logger.get(); - -const SECRET_KEY: string | undefined = process.env.JWT_SECRET; - -// Génération d'un token JWT -const generateToken = (user: any) => { - if (!SECRET_KEY) { - logger.error(new Error("SECRET_KEY is not defined")); - return ""; - } - return jwt.sign( - { - id: user._id, - email: user.email, - role: user.role, - }, - SECRET_KEY, - { expiresIn: "1d" } - ); -}; - -// Vérification du token JWT -const authenticateToken = (req: Request, res: Response, next: NextFunction) => { - const authHeader = req.headers["authorization"]; - const jwtToken = authHeader && authHeader.split(" ")[1]; - - try { - if (!jwtToken) { - res.status(401); - throw new Error("Token manquant"); - } - if (!SECRET_KEY) { - res.status(500); - throw new Error("SECRET_KEY is not defined"); - } - jwt.verify(jwtToken, SECRET_KEY, (err: any, user: any) => { - if (err) { - res.status(403); - throw new Error("Token invalide"); - } - next(); - }); - } catch (error) { - if (!res.statusCode) { - res.status(500); - } - next(error); - } -}; - -export { authenticateToken, generateToken }; diff --git a/apis/gateway/Interface/middlewares/validateRole.ts b/apis/gateway/Interface/middlewares/validateRole.ts deleted file mode 100644 index 0913353..0000000 --- a/apis/gateway/Interface/middlewares/validateRole.ts +++ /dev/null @@ -1,130 +0,0 @@ -import { Request, Response, NextFunction } from "express"; -import jwt from "jsonwebtoken"; -import { Role } from "../models"; -import connectDB from "../../infrastructure/databases/database"; -import { config } from "dotenv"; - -config(); -const SECRET_KEY: string | undefined = process.env.JWT_SECRET; - -const getUser = async (req: Request, res: Response) => { - if (!SECRET_KEY) { - res.status(500); - throw new Error("JWT_SECRET is not defined"); - } - - const authHeader = req.headers["authorization"]; - const jwtToken = authHeader && authHeader.split(" ")[1]; - - if (!jwtToken) { - res.status(401); - throw new Error("No token, authorization denied"); - } - - const decoded = jwt.verify(jwtToken, SECRET_KEY) as jwt.JwtPayload; - - const dbType = process.env.DB_TYPE; - if (!dbType) { - res.status(500); - throw new Error("DB_TYPE is not defined"); - } - const database = await connectDB(dbType); - const userRepo = database && 'userRepository' in database ? await database.userRepository : null; - const user = await userRepo.findById(decoded.id); - if (!user) { - res.status(401); - throw new Error("Authentication failed"); - } - return user; -}; - -export const validateRole = async ( - req: Request, - res: Response, - next: NextFunction, - role: Role[] -) => { - try { - const user = await getUser(req, res); - if (role.length === 1) { - if (user.role !== role[0]) { - res.status(403); - throw new Error("Unauthorized"); - } - next(); - } - if (role.length === 2) { - if (user.role !== role[0] && user.role !== role[1]) { - res.status(403); - throw new Error("Unauthorized"); - } - next(); - } - if (role.length === 3) { - if ( - user.role !== role[0] && - user.role !== role[1] && - user.role !== role[2] - ) { - res.status(403); - throw new Error("Unauthorized"); - } - next(); - } - } catch (error) { - if (!res.statusCode) { - res.status(500); - } - next(error); - } -}; - -export const validateRoleAdmin = async ( - req: Request, - res: Response, - next: NextFunction -) => { - validateRole(req, res, next, [Role.Admin]); -}; -export const validateRoleOwner = async ( - req: Request, - res: Response, - next: NextFunction -) => { - validateRole(req, res, next, [Role.Owner]); -}; -export const validateRoleCustomer = async ( - req: Request, - res: Response, - next: NextFunction -) => { - validateRole(req, res, next, [Role.Customer]); -}; -export const validateRoleAdminOwner = async ( - req: Request, - res: Response, - next: NextFunction -) => { - validateRole(req, res, next, [Role.Admin, Role.Owner]); -}; -export const validateRoleAdminCustomer = async ( - req: Request, - res: Response, - next: NextFunction -) => { - validateRole(req, res, next, [Role.Admin, Role.Customer]); -}; -export const validateRoleOwnerCustomer = async ( - req: Request, - res: Response, - next: NextFunction -) => { - validateRole(req, res, next, [Role.Owner, Role.Customer]); -}; -export const validateRoleAll = async ( - req: Request, - res: Response, - next: NextFunction -) => { - validateRole(req, res, next, [Role.Admin, Role.Owner, Role.Customer]); -}; diff --git a/apis/gateway/Interface/routes/auth.routes.ts b/apis/gateway/Interface/routes/auth.routes.ts deleted file mode 100644 index a88a0c0..0000000 --- a/apis/gateway/Interface/routes/auth.routes.ts +++ /dev/null @@ -1,10 +0,0 @@ -import express from "express"; -import { SignUpController } from "../controllers/auth/sign-up.controller"; - -const router = express.Router(); - -// router.post("/login", AuthController.login); -const signUpController = new SignUpController(); -router.post("/register", signUpController.register.bind(signUpController)); - -export default router; diff --git a/apis/gateway/application/dtos/auth/index.ts b/apis/gateway/application/dtos/auth/index.ts deleted file mode 100644 index f4e811d..0000000 --- a/apis/gateway/application/dtos/auth/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from "./login.user.dto"; -export * from "./register.user.dto"; \ No newline at end of file diff --git a/apis/gateway/application/dtos/auth/register.user.dto.ts b/apis/gateway/application/dtos/auth/register.user.dto.ts deleted file mode 100644 index f7b4274..0000000 --- a/apis/gateway/application/dtos/auth/register.user.dto.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { Role } from "../../../domain/enums" - -export interface RegisterUserDTO { - email: string; - password: string; - role?: Role; -} \ No newline at end of file diff --git a/apis/gateway/application/errors/bad-request-error.ts b/apis/gateway/application/errors/bad-request-error.ts deleted file mode 100644 index 793c019..0000000 --- a/apis/gateway/application/errors/bad-request-error.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { DefaultApplicationError } from './default-application-error'; - -export class BadRequestError extends DefaultApplicationError { - name = 'BadRequestError'; - statusCode = 400; -} - \ No newline at end of file diff --git a/apis/gateway/application/errors/date-time-error.ts b/apis/gateway/application/errors/date-time-error.ts deleted file mode 100644 index c771a19..0000000 --- a/apis/gateway/application/errors/date-time-error.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { DefaultApplicationError } from './default-application-error'; - -export class DateTimeError extends DefaultApplicationError { - statusCode = 500; - name = 'DateTimeError'; -} diff --git a/apis/gateway/application/errors/default-application-error.ts b/apis/gateway/application/errors/default-application-error.ts deleted file mode 100644 index bf1f074..0000000 --- a/apis/gateway/application/errors/default-application-error.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { ResponseModel } from '../ports/responses/response.interface'; - -export type ErrorParams = { - name?: string; - message?: string; - statusCode?: number; - messages?: string[]; - stack?: Error['stack']; -}; - -export type ErrorResponseModel = Omit, 'body'>; - -export class DefaultApplicationError - extends Error - implements ErrorResponseModel { - public statusCode = 500; - public messages: string[] = []; - - constructor(message?: string) { - super(message); - this.message = message || this.name; - this.name = 'DefaultApplicationError'; - this.messages.push(this.message); - } -} diff --git a/apis/gateway/application/errors/email-validation-error.ts b/apis/gateway/application/errors/email-validation-error.ts deleted file mode 100644 index 22ecabd..0000000 --- a/apis/gateway/application/errors/email-validation-error.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { DefaultApplicationError } from './default-application-error'; - -export class EmailValidationError extends DefaultApplicationError { - statusCode = 400; - name = 'EmailValidationError'; -} diff --git a/apis/gateway/application/errors/index.ts b/apis/gateway/application/errors/index.ts deleted file mode 100644 index d6466af..0000000 --- a/apis/gateway/application/errors/index.ts +++ /dev/null @@ -1,11 +0,0 @@ -export * from './bad-request-error'; -export * from './date-time-error'; -export * from './default-application-error'; -export * from './email-validation-error'; -export * from './internal-server-error'; -export * from './not-found-error'; -export * from './repository-error'; -export * from './request-validation-error'; -export * from './sanitizer-error'; -export * from './unauthorized-error'; -export * from './user-exists-error'; \ No newline at end of file diff --git a/apis/gateway/application/errors/internal-server-error.ts b/apis/gateway/application/errors/internal-server-error.ts deleted file mode 100644 index f92119c..0000000 --- a/apis/gateway/application/errors/internal-server-error.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { DefaultApplicationError } from './default-application-error'; - -export class InternalServerError extends DefaultApplicationError { - name = 'InternalServerError'; - statusCode = 500; -} diff --git a/apis/gateway/application/errors/not-found-error.ts b/apis/gateway/application/errors/not-found-error.ts deleted file mode 100644 index 1e88132..0000000 --- a/apis/gateway/application/errors/not-found-error.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { DefaultApplicationError } from './default-application-error'; - -export class NotFoundError extends DefaultApplicationError { - statusCode = 404; - name = 'NotFoundError'; -} diff --git a/apis/gateway/application/errors/password-validation-error.ts b/apis/gateway/application/errors/password-validation-error.ts deleted file mode 100644 index 88736ea..0000000 --- a/apis/gateway/application/errors/password-validation-error.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { DefaultApplicationError } from './default-application-error'; - -export class EmailValidationError extends DefaultApplicationError { - statusCode = 400; - name = 'PasswordValidationError'; -} \ No newline at end of file diff --git a/apis/gateway/application/errors/repository-error.ts b/apis/gateway/application/errors/repository-error.ts deleted file mode 100644 index c87e1ab..0000000 --- a/apis/gateway/application/errors/repository-error.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { DefaultApplicationError } from './default-application-error'; - -export class RepositoryError extends DefaultApplicationError { - name = 'RepositoryError'; - statusCode = 500; -} diff --git a/apis/gateway/application/errors/request-validation-error.ts b/apis/gateway/application/errors/request-validation-error.ts deleted file mode 100644 index b34692d..0000000 --- a/apis/gateway/application/errors/request-validation-error.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { DefaultApplicationError } from './default-application-error'; - -export class RequestValidationError extends DefaultApplicationError { - statusCode = 400; - name = 'RequestValidationError'; -} diff --git a/apis/gateway/application/errors/sanitizer-error.ts b/apis/gateway/application/errors/sanitizer-error.ts deleted file mode 100644 index 9fb0a7e..0000000 --- a/apis/gateway/application/errors/sanitizer-error.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { DefaultApplicationError } from './default-application-error'; - -export class SanitizerError extends DefaultApplicationError { - name = 'SanitizerError'; - statusCode = 400; -} diff --git a/apis/gateway/application/errors/unauthorized-error.ts b/apis/gateway/application/errors/unauthorized-error.ts deleted file mode 100644 index 445a2fd..0000000 --- a/apis/gateway/application/errors/unauthorized-error.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { DefaultApplicationError } from './default-application-error'; - -export class UnauthorizedError extends DefaultApplicationError { - name = 'UnauthorizedError'; - statusCode = 401; -} diff --git a/apis/gateway/application/errors/user-exists-error.ts b/apis/gateway/application/errors/user-exists-error.ts deleted file mode 100644 index 19e0586..0000000 --- a/apis/gateway/application/errors/user-exists-error.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { DefaultApplicationError } from './default-application-error'; - -export class UserExistsError extends DefaultApplicationError { - statusCode = 409; - name = 'UserExistsError'; -} diff --git a/apis/gateway/application/ports/auth.service.interface.ts b/apis/gateway/application/ports/auth.service.interface.ts deleted file mode 100644 index 125c68e..0000000 --- a/apis/gateway/application/ports/auth.service.interface.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { User } from "../../domain/entities/"; - -export interface AuthServiceInterface { - generateToken(user: User): string; - verifyToken(token: string): User; -} \ No newline at end of file diff --git a/apis/gateway/application/ports/index.ts b/apis/gateway/application/ports/index.ts deleted file mode 100644 index 9ef5ab1..0000000 --- a/apis/gateway/application/ports/index.ts +++ /dev/null @@ -1,3 +0,0 @@ -export * from './auth.service.interface'; -export * from './password.service.interface'; -export * from './user.repository.interface'; diff --git a/apis/gateway/application/ports/password.service.interface.ts b/apis/gateway/application/ports/password.service.interface.ts deleted file mode 100644 index dc51bba..0000000 --- a/apis/gateway/application/ports/password.service.interface.ts +++ /dev/null @@ -1,4 +0,0 @@ -export interface PasswordServiceInterface { - hash(password: string): Promise; - compare(password: string, hash: string): Promise; -} \ No newline at end of file diff --git a/apis/gateway/application/ports/responses/response.interface.ts b/apis/gateway/application/ports/responses/response.interface.ts deleted file mode 100644 index 0c62167..0000000 --- a/apis/gateway/application/ports/responses/response.interface.ts +++ /dev/null @@ -1,5 +0,0 @@ -/* eslint-disable @typescript-eslint/no-explicit-any */ -export interface ResponseModel { - body: T; - statusCode: number; -} diff --git a/apis/gateway/application/ports/user.repository.interface.ts b/apis/gateway/application/ports/user.repository.interface.ts deleted file mode 100644 index acad1ac..0000000 --- a/apis/gateway/application/ports/user.repository.interface.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { User } from '../../domain/entities'; - -export interface UserRepositoryInterface { - - findByEmail(email: string): Promise; - create(user: User): Promise; -} diff --git a/apis/gateway/application/usecases/auth/register.usecase.ts b/apis/gateway/application/usecases/auth/register.usecase.ts deleted file mode 100644 index c1054b2..0000000 --- a/apis/gateway/application/usecases/auth/register.usecase.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { User } from "../../../domain/entities"; -import { RegisterUserDTO } from "../../dtos/auth"; -import { UserExistsError } from "../../errors/user-exists-error"; -import { AuthServiceInterface, UserRepositoryInterface } from "../../ports"; - - -export class RegisterUseCase { - - private userRepository: UserRepositoryInterface; - private authService: AuthServiceInterface; - - constructor(userRepository: UserRepositoryInterface, authService: AuthServiceInterface) { - this.userRepository = userRepository; - this.authService = authService; - } - - async execute(dto: RegisterUserDTO): Promise { - // Fail Fast: Vérifie si les données d’entrée sont valides - if (!dto.email || !dto.password) { - throw new Error("Email et mot de passe sont requis"); - } - - // Vérifie si l’utilisateur existe déjà - const user = await this.userRepository.findByEmail(dto.email); - if (user) { - throw new UserExistsError(); - } - - // Crée un nouvel utilisateur - const newUser = new User(dto.email, dto.password); - await this.userRepository.create(newUser); - - // Génère et retourne un token JWT - return this.authService.generateToken(newUser); - } -} \ No newline at end of file diff --git a/apis/gateway/config/cors.ts b/apis/gateway/config/cors.ts deleted file mode 100644 index 67da7e1..0000000 --- a/apis/gateway/config/cors.ts +++ /dev/null @@ -1,39 +0,0 @@ -import cors from 'cors'; -import { Application } from 'express'; -import { Logger } from './logger'; - -const logger = Logger.get(); - -const configureCORS = (app: Application) => { - const corsOptions = { - origin: (origin: string | undefined, callback: Function) => { - if (!origin) { - callback(null, true); - return; - } - - const allowedOrigins = process.env.ALLOWED_ORIGINS; - if (!allowedOrigins) { - callback(new Error("Request from unauthorized origin")); - return; - } - - const origins = allowedOrigins.split(" "); - if (origins.indexOf(origin) !== -1) { - callback(null, true); - } else { - callback(new Error("Request from unauthorized origin")); - } - }, - methods: ['GET', 'POST', 'PUT', 'DELETE'], - allowedHeaders: ['Content-Type', 'Authorization'], - credentials: true, - optionsSuccessStatus: 200, - }; - - app.use(cors(corsOptions)); - - logger.info('Cors has been enabled'); -}; - -export default configureCORS; diff --git a/apis/gateway/config/helmet.ts b/apis/gateway/config/helmet.ts deleted file mode 100644 index feb48ba..0000000 --- a/apis/gateway/config/helmet.ts +++ /dev/null @@ -1,12 +0,0 @@ -import helmet from 'helmet'; -import { Application } from 'express'; -import { Logger } from './logger'; - -const logger = Logger.get(); - -const configureHelmet = (app: Application) => { - app.use(helmet()); - logger.info('Helmet has been enabled'); -} - -export default configureHelmet; \ No newline at end of file diff --git a/apis/gateway/config/logger.ts b/apis/gateway/config/logger.ts deleted file mode 100644 index cfafb7b..0000000 --- a/apis/gateway/config/logger.ts +++ /dev/null @@ -1,109 +0,0 @@ -import winston from "winston"; -import "winston-daily-rotate-file"; -import { config } from "dotenv"; - -config(); -export class Logger { - private static instance: Logger; - private logger: winston.Logger; - - private readonly level: string = process.env.NODE_ENV === "development" ? "debug" : "info"; - private readonly levels = { error: 0, warn: 1, info: 2, http: 3, debug: 5 }; - private readonly colors = { - error: "red", - warn: "yellow", - info: "green", - http: "magenta", - debug: "white", - }; - private readonly format = winston.format.combine( - winston.format.timestamp({ format: "YYYY-MM-DD HH:mm:ss:ms" }), - winston.format.colorize({ all: true }), - winston.format.errors({ stack: true }), - winston.format.printf((info ) => { - const stack = info.stack ? `\nStack trace: ${info.stack}` : ""; - return `${info.level}: ${info.message}, timestamp : ${info.timestamp}${stack}`; - }) - ); - - - private constructor() { - winston.addColors(this.colors); - - this.logger = winston.createLogger({ - level: this.level, - levels: this.levels, - format: this.format, - transports: this.createTransports(), - exceptionHandlers: this.createExceptionHandlers(), - }); - this.handleUnhandledRejections(); - } - - private createTransports(): winston.transport[] { - return [ - new winston.transports.Console(), - this.createDailyRotateFile("api-combined"), - this.createDailyRotateFile("api-error", "error"), - this.createDailyRotateFile("api-info", "info"), - this.createDailyRotateFile("api-http", "http"), - ]; - } - - private createExceptionHandlers(): winston.transport[] { - return [ - new winston.transports.Console(), - this.createDailyRotateFile("api-exceptions"), - ]; - } - - private createDailyRotateFile( - filename: string, - level?: string - ) { - return new winston.transports.DailyRotateFile({ - filename: `logs/${filename}-%DATE%.log`, - level, - datePattern: "YYYY-MM-DD", - zippedArchive: true, - maxFiles: "14d", - }); - } - - private handleUnhandledRejections(): void { - process.on("unhandledRejection", (reason, promise) => { - this.logger.error(`Unhandled Rejection at: ${promise} reason: ${reason}`); - }); - } - - public static get(): Logger { - if (!Logger.instance) { - Logger.instance = new Logger(); - } - return Logger.instance; - } - - public error(message: Error): void { - this.logger.error(message); - } - - public warn(message: string): void { - this.logger.warn(message); - } - - public info(message: string): void { - this.logger.info(message); - } - - public http(message: string): void { - this.logger.log("http", message); - } - - public debug(message: string): void { - this.logger.debug(message); - } - - public getLogger(): winston.Logger { - return this.logger; - } -} diff --git a/apis/gateway/dockerfile b/apis/gateway/dockerfile index 5272196..07bf48b 100644 --- a/apis/gateway/dockerfile +++ b/apis/gateway/dockerfile @@ -21,5 +21,5 @@ COPY --from=build /app/package.json /app/yarn.lock* ./ RUN yarn install --production --frozen-lockfile COPY --from=build /app/dist ./dist -EXPOSE 3000 +EXPOSE 8080 CMD ["node", "dist/index.js"] diff --git a/apis/gateway/domain/entities/index.ts b/apis/gateway/domain/entities/index.ts deleted file mode 100644 index 6e93025..0000000 --- a/apis/gateway/domain/entities/index.ts +++ /dev/null @@ -1,9 +0,0 @@ -export * from "./incident" -export * from "./maintenance" -export * from "./rental" -export * from "./reservation" -export * from "./scooter" -export * from "./stockOrder" -export * from "./stockPiece" -export * from "./user" -export * from "./warranty" \ No newline at end of file diff --git a/apis/gateway/domain/entities/user.ts b/apis/gateway/domain/entities/user.ts deleted file mode 100644 index e8cf21d..0000000 --- a/apis/gateway/domain/entities/user.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { Role } from '../enums'; -import { UserInterface } from '../interfaces'; -import { v4 as uuidv4 } from 'uuid'; -import { PasswordHelper } from '../../shared/helpers/password.helper'; - -export class User implements UserInterface { - - public id: string; - public email: string; - public password: string; - public role: Role; - public firstName?: string; - public lastName?: string; - public phone?: string; - - constructor( - email: string, - password: string, - role: Role = Role.CUSTOMER, - id: string = uuidv4() - ) { - this.id = id; - this.email = email; - this.password = password; - this.role = role; - } - - isValidPassword(password: string, hashedPassword: string): Promise { - const passwordHelper = new PasswordHelper(); - return passwordHelper.compare(password, hashedPassword); - } -} \ No newline at end of file diff --git a/apis/gateway/domain/enums/index.ts b/apis/gateway/domain/enums/index.ts deleted file mode 100644 index f739fe8..0000000 --- a/apis/gateway/domain/enums/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from "./user.role.enum"; diff --git a/apis/gateway/domain/enums/user.role.enum.ts b/apis/gateway/domain/enums/user.role.enum.ts deleted file mode 100644 index 84681b9..0000000 --- a/apis/gateway/domain/enums/user.role.enum.ts +++ /dev/null @@ -1,5 +0,0 @@ -export enum Role { - ADMIN = "superAdmin", - OWNER = "owner", - CUSTOMER = "customer", -} diff --git a/apis/gateway/domain/interfaces/index.ts b/apis/gateway/domain/interfaces/index.ts deleted file mode 100644 index 15b951b..0000000 --- a/apis/gateway/domain/interfaces/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from "./timestamp.interface"; -export * from "./user.interface"; diff --git a/apis/gateway/domain/interfaces/timestamp.interface.ts b/apis/gateway/domain/interfaces/timestamp.interface.ts deleted file mode 100644 index 15a8e36..0000000 --- a/apis/gateway/domain/interfaces/timestamp.interface.ts +++ /dev/null @@ -1,4 +0,0 @@ -export interface Timestamps { - createdAt: Date; - updatedAt: Date; -} \ No newline at end of file diff --git a/apis/gateway/domain/interfaces/user.interface.ts b/apis/gateway/domain/interfaces/user.interface.ts deleted file mode 100644 index 72cf08c..0000000 --- a/apis/gateway/domain/interfaces/user.interface.ts +++ /dev/null @@ -1,9 +0,0 @@ -export interface UserInterface { - id: string; - firstName?: string; - lastName?: string; - email: string; - password: string; - role: string; - phone?: string; -} diff --git a/apis/gateway/index.ts b/apis/gateway/index.ts index b01a559..84c2108 100644 --- a/apis/gateway/index.ts +++ b/apis/gateway/index.ts @@ -1,64 +1,38 @@ +import express, { Express, Request, Response } from "express"; import proxy from "express-http-proxy"; -import express, { Express, Request, Response, NextFunction } from "express"; -import configureCORS from "./Infrastructure/libs/cors"; -import configureHelmet from "./Infrastructure/libs/helmet"; -import swaggerSpec from "./Infrastructure/docs/swagger"; -import swaggerUi from "swagger-ui-express"; -import { config } from "dotenv"; -import { Logger } from "./Infrastructure/libs/logger"; -import errorHandler from "./Interface/middlewares/errorHandler"; -config(); const app: Express = express(); app.use(express.json()); app.use(express.urlencoded({ extended: true })); -configureCORS(app); -configureHelmet(app); -const logger = Logger.get(); - -app.use((req: Request, res: Response, next: NextFunction) => { - if (process.env.MODE_ENV === "development") { - logger.http( - `${req.method} ${req.url} - ${req.ip} - ${req.headers["user-agent"]}` - ); - } - next(); +app.get("/", (req: Request, res: Response) => { + res.send("Hello, TypeScript Node Express! Gateway"); }); -const authCommand = proxy("http://localhost:8081"); -const authQuery = proxy("http://localhost:8082"); -// const maintenanceCommand = proxy("http://localhost:8083"); -// const maintenanceQuery = proxy("http://localhost:8084"); -// const reservationCommand = proxy("http://localhost:8085"); -// const reservationQuery = proxy("http://localhost:8086"); -// const stockCommand = proxy("http://localhost:8087"); -// const stockQuery = proxy("http://localhost:8088"); +const auth = proxy("http://authcommand:5000"); +const query = proxy("http://authquery:5000"); -app.use("/doc", swaggerUi.serve, swaggerUi.setup(swaggerSpec)); +app.use("/auth", auth); -app.use(errorHandler()); - -app.use("/api/auth", (req: Request, res: Response, next: NextFunction) => { - req.method === "GET" ? authQuery(req, res, next) : authCommand(req, res, next); +const server = app.listen(8080, () => { + console.log("Gateway is Listening to Port 8080"); }); -// app.use("/api/maintenance", (req: Request, res: Response, next: NextFunction) => { -// req.method === "GET" ? maintenanceQuery(req, res, next) : maintenanceCommand(req, res, next); -// }); - -// app.use("/api/reservation", (req: Request, res: Response, next: NextFunction) => { -// req.method === "GET" ? reservationQuery(req, res, next) : reservationCommand(req, res, next); -// }); - -// app.use("/api/stock", (req: Request, res: Response, next: NextFunction) => { -// req.method === "GET" ? stockQuery(req, res, next) : stockCommand(req, res, next); -// }); - -const host = process.env.API_HOST || "localhost"; -const port = process.env.API_PORT || 5000; - -app.listen(port, () => { - console.log(`Server is running on http://${host}:${port}`); - console.log(`Server is running on http://${host}:${port}/doc`); -}); \ No newline at end of file +const exitHandler = () => { + if (server) { + server.close(() => { + console.info("Server closed"); + process.exit(1); + }); + } else { + process.exit(1); + } +}; + +const unexpectedErrorHandler = (error: unknown) => { + console.error(error); + exitHandler(); +}; + +process.on("uncaughtException", unexpectedErrorHandler); +process.on("unhandledRejection", unexpectedErrorHandler); diff --git a/apis/gateway/infrastructure/databases/adapter.ts b/apis/gateway/infrastructure/databases/adapter.ts deleted file mode 100644 index a0f6730..0000000 --- a/apis/gateway/infrastructure/databases/adapter.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { MongooseService } from "./mongoose"; -import { Sequelize } from "sequelize"; - -export interface Adapter { - get(): Promise; - connect(): Promise; - disconnect(): Promise; -} \ No newline at end of file diff --git a/apis/gateway/infrastructure/databases/database.ts b/apis/gateway/infrastructure/databases/database.ts deleted file mode 100644 index bf2bc81..0000000 --- a/apis/gateway/infrastructure/databases/database.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { SequelizeService } from "./sequelize"; -import { MongooseService } from "./mongoose"; - -const connectDB = async (DBType: string): Promise => { - if (DBType === "pgsql") { - return await SequelizeService.get(); - }; - if (DBType === "mongo") { - return await MongooseService.get(); - }; - return undefined; -} - -export default connectDB; diff --git a/apis/gateway/infrastructure/databases/index.ts b/apis/gateway/infrastructure/databases/index.ts deleted file mode 100644 index 5b486c3..0000000 --- a/apis/gateway/infrastructure/databases/index.ts +++ /dev/null @@ -1,6 +0,0 @@ -export * from "./mongoose"; -export * from "./sequelize"; -// export * from "./redis"; -// export * from "./inMemory"; -export * from "./database"; -export * from "./adapter"; diff --git a/apis/gateway/infrastructure/databases/mongoose.ts b/apis/gateway/infrastructure/databases/mongoose.ts deleted file mode 100644 index f86b437..0000000 --- a/apis/gateway/infrastructure/databases/mongoose.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { config } from "dotenv"; -import { Mongoose, connect } from "mongoose"; -import { UserRepository } from "../repositories/mongoose"; -import { Adapter } from "./adapter"; - -config(); -export class MongooseService implements Adapter { - private static instance?: MongooseService; - - readonly mongoose: Mongoose; - readonly userRepository: UserRepository; - - private constructor(mongoose: Mongoose) { - this.mongoose = mongoose; - - this.userRepository = new UserRepository(this); - } - get(): Promise { - return MongooseService.get(); - } - connect(): Promise { - throw new Error("Method not implemented."); - } - - public static async get(): Promise { - if (this.instance !== undefined) { - return this.instance; - } - const connection = await this.connect(); - this.instance = new MongooseService(connection); - return this.instance; - } - - private static async connect(): Promise { - const connection = await connect(process.env.MONGO_URI as string, { - auth: { - username: process.env.MONGO_USER, - password: process.env.MONGO_PASSWORD, - }, - authSource: "admin", - dbName: process.env.MONGO_DB, - }); - return connection; - } - - public async disconnect(): Promise { - await this.mongoose.disconnect(); - } -} diff --git a/apis/gateway/infrastructure/databases/sequelize.ts b/apis/gateway/infrastructure/databases/sequelize.ts deleted file mode 100644 index 1da5874..0000000 --- a/apis/gateway/infrastructure/databases/sequelize.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { config } from "dotenv"; -import { Sequelize } from "sequelize"; -import { UserService } from "./user.service"; -import { Logger } from "../config/logger"; - -config(); -const logger = Logger.get(); - -export class SequelizeService { - private static instance?: SequelizeService; - - readonly sequelize: Sequelize; - readonly userService: UserService; - - private constructor(sequelize: Sequelize) { - this.sequelize = sequelize; - - this.userService = new UserService(this); - } - - public static async get(): Promise { - if (this.instance !== undefined) { - return this.instance; - } - const connection = await this.connect(); - this.instance = new SequelizeService(connection); - return this.instance; - } - - private static async connect(): Promise { - const sequelize = new Sequelize(process.env.POSTGRES_URI as string, { - dialect: "postgres", - logging: false, // Désactiver les logs SQL - }); - - try { - await sequelize.authenticate(); - } catch (error) { - logger.error( new Error("Impossible de se connecter à PostgreSQL :", error)); - } - - return sequelize; - } -} diff --git a/apis/gateway/infrastructure/orms/adapter.ts b/apis/gateway/infrastructure/orms/adapter.ts deleted file mode 100644 index bf58a7e..0000000 --- a/apis/gateway/infrastructure/orms/adapter.ts +++ /dev/null @@ -1,5 +0,0 @@ -export interface Adapter { - get(): Promise; - connect(): Promise; - disconnect(): Promise; -} \ No newline at end of file diff --git a/apis/gateway/infrastructure/orms/mongoose/index.ts b/apis/gateway/infrastructure/orms/mongoose/index.ts deleted file mode 100644 index baedd6d..0000000 --- a/apis/gateway/infrastructure/orms/mongoose/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './user.schema'; diff --git a/apis/gateway/infrastructure/orms/mongoose/user.schema.ts b/apis/gateway/infrastructure/orms/mongoose/user.schema.ts deleted file mode 100644 index e877cfa..0000000 --- a/apis/gateway/infrastructure/orms/mongoose/user.schema.ts +++ /dev/null @@ -1,59 +0,0 @@ -import { Schema } from "mongoose"; -import { User } from "../../../domain/entities"; -import { Role } from "../../../domain/enums"; - -/** - * @swagger - * components: - * schemas: - * User: - * type: object - * required: - * - email - * - password - * - role - * properties: - * email: - * type: string - * description: L'email de l'utilisateur - * password: - * type: string - * description: Le mot de passe de l'utilisateur - * role: - * type: string - * enum: [ROLE_USER, ROLE_STORE_KEEPER, ROLE_ADMIN, ROLE_COMPTA] - * default: ROLE_USER - * description: Le rôle de l'utilisateur - * example: - * email: john.doe@toto.com - * password: password - * role: ROLE_USER - */ - -export const userSchema = new Schema( - { - id: { - type: String, - required: false, - }, - email: { - type: String, - unique: true, - required: true, - }, - password: { - type: String, - required: true, - }, - role: { - type: String, - enum: Object.values(Role), - default: Role.Customer, - }, - }, - { - timestamps: true, - collection: "users", - versionKey: false, - } -); diff --git a/apis/gateway/infrastructure/repositories/index.ts b/apis/gateway/infrastructure/repositories/index.ts deleted file mode 100644 index da83afc..0000000 --- a/apis/gateway/infrastructure/repositories/index.ts +++ /dev/null @@ -1,5 +0,0 @@ -export * from "./repertory-choice"; -export * from "./sequelize/user.repository"; -export * from "./mongoose/user.repository"; -export * from "./sequelize"; -export * from "./mongoose"; \ No newline at end of file diff --git a/apis/gateway/infrastructure/repositories/mongoose/index.ts b/apis/gateway/infrastructure/repositories/mongoose/index.ts deleted file mode 100644 index e7ce7fd..0000000 --- a/apis/gateway/infrastructure/repositories/mongoose/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from "./user.repository"; \ No newline at end of file diff --git a/apis/gateway/infrastructure/repositories/mongoose/user.repository.ts b/apis/gateway/infrastructure/repositories/mongoose/user.repository.ts deleted file mode 100644 index 0b80ad0..0000000 --- a/apis/gateway/infrastructure/repositories/mongoose/user.repository.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { Model } from "mongoose"; -import { UserRepositoryInterface } from "../../../application/ports"; -import { User } from "../../../domain/entities"; -import { userSchema } from "../../orm/mongoose"; -import { MongooseService } from "../../databases"; - -export class UserRepository implements UserRepositoryInterface { - - readonly mongooseService: MongooseService; - readonly model: Model; - - constructor(mongooseService: MongooseService) { - this.mongooseService = mongooseService; - const mongoose = this.mongooseService.mongoose; - this.model = mongoose.model("User",userSchema); - } - - create(user: User): Promise { - throw new Error("Method not implemented."); - } - - async findByEmail(email: string): Promise { - const userData = await this.model.findOne({ email }); - return userData ? new User(userData.email, userData.password, userData.role, userData.id) : null; - } -} diff --git a/apis/gateway/infrastructure/repositories/sequelize/index.ts b/apis/gateway/infrastructure/repositories/sequelize/index.ts deleted file mode 100644 index e7ce7fd..0000000 --- a/apis/gateway/infrastructure/repositories/sequelize/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from "./user.repository"; \ No newline at end of file diff --git a/apis/gateway/infrastructure/repositories/sequelize/user.repository.ts b/apis/gateway/infrastructure/repositories/sequelize/user.repository.ts deleted file mode 100644 index e69de29..0000000 diff --git a/apis/gateway/package.json b/apis/gateway/package.json index 62f664d..491b403 100644 --- a/apis/gateway/package.json +++ b/apis/gateway/package.json @@ -3,9 +3,9 @@ "version": "1.0.0", "main": "server.js", "scripts": { - "start": "tsc && node dist/server.js", - "dev": "nodemon src/server.ts", - "build": "tsc", + "start": "node dist/index.js", + "dev": "nodemon src/index.ts", + "build": "rm -rf ./dist && tsc", "lint": "eslint .", "lint:fix": "eslint . --fix", "prettier": "prettier --write .", @@ -16,30 +16,15 @@ "license": "ISC", "description": "", "dependencies": { - "bcrypt": "^5.1.1", "cors": "^2.8.5", "dotenv": "^16.4.7", "express": "^4.21.2", - "helmet": "^8.0.0", - "jsonwebtoken": "^9.0.2", - "mongoose": "^8.9.6", - "sequelize": "^6.37.5", - "swagger-jsdoc": "^6.2.8", - "swagger-ui-express": "^5.0.1", - "uuid": "^11.0.5", - "winston": "^3.17.0", - "winston-daily-rotate-file": "^5.0.0" + "express-http-proxy": "^2.1.1" }, "devDependencies": { - "@types/bcryptjs": "^2.4.6", "@types/cors": "^2.8.17", "@types/express": "^5.0.0", - "@types/jsonwebtoken": "^9.0.8", - "@types/sequelize": "^4.28.20", - "@types/swagger-jsdoc": "^6.0.4", - "@types/swagger-ui-express": "^4.1.7", - "eslint": "^9.19.0", - "nodemon": "^3.1.9", + "@types/express-http-proxy": "^1.6.6", "prettier": "^3.4.2", "ts-node": "^10.9.2", "typescript": "^5.7.3" diff --git a/apis/gateway/shared/helpers/password.helper.ts b/apis/gateway/shared/helpers/password.helper.ts deleted file mode 100644 index b20a22c..0000000 --- a/apis/gateway/shared/helpers/password.helper.ts +++ /dev/null @@ -1,32 +0,0 @@ -import bcrypt from 'bcryptjs'; -import { Logger } from '../../config/logger'; -import { PasswordServiceInterface } from '../../application/ports/password.service.interface'; - -const logger = Logger.get(); -export class PasswordHelper implements PasswordServiceInterface { - - private saltRounds: number; - - constructor(saltRounds: number = 10) { - this.saltRounds = saltRounds; - } - - async hash(password: string): Promise { - try { - const salt = bcrypt.genSaltSync(this.saltRounds); - return bcrypt.hashSync(password, salt); - } catch (error) { - logger.error(new Error(`Error hashing password: ${error}`)); - throw new Error("Erreur lors du hachage du mot de passe"); - } - } - - async compare(password: string, hash: string): Promise { - try { - return bcrypt.compareSync(password, hash); - } catch (error) { - logger.error(new Error(`Error comparing password: ${error}`)); - throw new Error("Erreur lors de la comparaison des mots de passe"); - } - } -} \ No newline at end of file diff --git a/apis/gateway/shared/helpers/token.helper.ts b/apis/gateway/shared/helpers/token.helper.ts deleted file mode 100644 index 30d21a1..0000000 --- a/apis/gateway/shared/helpers/token.helper.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { sign, verify } from 'jsonwebtoken'; -import { config } from 'dotenv'; -import { Logger } from '../../config/logger'; -import { AuthServiceInterface } from '../../application/ports'; -import { User } from '../../domain/entities'; - -config(); -export class TokenHelper implements AuthServiceInterface { - private secret: string; - - constructor() { - this.secret = process.env.JWT_SECRET || ''; - if (this.secret === '') { - Logger.get().error(new Error('JWT_SECRET is not defined')); - throw new Error('JWT_SECRET is not defined'); - } - } - - generateToken(user: User): string { - return sign({email: user.email, role: user.role}, this.secret, { expiresIn: '1h' }); - } - - verifyToken(token: string): any { - return verify(token, this.secret); - } -} \ No newline at end of file diff --git a/apis/gateway/shared/validators/env.ts b/apis/gateway/shared/validators/env.ts deleted file mode 100644 index e69de29..0000000 diff --git a/docker-compose.yml b/docker-compose.yml index 65d6f14..10fb310 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,57 +1,36 @@ services: - nginx: - build: - context: ./nginx - dockerfile: Dockerfile - ports: - - "8080:8080" - depends_on: - - gateway - - authcommand - - authquery - gateway: build: context: ./apis/gateway - target: production env_file: .env volumes: - - ./api:/api + - ./apis:/api ports: - - "5001:3000" + - "5001:8080" depends_on: - authcommand - - authquery authcommand: - container_name: authCommand + container_name: authcommand build: context: ./apis/authCommand - target: production env_file: .env - volumes: - - ./api:/api - ports: - - 8081:3000 depends_on: - - mongodb - networks: - - voltride + - "mongodb" + environment: + - NODE_ENV=production - authquery: - container_name: authQuery - build: - context: ./apis/authQuery - target: production - env_file: .env - volumes: - - ./api:/api - ports: - - 8082:3000 - depends_on: - - mongodb - networks: - - voltride + # authquery: + # container_name: authQuery + # build: + # context: ./apis/authQuery + # env_file: .env + # volumes: + # - ./apis:/api + # ports: + # - 8082:3000 + # depends_on: + # - mongodb # MaintenanceCommand: # container_name: MaintenanceCommand diff --git a/nginx/Dockerfile b/nginx/Dockerfile deleted file mode 100644 index 744103c..0000000 --- a/nginx/Dockerfile +++ /dev/null @@ -1,5 +0,0 @@ -FROM nginx:alpine3.21 - -RUN rm /etc/nginx/nginx.conf - -COPY nginx.conf /etc/nginx/nginx.conf diff --git a/nginx/nginx.conf b/nginx/nginx.conf deleted file mode 100644 index 66b3f73..0000000 --- a/nginx/nginx.conf +++ /dev/null @@ -1,28 +0,0 @@ -http { - upstream authcommand { - server user:8081; - } - upstream authquery { - server chat:8082; - } - # upstream gateway { - # server notification:8083; - # } - - server { - listen 8080 - - location /user/ { - proxy_pass http://user/; - } - - location /chat/ { - proxy_pass http://chat/; - } - - location /notification/ { - proxy_pass http://notification/; - } - } -} -events {} \ No newline at end of file