diff --git a/src/core/domains/Auth/actions/create.ts b/src/core/domains/auth/actions/create.ts similarity index 97% rename from src/core/domains/Auth/actions/create.ts rename to src/core/domains/auth/actions/create.ts index a7e743c65..beb8b3919 100644 --- a/src/core/domains/Auth/actions/create.ts +++ b/src/core/domains/auth/actions/create.ts @@ -1,67 +1,67 @@ -import Roles from '@src/core/domains/auth/enums/RolesEnum'; -import UserFactory from '@src/core/domains/auth/factory/userFactory'; -import { IUserData } from '@src/core/domains/auth/interfaces/IUserModel'; -import hashPassword from '@src/core/domains/auth/utils/hashPassword'; -import responseError from '@src/core/domains/express/requests/responseError'; -import ValidationError from '@src/core/exceptions/ValidationError'; -import { App } from '@src/core/services/App'; -import { Request, Response } from 'express'; - -/** - * Creates a new user - * - * @param {Request} req - The request object - * @param {Response} res - The response object - * @returns {Promise} - */ -export default async (req: Request, res: Response): Promise => { - - const { email, password, firstName, lastName } = req.body as Pick; - - try { - // Check if the user already exists - const repository = App.container('auth').userRepository; - const existingUser = await repository.findOneByEmail(email); - - if (existingUser) { - // If the user already exists, throw a validation error - throw new ValidationError('User already exists'); - } - - // Create a new user - const user = new UserFactory().create({ - email, - password, - hashedPassword: hashPassword(password ?? ''), - roles: [Roles.USER], - firstName, - lastName - }); - - // Save the user to the database - await user.save(); - - // Generate a JWT token for the user - const token = await App.container('auth').createJwtFromUser(user); - - // Return the user data and the JWT token - res.send({ - success: true, - token, - user: user.getData({ excludeGuarded: true }) - }); - } - catch (error) { - // Handle validation errors - if (error instanceof ValidationError) { - res.status(400).send({ error: error.message }); - return; - } - - // Handle other errors - if (error instanceof Error) { - responseError(req, res, error); - } - } - -} +import Roles from '@src/core/domains/auth/enums/RolesEnum'; +import UserFactory from '@src/core/domains/auth/factory/userFactory'; +import { IUserData } from '@src/core/domains/auth/interfaces/IUserModel'; +import hashPassword from '@src/core/domains/auth/utils/hashPassword'; +import responseError from '@src/core/domains/express/requests/responseError'; +import ValidationError from '@src/core/exceptions/ValidationError'; +import { App } from '@src/core/services/App'; +import { Request, Response } from 'express'; + +/** + * Creates a new user + * + * @param {Request} req - The request object + * @param {Response} res - The response object + * @returns {Promise} + */ +export default async (req: Request, res: Response): Promise => { + + const { email, password, firstName, lastName } = req.body as Pick; + + try { + // Check if the user already exists + const repository = App.container('auth').userRepository; + const existingUser = await repository.findOneByEmail(email); + + if (existingUser) { + // If the user already exists, throw a validation error + throw new ValidationError('User already exists'); + } + + // Create a new user + const user = new UserFactory().create({ + email, + password, + hashedPassword: hashPassword(password ?? ''), + roles: [Roles.USER], + firstName, + lastName + }); + + // Save the user to the database + await user.save(); + + // Generate a JWT token for the user + const token = await App.container('auth').createJwtFromUser(user); + + // Return the user data and the JWT token + res.send({ + success: true, + token, + user: user.getData({ excludeGuarded: true }) + }); + } + catch (error) { + // Handle validation errors + if (error instanceof ValidationError) { + res.status(400).send({ error: error.message }); + return; + } + + // Handle other errors + if (error instanceof Error) { + responseError(req, res, error); + } + } + +} diff --git a/src/core/domains/Auth/actions/getUser.ts b/src/core/domains/auth/actions/getUser.ts similarity index 96% rename from src/core/domains/Auth/actions/getUser.ts rename to src/core/domains/auth/actions/getUser.ts index b8574bba8..706221717 100644 --- a/src/core/domains/Auth/actions/getUser.ts +++ b/src/core/domains/auth/actions/getUser.ts @@ -1,23 +1,23 @@ -import IAuthorizedRequest from '@src/core/domains/auth/interfaces/IAuthorizedRequest'; -import responseError from '@src/core/domains/express/requests/responseError'; -import { Response } from 'express'; - -/** - * Gets the currently logged in user - * - * @param {IAuthorizedRequest} req - * @param {Response} res - * @returns {Promise} - */ -export default async (req: IAuthorizedRequest, res: Response) => { - try { - // Send the user data without the password - res.send({ success: true, user: req.user?.getData({ excludeGuarded: true }) }); - } - catch (error) { - // If there is an error, send the error response - if (error instanceof Error) { - responseError(req, res, error); - } - } -}; +import IAuthorizedRequest from '@src/core/domains/auth/interfaces/IAuthorizedRequest'; +import responseError from '@src/core/domains/express/requests/responseError'; +import { Response } from 'express'; + +/** + * Gets the currently logged in user + * + * @param {IAuthorizedRequest} req + * @param {Response} res + * @returns {Promise} + */ +export default async (req: IAuthorizedRequest, res: Response) => { + try { + // Send the user data without the password + res.send({ success: true, user: req.user?.getData({ excludeGuarded: true }) }); + } + catch (error) { + // If there is an error, send the error response + if (error instanceof Error) { + responseError(req, res, error); + } + } +}; diff --git a/src/core/domains/Auth/actions/login.ts b/src/core/domains/auth/actions/login.ts similarity index 96% rename from src/core/domains/Auth/actions/login.ts rename to src/core/domains/auth/actions/login.ts index 5bebda8b5..99062bdd9 100644 --- a/src/core/domains/Auth/actions/login.ts +++ b/src/core/domains/auth/actions/login.ts @@ -1,43 +1,43 @@ -import unauthorizedError from '@src/core/domains/auth/exceptions/UnauthorizedError'; -import responseError from '@src/core/domains/express/requests/responseError'; -import { App } from '@src/core/services/App'; -import { Request, Response } from 'express'; - -/** - * Logs in a user - * - * @param {Request} req - The request object - * @param {Response} res - The response object - * @returns {Promise} - */ -export default async (req: Request, res: Response): Promise => { - try { - // Get the email and password from the request body - const { email, password } = req?.body ?? {}; - - // Attempt to log in the user - const token = await App.container('auth').attemptCredentials(email, password); - - // Get the user from the database - const user = await App.container('auth').userRepository.findOneByEmail(email); - - // Send the user data and the token back to the client - res.send({ - success: true, - token, - user: user?.getData({ excludeGuarded: true }) - }) - } - catch (error) { - // Handle unauthorized errors - if (error instanceof unauthorizedError) { - res.status(401).send({ error: error.message },) - return; - } - - // Handle other errors - if (error instanceof Error) { - responseError(req, res, error) - } - } -} +import unauthorizedError from '@src/core/domains/auth/exceptions/UnauthorizedError'; +import responseError from '@src/core/domains/express/requests/responseError'; +import { App } from '@src/core/services/App'; +import { Request, Response } from 'express'; + +/** + * Logs in a user + * + * @param {Request} req - The request object + * @param {Response} res - The response object + * @returns {Promise} + */ +export default async (req: Request, res: Response): Promise => { + try { + // Get the email and password from the request body + const { email, password } = req?.body ?? {}; + + // Attempt to log in the user + const token = await App.container('auth').attemptCredentials(email, password); + + // Get the user from the database + const user = await App.container('auth').userRepository.findOneByEmail(email); + + // Send the user data and the token back to the client + res.send({ + success: true, + token, + user: user?.getData({ excludeGuarded: true }) + }) + } + catch (error) { + // Handle unauthorized errors + if (error instanceof unauthorizedError) { + res.status(401).send({ error: error.message },) + return; + } + + // Handle other errors + if (error instanceof Error) { + responseError(req, res, error) + } + } +} diff --git a/src/core/domains/Auth/actions/revoke.ts b/src/core/domains/auth/actions/revoke.ts similarity index 100% rename from src/core/domains/Auth/actions/revoke.ts rename to src/core/domains/auth/actions/revoke.ts diff --git a/src/core/domains/Auth/actions/update.ts b/src/core/domains/auth/actions/update.ts similarity index 100% rename from src/core/domains/Auth/actions/update.ts rename to src/core/domains/auth/actions/update.ts diff --git a/src/core/domains/Auth/actions/user.ts b/src/core/domains/auth/actions/user.ts similarity index 97% rename from src/core/domains/Auth/actions/user.ts rename to src/core/domains/auth/actions/user.ts index 9f8c4111d..7c014d094 100644 --- a/src/core/domains/Auth/actions/user.ts +++ b/src/core/domains/auth/actions/user.ts @@ -1,23 +1,23 @@ -import IAuthorizedRequest from '@src/core/domains/auth/interfaces/IAuthorizedRequest'; -import responseError from '@src/core/domains/express/requests/responseError'; -import { Response } from 'express'; - -/** - * Returns the currently logged in user - * - * @param {IAuthorizedRequest} req - The request object - * @param {Response} res - The response object - * @returns {Promise} - */ -export default (req: IAuthorizedRequest, res: Response) => { - try { - // Send the user data without the password - res.send({ success: true, user: req.user?.getData({ excludeGuarded: true }) }); - } - catch (error) { - // Handle any errors - if (error instanceof Error) { - responseError(req, res, error); - } - } -}; +import IAuthorizedRequest from '@src/core/domains/auth/interfaces/IAuthorizedRequest'; +import responseError from '@src/core/domains/express/requests/responseError'; +import { Response } from 'express'; + +/** + * Returns the currently logged in user + * + * @param {IAuthorizedRequest} req - The request object + * @param {Response} res - The response object + * @returns {Promise} + */ +export default (req: IAuthorizedRequest, res: Response) => { + try { + // Send the user data without the password + res.send({ success: true, user: req.user?.getData({ excludeGuarded: true }) }); + } + catch (error) { + // Handle any errors + if (error instanceof Error) { + responseError(req, res, error); + } + } +}; diff --git a/src/core/domains/Auth/commands/GenerateJWTSecret.ts b/src/core/domains/auth/commands/GenerateJWTSecret.ts similarity index 100% rename from src/core/domains/Auth/commands/GenerateJWTSecret.ts rename to src/core/domains/auth/commands/GenerateJWTSecret.ts diff --git a/src/core/domains/Auth/consts/authConsts.ts b/src/core/domains/auth/consts/authConsts.ts similarity index 94% rename from src/core/domains/Auth/consts/authConsts.ts rename to src/core/domains/auth/consts/authConsts.ts index 652116c5f..3903f38db 100644 --- a/src/core/domains/Auth/consts/authConsts.ts +++ b/src/core/domains/auth/consts/authConsts.ts @@ -1,38 +1,38 @@ -/** - * Constants for auth routes - */ -const authConsts = { - - /** - * Route for creating a new user - */ - routes: { - - /** - * Route for creating a new user - */ - authCreate: 'authCreate', - - /** - * Route for logging in - */ - authLogin: 'authLogin', - - /** - * Route for retrieving the current user - */ - authUser: 'authUser', - - /** - * Route for revoking a token - */ - authRevoke: 'authRevoke', - - /** - * Route for updating the current user - */ - authUpdate: 'authUpdate' - } -} - -export default authConsts +/** + * Constants for auth routes + */ +const authConsts = { + + /** + * Route for creating a new user + */ + routes: { + + /** + * Route for creating a new user + */ + authCreate: 'authCreate', + + /** + * Route for logging in + */ + authLogin: 'authLogin', + + /** + * Route for retrieving the current user + */ + authUser: 'authUser', + + /** + * Route for revoking a token + */ + authRevoke: 'authRevoke', + + /** + * Route for updating the current user + */ + authUpdate: 'authUpdate' + } +} + +export default authConsts diff --git a/src/core/domains/Auth/enums/RolesEnum.ts b/src/core/domains/auth/enums/RolesEnum.ts similarity index 94% rename from src/core/domains/Auth/enums/RolesEnum.ts rename to src/core/domains/auth/enums/RolesEnum.ts index bd5af65d2..13014fbb2 100644 --- a/src/core/domains/Auth/enums/RolesEnum.ts +++ b/src/core/domains/auth/enums/RolesEnum.ts @@ -1,6 +1,6 @@ -const roles = Object.freeze({ - USER: 'user', - ADMIN: 'admin' -}) - +const roles = Object.freeze({ + USER: 'user', + ADMIN: 'admin' +}) + export default roles \ No newline at end of file diff --git a/src/core/domains/Auth/exceptions/InvalidJWTSecret.ts b/src/core/domains/auth/exceptions/InvalidJWTSecret.ts similarity index 100% rename from src/core/domains/Auth/exceptions/InvalidJWTSecret.ts rename to src/core/domains/auth/exceptions/InvalidJWTSecret.ts diff --git a/src/core/domains/Auth/exceptions/UnauthorizedError.ts b/src/core/domains/auth/exceptions/UnauthorizedError.ts similarity index 97% rename from src/core/domains/Auth/exceptions/UnauthorizedError.ts rename to src/core/domains/auth/exceptions/UnauthorizedError.ts index 7e87b606d..7a66acaeb 100644 --- a/src/core/domains/Auth/exceptions/UnauthorizedError.ts +++ b/src/core/domains/auth/exceptions/UnauthorizedError.ts @@ -1,8 +1,8 @@ export default class UnauthorizedError extends Error { - - constructor(message: string = 'Unauthorized') { - super(message); - this.name = 'UnauthorizeError'; - } + + constructor(message: string = 'Unauthorized') { + super(message); + this.name = 'UnauthorizeError'; + } } \ No newline at end of file diff --git a/src/core/domains/Auth/factory/apiTokenFactory.ts b/src/core/domains/auth/factory/apiTokenFactory.ts similarity index 96% rename from src/core/domains/Auth/factory/apiTokenFactory.ts rename to src/core/domains/auth/factory/apiTokenFactory.ts index 5dfffef7e..62c67130f 100644 --- a/src/core/domains/Auth/factory/apiTokenFactory.ts +++ b/src/core/domains/auth/factory/apiTokenFactory.ts @@ -1,35 +1,35 @@ -import ApiToken from '@src/app/models/auth/ApiToken' -import Factory from '@src/core/base/Factory' -import IApiTokenModel, { IApiTokenData } from '@src/core/domains/auth/interfaces/IApitokenModel' -import IUserModel from '@src/core/domains/auth/interfaces/IUserModel' -import tokenFactory from '@src/core/domains/auth/utils/generateToken' - -/** - * Factory for creating ApiToken models. - * - * @class ApiTokenFactory - * @extends {Factory} - */ -class ApiTokenFactory extends Factory { - - constructor() { - super(ApiToken) - } - - /** - * Creates a new ApiToken model from the User - * - * @param {IUserModel} user - * @returns {IApiTokenModel} - */ - createFromUser(user: IUserModel): IApiTokenModel { - return new this.modelCtor({ - userId: user.data?.id, - token: tokenFactory(), - revokedAt: null, - }) - } - -} - -export default ApiTokenFactory +import ApiToken from '@src/app/models/auth/ApiToken' +import Factory from '@src/core/base/Factory' +import IApiTokenModel, { IApiTokenData } from '@src/core/domains/auth/interfaces/IApitokenModel' +import IUserModel from '@src/core/domains/auth/interfaces/IUserModel' +import tokenFactory from '@src/core/domains/auth/utils/generateToken' + +/** + * Factory for creating ApiToken models. + * + * @class ApiTokenFactory + * @extends {Factory} + */ +class ApiTokenFactory extends Factory { + + constructor() { + super(ApiToken) + } + + /** + * Creates a new ApiToken model from the User + * + * @param {IUserModel} user + * @returns {IApiTokenModel} + */ + createFromUser(user: IUserModel): IApiTokenModel { + return new this.modelCtor({ + userId: user.data?.id, + token: tokenFactory(), + revokedAt: null, + }) + } + +} + +export default ApiTokenFactory diff --git a/src/core/domains/Auth/factory/jwtTokenFactory.ts b/src/core/domains/auth/factory/jwtTokenFactory.ts similarity index 95% rename from src/core/domains/Auth/factory/jwtTokenFactory.ts rename to src/core/domains/auth/factory/jwtTokenFactory.ts index 116d2ccca..7743a7d17 100644 --- a/src/core/domains/Auth/factory/jwtTokenFactory.ts +++ b/src/core/domains/auth/factory/jwtTokenFactory.ts @@ -1,26 +1,26 @@ -import { IJSonWebToken } from "@src/core/domains/auth/interfaces/IJSonWebToken" - -/** - * Factory for creating JWT tokens. - * - * @class JWTTokenFactory - */ -export default class JWTTokenFactory { - - /** - * Creates a new JWT token from a user ID and token. - * - * @param {string} userId - The user ID. - * @param {string} token - The token. - * @returns {IJSonWebToken} A new JWT token. - */ - static create(userId: string, token: string): IJSonWebToken { - return { - uid: userId, - token - } - } - -} - - +import { IJSonWebToken } from "@src/core/domains/auth/interfaces/IJSonWebToken" + +/** + * Factory for creating JWT tokens. + * + * @class JWTTokenFactory + */ +export default class JWTTokenFactory { + + /** + * Creates a new JWT token from a user ID and token. + * + * @param {string} userId - The user ID. + * @param {string} token - The token. + * @returns {IJSonWebToken} A new JWT token. + */ + static create(userId: string, token: string): IJSonWebToken { + return { + uid: userId, + token + } + } + +} + + diff --git a/src/core/domains/Auth/factory/userFactory.ts b/src/core/domains/auth/factory/userFactory.ts similarity index 95% rename from src/core/domains/Auth/factory/userFactory.ts rename to src/core/domains/auth/factory/userFactory.ts index d9e5471a0..e91fed6b4 100644 --- a/src/core/domains/Auth/factory/userFactory.ts +++ b/src/core/domains/auth/factory/userFactory.ts @@ -1,22 +1,22 @@ -import User from '@src/app/models/auth/User'; -import Factory from '@src/core/base/Factory'; -import { IUserData } from '@src/core/domains/auth/interfaces/IUserModel'; - -/** - * Factory for creating User models. - * - * @class UserFactory - * @extends {Factory} - */ -export default class UserFactory extends Factory { - - /** - * Constructor - * - * @constructor - */ - constructor() { - super(User) - } - -} +import User from '@src/app/models/auth/User'; +import Factory from '@src/core/base/Factory'; +import { IUserData } from '@src/core/domains/auth/interfaces/IUserModel'; + +/** + * Factory for creating User models. + * + * @class UserFactory + * @extends {Factory} + */ +export default class UserFactory extends Factory { + + /** + * Constructor + * + * @constructor + */ + constructor() { + super(User) + } + +} diff --git a/src/core/domains/Auth/interfaces/IApiTokenRepository.ts b/src/core/domains/auth/interfaces/IApiTokenRepository.ts similarity index 100% rename from src/core/domains/Auth/interfaces/IApiTokenRepository.ts rename to src/core/domains/auth/interfaces/IApiTokenRepository.ts diff --git a/src/core/domains/Auth/interfaces/IApitokenModel.ts b/src/core/domains/auth/interfaces/IApitokenModel.ts similarity index 100% rename from src/core/domains/Auth/interfaces/IApitokenModel.ts rename to src/core/domains/auth/interfaces/IApitokenModel.ts diff --git a/src/core/domains/Auth/interfaces/IAuthConfig.ts b/src/core/domains/auth/interfaces/IAuthConfig.ts similarity index 97% rename from src/core/domains/Auth/interfaces/IAuthConfig.ts rename to src/core/domains/auth/interfaces/IAuthConfig.ts index af1bdd024..f0298e1b8 100644 --- a/src/core/domains/Auth/interfaces/IAuthConfig.ts +++ b/src/core/domains/auth/interfaces/IAuthConfig.ts @@ -1,30 +1,30 @@ -import IApiTokenModel from "@src/core/domains/auth/interfaces/IApitokenModel"; -import IApiTokenRepository from "@src/core/domains/auth/interfaces/IApiTokenRepository"; -import { IAuthService } from "@src/core/domains/auth/interfaces/IAuthService"; -import IUserModel from "@src/core/domains/auth/interfaces/IUserModel"; -import IUserRepository from "@src/core/domains/auth/interfaces/IUserRepository"; -import { IInterfaceCtor } from "@src/core/domains/validator/interfaces/IValidator"; -import { ModelConstructor } from "@src/core/interfaces/IModel"; -import { RepositoryConstructor } from "@src/core/interfaces/IRepository"; -import { ServiceConstructor } from "@src/core/interfaces/IService"; - -export interface IAuthConfig { - service: { - authService: ServiceConstructor; - }; - models: { - user: ModelConstructor; - apiToken: ModelConstructor; - }; - repositories: { - user: RepositoryConstructor; - apiToken: RepositoryConstructor; - }; - validators: { - createUser: IInterfaceCtor; - updateUser: IInterfaceCtor; - }; - jwtSecret: string, - enableAuthRoutes: boolean; - enableAuthRoutesAllowCreate: boolean; +import IApiTokenModel from "@src/core/domains/auth/interfaces/IApitokenModel"; +import IApiTokenRepository from "@src/core/domains/auth/interfaces/IApiTokenRepository"; +import { IAuthService } from "@src/core/domains/auth/interfaces/IAuthService"; +import IUserModel from "@src/core/domains/auth/interfaces/IUserModel"; +import IUserRepository from "@src/core/domains/auth/interfaces/IUserRepository"; +import { IInterfaceCtor } from "@src/core/domains/validator/interfaces/IValidator"; +import { ModelConstructor } from "@src/core/interfaces/IModel"; +import { RepositoryConstructor } from "@src/core/interfaces/IRepository"; +import { ServiceConstructor } from "@src/core/interfaces/IService"; + +export interface IAuthConfig { + service: { + authService: ServiceConstructor; + }; + models: { + user: ModelConstructor; + apiToken: ModelConstructor; + }; + repositories: { + user: RepositoryConstructor; + apiToken: RepositoryConstructor; + }; + validators: { + createUser: IInterfaceCtor; + updateUser: IInterfaceCtor; + }; + jwtSecret: string, + enableAuthRoutes: boolean; + enableAuthRoutesAllowCreate: boolean; } \ No newline at end of file diff --git a/src/core/domains/Auth/interfaces/IAuthService.ts b/src/core/domains/auth/interfaces/IAuthService.ts similarity index 96% rename from src/core/domains/Auth/interfaces/IAuthService.ts rename to src/core/domains/auth/interfaces/IAuthService.ts index 76096e44b..694d4392f 100644 --- a/src/core/domains/Auth/interfaces/IAuthService.ts +++ b/src/core/domains/auth/interfaces/IAuthService.ts @@ -1,105 +1,105 @@ -/* eslint-disable no-unused-vars */ -import IApiTokenModel from "@src/core/domains/auth/interfaces/IApitokenModel"; -import IApiTokenRepository from "@src/core/domains/auth/interfaces/IApiTokenRepository"; -import IUserModel from "@src/core/domains/auth/interfaces/IUserModel"; -import IUserRepository from "@src/core/domains/auth/interfaces/IUserRepository"; -import { IRoute } from "@src/core/domains/express/interfaces/IRoute"; -import IService from "@src/core/interfaces/IService"; - - -/** - * The service that handles authentication. - * - * @export - * @interface IAuthService - * @extends {IService} - */ -export interface IAuthService extends IService { - - /** - * The auth config - * - * @type {any} - * @memberof IAuthService - */ - config: any; - - /** - * The user repository - * - * @type {IUserRepository} - * @memberof IAuthService - */ - userRepository: IUserRepository; - - /** - * The api token repository - * - * @type {IApiTokenRepository} - * @memberof IAuthService - */ - apiTokenRepository: IApiTokenRepository; - - /** - * Attempt to authenticate a user using a JWT token. - * - * @param {string} token The JWT token - * @returns {Promise} The authenticated user, or null if not authenticated - * @memberof IAuthService - */ - attemptAuthenticateToken: (token: string) => Promise; - - /** - * Creates a JWT for the user. - * - * @param {IUserModel} user The user - * @returns {Promise} The JWT token - * @memberof IAuthService - */ - createJwtFromUser: (user: IUserModel) => Promise; - - /** - * Creates a new ApiToken model from the User - * - * @param {IUserModel} user The user - * @returns {Promise} The new ApiToken model - * @memberof IAuthService - */ - createApiTokenFromUser: (user: IUserModel) => Promise; - - /** - * Revokes a token. - * - * @param {IApiTokenModel} apiToken The ApiToken model - * @returns {Promise} - * @memberof IAuthService - */ - revokeToken: (apiToken: IApiTokenModel) => Promise; - - /** - * Attempt to authenticate a user using their credentials. - * - * @param {string} email The user's email - * @param {string} password The user's password - * @returns {Promise} The JWT token - * @memberof IAuthService - */ - attemptCredentials: (email: string, password: string) => Promise; - - /** - * Generates a JWT. - * - * @param {IApiTokenModel} apiToken The ApiToken model - * @returns {string} The JWT token - * @memberof IAuthService - */ - jwt: (apiToken: IApiTokenModel) => string; - - /** - * Returns the auth routes. - * - * @returns {IRoute[] | null} An array of routes, or null if auth routes are disabled - * @memberof IAuthService - */ - getAuthRoutes(): IRoute[] | null; -} +/* eslint-disable no-unused-vars */ +import IApiTokenModel from "@src/core/domains/auth/interfaces/IApitokenModel"; +import IApiTokenRepository from "@src/core/domains/auth/interfaces/IApiTokenRepository"; +import IUserModel from "@src/core/domains/auth/interfaces/IUserModel"; +import IUserRepository from "@src/core/domains/auth/interfaces/IUserRepository"; +import { IRoute } from "@src/core/domains/express/interfaces/IRoute"; +import IService from "@src/core/interfaces/IService"; + + +/** + * The service that handles authentication. + * + * @export + * @interface IAuthService + * @extends {IService} + */ +export interface IAuthService extends IService { + + /** + * The auth config + * + * @type {any} + * @memberof IAuthService + */ + config: any; + + /** + * The user repository + * + * @type {IUserRepository} + * @memberof IAuthService + */ + userRepository: IUserRepository; + + /** + * The api token repository + * + * @type {IApiTokenRepository} + * @memberof IAuthService + */ + apiTokenRepository: IApiTokenRepository; + + /** + * Attempt to authenticate a user using a JWT token. + * + * @param {string} token The JWT token + * @returns {Promise} The authenticated user, or null if not authenticated + * @memberof IAuthService + */ + attemptAuthenticateToken: (token: string) => Promise; + + /** + * Creates a JWT for the user. + * + * @param {IUserModel} user The user + * @returns {Promise} The JWT token + * @memberof IAuthService + */ + createJwtFromUser: (user: IUserModel) => Promise; + + /** + * Creates a new ApiToken model from the User + * + * @param {IUserModel} user The user + * @returns {Promise} The new ApiToken model + * @memberof IAuthService + */ + createApiTokenFromUser: (user: IUserModel) => Promise; + + /** + * Revokes a token. + * + * @param {IApiTokenModel} apiToken The ApiToken model + * @returns {Promise} + * @memberof IAuthService + */ + revokeToken: (apiToken: IApiTokenModel) => Promise; + + /** + * Attempt to authenticate a user using their credentials. + * + * @param {string} email The user's email + * @param {string} password The user's password + * @returns {Promise} The JWT token + * @memberof IAuthService + */ + attemptCredentials: (email: string, password: string) => Promise; + + /** + * Generates a JWT. + * + * @param {IApiTokenModel} apiToken The ApiToken model + * @returns {string} The JWT token + * @memberof IAuthService + */ + jwt: (apiToken: IApiTokenModel) => string; + + /** + * Returns the auth routes. + * + * @returns {IRoute[] | null} An array of routes, or null if auth routes are disabled + * @memberof IAuthService + */ + getAuthRoutes(): IRoute[] | null; +} diff --git a/src/core/domains/Auth/interfaces/IAuthorizedRequest.ts b/src/core/domains/auth/interfaces/IAuthorizedRequest.ts similarity index 97% rename from src/core/domains/Auth/interfaces/IAuthorizedRequest.ts rename to src/core/domains/auth/interfaces/IAuthorizedRequest.ts index 4c33d3cd0..c437fcc99 100644 --- a/src/core/domains/Auth/interfaces/IAuthorizedRequest.ts +++ b/src/core/domains/auth/interfaces/IAuthorizedRequest.ts @@ -1,8 +1,8 @@ -import IApiTokenModel from '@src/core/domains/auth/interfaces/IApitokenModel'; -import IUserModel from '@src/core/domains/auth/interfaces/IUserModel'; -import { Request } from 'express'; - -export default interface IAuthorizedRequest extends Request { - user?: IUserModel | null; - apiToken?: IApiTokenModel | null; +import IApiTokenModel from '@src/core/domains/auth/interfaces/IApitokenModel'; +import IUserModel from '@src/core/domains/auth/interfaces/IUserModel'; +import { Request } from 'express'; + +export default interface IAuthorizedRequest extends Request { + user?: IUserModel | null; + apiToken?: IApiTokenModel | null; } \ No newline at end of file diff --git a/src/core/domains/Auth/interfaces/IJSonWebToken.ts b/src/core/domains/auth/interfaces/IJSonWebToken.ts similarity index 100% rename from src/core/domains/Auth/interfaces/IJSonWebToken.ts rename to src/core/domains/auth/interfaces/IJSonWebToken.ts diff --git a/src/core/domains/Auth/interfaces/IUserModel.ts b/src/core/domains/auth/interfaces/IUserModel.ts similarity index 100% rename from src/core/domains/Auth/interfaces/IUserModel.ts rename to src/core/domains/auth/interfaces/IUserModel.ts diff --git a/src/core/domains/Auth/interfaces/IUserRepository.ts b/src/core/domains/auth/interfaces/IUserRepository.ts similarity index 100% rename from src/core/domains/Auth/interfaces/IUserRepository.ts rename to src/core/domains/auth/interfaces/IUserRepository.ts diff --git a/src/core/domains/Auth/providers/AuthProvider.ts b/src/core/domains/auth/providers/AuthProvider.ts similarity index 100% rename from src/core/domains/Auth/providers/AuthProvider.ts rename to src/core/domains/auth/providers/AuthProvider.ts diff --git a/src/core/domains/Auth/routes/auth.ts b/src/core/domains/auth/routes/auth.ts similarity index 97% rename from src/core/domains/Auth/routes/auth.ts rename to src/core/domains/auth/routes/auth.ts index 7a1922e3d..fbda9c686 100644 --- a/src/core/domains/Auth/routes/auth.ts +++ b/src/core/domains/auth/routes/auth.ts @@ -1,55 +1,55 @@ -import create from "@src/core/domains/auth/actions/create"; -import login from "@src/core/domains/auth/actions/login"; -import revoke from "@src/core/domains/auth/actions/revoke"; -import update from "@src/core/domains/auth/actions/update"; -import user from "@src/core/domains/auth/actions/user"; -import authConsts from "@src/core/domains/auth/consts/authConsts"; -import { IAuthConfig } from "@src/core/domains/auth/interfaces/IAuthConfig"; -import { IRoute } from "@src/core/domains/express/interfaces/IRoute"; -import { authorize } from "@src/core/domains/express/middleware/authorize"; -import Route from "@src/core/domains/express/routing/Route"; -import RouteGroup from "@src/core/domains/express/routing/RouteGroup"; - -export const routes = (config: IAuthConfig): IRoute[] => { - return RouteGroup([ - Route({ - name: authConsts.routes.authLogin, - method: 'post', - path: '/auth/login', - action: login - }), - Route({ - name: authConsts.routes.authCreate, - method: 'post', - path: '/auth/create', - action: create, - validator: config.validators.createUser, - validateBeforeAction: true - }), - Route({ - name: authConsts.routes.authUpdate, - method: 'patch', - path: '/auth/user', - action: update, - middlewares: [authorize()], - validator: config.validators.updateUser, - validateBeforeAction: true - }), - Route({ - name: authConsts.routes.authUser, - method: 'get', - path: '/auth/user', - action: user, - middlewares: [authorize()] - }), - Route({ - name: authConsts.routes.authRevoke, - method: 'post', - path: '/auth/revoke', - action: revoke, - middlewares: [authorize()] - }) - ]) -} - +import create from "@src/core/domains/auth/actions/create"; +import login from "@src/core/domains/auth/actions/login"; +import revoke from "@src/core/domains/auth/actions/revoke"; +import update from "@src/core/domains/auth/actions/update"; +import user from "@src/core/domains/auth/actions/user"; +import authConsts from "@src/core/domains/auth/consts/authConsts"; +import { IAuthConfig } from "@src/core/domains/auth/interfaces/IAuthConfig"; +import { IRoute } from "@src/core/domains/express/interfaces/IRoute"; +import { authorize } from "@src/core/domains/express/middleware/authorize"; +import Route from "@src/core/domains/express/routing/Route"; +import RouteGroup from "@src/core/domains/express/routing/RouteGroup"; + +export const routes = (config: IAuthConfig): IRoute[] => { + return RouteGroup([ + Route({ + name: authConsts.routes.authLogin, + method: 'post', + path: '/auth/login', + action: login + }), + Route({ + name: authConsts.routes.authCreate, + method: 'post', + path: '/auth/create', + action: create, + validator: config.validators.createUser, + validateBeforeAction: true + }), + Route({ + name: authConsts.routes.authUpdate, + method: 'patch', + path: '/auth/user', + action: update, + middlewares: [authorize()], + validator: config.validators.updateUser, + validateBeforeAction: true + }), + Route({ + name: authConsts.routes.authUser, + method: 'get', + path: '/auth/user', + action: user, + middlewares: [authorize()] + }), + Route({ + name: authConsts.routes.authRevoke, + method: 'post', + path: '/auth/revoke', + action: revoke, + middlewares: [authorize()] + }) + ]) +} + export default routes; \ No newline at end of file diff --git a/src/core/domains/Auth/services/AuthService.ts b/src/core/domains/auth/services/AuthService.ts similarity index 100% rename from src/core/domains/Auth/services/AuthService.ts rename to src/core/domains/auth/services/AuthService.ts diff --git a/src/core/domains/Auth/utils/comparePassword.ts b/src/core/domains/auth/utils/comparePassword.ts similarity index 97% rename from src/core/domains/Auth/utils/comparePassword.ts rename to src/core/domains/auth/utils/comparePassword.ts index 88555294f..1ab592d2a 100644 --- a/src/core/domains/Auth/utils/comparePassword.ts +++ b/src/core/domains/auth/utils/comparePassword.ts @@ -1,10 +1,10 @@ -import bcrypt from 'bcryptjs' - -/** - * Compares a plain text password with a hashed password. - * - * @param password The plain text password - * @param hashedPassword The hashed password - * @returns true if the password matches the hashed password, false otherwise - */ -export default (password: string, hashedPassword: string): boolean => bcrypt.compareSync(password, hashedPassword) +import bcrypt from 'bcryptjs' + +/** + * Compares a plain text password with a hashed password. + * + * @param password The plain text password + * @param hashedPassword The hashed password + * @returns true if the password matches the hashed password, false otherwise + */ +export default (password: string, hashedPassword: string): boolean => bcrypt.compareSync(password, hashedPassword) diff --git a/src/core/domains/Auth/utils/createJwt.ts b/src/core/domains/auth/utils/createJwt.ts similarity index 97% rename from src/core/domains/Auth/utils/createJwt.ts rename to src/core/domains/auth/utils/createJwt.ts index a472075a3..09fb5d503 100644 --- a/src/core/domains/Auth/utils/createJwt.ts +++ b/src/core/domains/auth/utils/createJwt.ts @@ -1,12 +1,12 @@ -import jwt from 'jsonwebtoken' - -/** - * Creates a JWT token - * @param secret The secret to sign the token with - * @param data The data to be stored in the token - * @param expiresIn The time until the token expires (default is 1 hour) - * @returns The created JWT token as a string - */ -export default (secret: string, data: object, expiresIn: string = '1h'): string => { - return jwt.sign(data, secret, { expiresIn }) -} +import jwt from 'jsonwebtoken' + +/** + * Creates a JWT token + * @param secret The secret to sign the token with + * @param data The data to be stored in the token + * @param expiresIn The time until the token expires (default is 1 hour) + * @returns The created JWT token as a string + */ +export default (secret: string, data: object, expiresIn: string = '1h'): string => { + return jwt.sign(data, secret, { expiresIn }) +} diff --git a/src/core/domains/Auth/utils/decodeJwt.ts b/src/core/domains/auth/utils/decodeJwt.ts similarity index 97% rename from src/core/domains/Auth/utils/decodeJwt.ts rename to src/core/domains/auth/utils/decodeJwt.ts index 62a09881b..58b07a377 100644 --- a/src/core/domains/Auth/utils/decodeJwt.ts +++ b/src/core/domains/auth/utils/decodeJwt.ts @@ -1,13 +1,13 @@ -import { IJSonWebToken } from '@src/core/domains/auth/interfaces/IJSonWebToken' -import jwt from 'jsonwebtoken' - -/** - * Decodes a JWT token using the provided secret. - * - * @param {string} secret - The secret to use to decode the token. - * @param {string} token - The JWT token to decode. - * @returns {IJSonWebToken} The decoded token. - */ -export default (secret: string, token: string): IJSonWebToken => { - return jwt.verify(token, secret) as IJSonWebToken -} +import { IJSonWebToken } from '@src/core/domains/auth/interfaces/IJSonWebToken' +import jwt from 'jsonwebtoken' + +/** + * Decodes a JWT token using the provided secret. + * + * @param {string} secret - The secret to use to decode the token. + * @param {string} token - The JWT token to decode. + * @returns {IJSonWebToken} The decoded token. + */ +export default (secret: string, token: string): IJSonWebToken => { + return jwt.verify(token, secret) as IJSonWebToken +} diff --git a/src/core/domains/Auth/utils/generateToken.ts b/src/core/domains/auth/utils/generateToken.ts similarity index 98% rename from src/core/domains/Auth/utils/generateToken.ts rename to src/core/domains/auth/utils/generateToken.ts index 9a52a1c84..846bb7edd 100644 --- a/src/core/domains/Auth/utils/generateToken.ts +++ b/src/core/domains/auth/utils/generateToken.ts @@ -1,9 +1,9 @@ -import crypto, { BinaryToTextEncoding } from 'crypto' - -/** - * Generates a random token of the given size (in bytes) and encoding. - * @param {number} [size=64] The size of the token in bytes. - * @param {BinaryToTextEncoding} [bufferEncoding='hex'] The encoding to use when converting the buffer to a string. - * @returns {string} A random token as a string. - */ -export default (size: number = 64, bufferEncoding: BinaryToTextEncoding = 'hex'): string => crypto.randomBytes(size).toString(bufferEncoding) +import crypto, { BinaryToTextEncoding } from 'crypto' + +/** + * Generates a random token of the given size (in bytes) and encoding. + * @param {number} [size=64] The size of the token in bytes. + * @param {BinaryToTextEncoding} [bufferEncoding='hex'] The encoding to use when converting the buffer to a string. + * @returns {string} A random token as a string. + */ +export default (size: number = 64, bufferEncoding: BinaryToTextEncoding = 'hex'): string => crypto.randomBytes(size).toString(bufferEncoding) diff --git a/src/core/domains/Auth/utils/hashPassword.ts b/src/core/domains/auth/utils/hashPassword.ts similarity index 97% rename from src/core/domains/Auth/utils/hashPassword.ts rename to src/core/domains/auth/utils/hashPassword.ts index 0959356c3..201c5195f 100644 --- a/src/core/domains/Auth/utils/hashPassword.ts +++ b/src/core/domains/auth/utils/hashPassword.ts @@ -1,10 +1,10 @@ -import bcryptjs from 'bcryptjs' - -/** - * Hashes a password using bcryptjs with a given salt (default is 10) - * @param password The password to hash - * @param salt The salt to use for hashing (optional, default is 10) - * @returns The hashed password - */ -export default (password: string, salt: number = 10): string => bcryptjs.hashSync(password, salt) - +import bcryptjs from 'bcryptjs' + +/** + * Hashes a password using bcryptjs with a given salt (default is 10) + * @param password The password to hash + * @param salt The salt to use for hashing (optional, default is 10) + * @returns The hashed password + */ +export default (password: string, salt: number = 10): string => bcryptjs.hashSync(password, salt) +