- Notifications
You must be signed in to change notification settings - Fork 13
Deposit flow #17
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
Deposit flow #17
Conversation
Instantiate objects globally only when necessary, Move all http requests into httpService, Delete console.logs
Transcribir PlayersController.create
Validate index params, Move authorization logic into DAO
Fixes/http n token services
Add bank accounts CRUD
…ransferResponse, Return deposit object from TransactionsController.deposit(), Avoid double payment verifications with dirty flag, Delay response in verifyPayment(), Merge /deposit and /deposit/:id/conifirm endpoints
Refactor FinanceServices deposit() and confirmDeposit()
Replace sender_balance and recipient_balance with player_balance on T…
Agent endpoints
Add JWT-based authentication with refresh token rotation
GET /players/id, Deposit, Cashout
Alpha dev87 readme
Agent bank account
Add endpoints to complete pending coin transfers
WalkthroughThe project underwent significant updates, transitioning from "TEN stack" to "Timba Api" with enhancements across the board. Modifications include the introduction of new environment variables, updates to database schema through Prisma migrations, and expanded functionality in various components like authentication, bank accounts, and web push notifications. The codebase improvements also encompass error handling, agent operations, and a WhatsApp bot integration, aiming to refine the API's robustness and feature set. Changes
Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media? TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (invoked as PR comments)
Additionally, you can add CodeRabbit Configration File ( |
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.
Review Status
Actionable comments generated: 59
Configuration used: CodeRabbit UI
Files ignored due to path filters (6)
bot.qr.pngis excluded by:!**/*.pngdocker-compose.ymlis excluded by:!**/*.ymlpackage-lock.jsonis excluded by:!**/*.jsonpackage.jsonis excluded by:!**/*.jsonprisma/migrations/migration_lock.tomlis excluded by:!**/*.tomlyarn.lockis excluded by:!**/*.lock
Files selected for processing (94)
- .env.example (2 hunks)
- .gitignore (2 hunks)
- .vscode/settings.json (1 hunks)
- README.md (2 hunks)
- ecosystem.config.js (2 hunks)
- prisma/migrations/20240220155527_initial_migration/migration.sql (1 hunks)
- prisma/migrations/20240222132000_drop_bank_accounts/migration.sql (1 hunks)
- prisma/migrations/20240222133838_drop_bank_account_indexes/migration.sql (1 hunks)
- prisma/migrations/20240222133915_add_bank_accounts/migration.sql (1 hunks)
- prisma/migrations/20240222140003_add_player_and_owner_to_bank_account/migration.sql (1 hunks)
- prisma/migrations/20240222140931_make_bank_alias_nullable/migration.sql (1 hunks)
- prisma/migrations/20240222203552_replace_panel_id_foreign_key_with_id/migration.sql (1 hunks)
- prisma/migrations/20240223113516_make_user_root_id_int/migration.sql (1 hunks)
- prisma/migrations/20240223184220_add_currency_to_deposits/migration.sql (1 hunks)
- prisma/migrations/20240223185921_add_currency_to_payments/migration.sql (1 hunks)
- prisma/migrations/20240226180926_add_dirty_flag_to_deposits/migration.sql (1 hunks)
- prisma/migrations/20240227170435_add_bank_account_to_user_root/migration.sql (1 hunks)
- prisma/migrations/20240228123536_add_tokens_table/migration.sql (1 hunks)
- prisma/migrations/20240304132411_add_coins_transfered_to_deposits/migration.sql (1 hunks)
- prisma/migrations/20240304210104_create_web_push_subscriptions_table/migration.sql (1 hunks)
- prisma/migrations/20240304214515_stretch_endpoint_and_add_exp_time_to_push_subscriptions/migration.sql (1 hunks)
- prisma/migrations/20240305132627_add_timestamps_to_token_and_pushsub/migration.sql (1 hunks)
- prisma/schema.prisma (1 hunks)
- seed.sql (1 hunks)
- src/app.ts (2 hunks)
- src/components/agent/controller.ts (1 hunks)
- src/components/agent/index.ts (1 hunks)
- src/components/agent/services.ts (1 hunks)
- src/components/agent/validators.ts (1 hunks)
- src/components/auth/controller.ts (1 hunks)
- src/components/auth/services.ts (1 hunks)
- src/components/bank-accounts/controller.ts (1 hunks)
- src/components/bank-accounts/index.ts (1 hunks)
- src/components/bank-accounts/services.ts (1 hunks)
- src/components/bank-accounts/validators.ts (1 hunks)
- src/components/players/controller.ts (1 hunks)
- src/components/players/index.ts (1 hunks)
- src/components/players/services.ts (1 hunks)
- src/components/players/validators.ts (1 hunks)
- src/components/transactions/controller.ts (1 hunks)
- src/components/transactions/index.ts (1 hunks)
- src/components/transactions/services.ts (1 hunks)
- src/components/transactions/validators.ts (1 hunks)
- src/components/web-push/controller.ts (1 hunks)
- src/components/web-push/services.ts (1 hunks)
- src/components/web-push/validators.ts (1 hunks)
- src/config/index.ts (3 hunks)
- src/db/agent.ts (1 hunks)
- src/db/bank-accounts.ts (1 hunks)
- src/db/deposits.ts (1 hunks)
- src/db/payments.ts (1 hunks)
- src/db/players.ts (1 hunks)
- src/db/token.ts (1 hunks)
- src/db/transactions.ts (1 hunks)
- src/db/user-root.ts (1 hunks)
- src/db/web-push.ts (1 hunks)
- src/helpers/apiResponse.ts (1 hunks)
- src/helpers/loggers.ts (3 hunks)
- src/helpers/notification.ts (1 hunks)
- src/index.ts (1 hunks)
- src/middlewares/auth.ts (1 hunks)
- src/middlewares/errorHandler.ts (2 hunks)
- src/middlewares/requestErrorHandler.ts (1 hunks)
- src/routes/agent.router.ts (1 hunks)
- src/routes/auth.router.ts (1 hunks)
- src/routes/bank-accounts.router.ts (1 hunks)
- src/routes/home.router.ts (1 hunks)
- src/routes/index.ts (1 hunks)
- src/routes/players.router.ts (1 hunks)
- src/routes/transactions.router.ts (1 hunks)
- src/routes/web-push.ts (1 hunks)
- src/server.ts (2 hunks)
- src/services/http.service.ts (1 hunks)
- src/services/jwt.service.ts (1 hunks)
- src/services/token.service.ts (1 hunks)
- src/types/bot/bot-whatsapp-database-baileys.d.ts (1 hunks)
- src/types/bot/bot-whatsapp-provider-mock.d.ts (1 hunks)
- src/types/bot/bot-whatsapp.d.ts (1 hunks)
- src/types/global.d.ts (2 hunks)
- src/types/request/bank-account.ts (1 hunks)
- src/types/request/players.ts (1 hunks)
- src/types/request/token.ts (1 hunks)
- src/types/request/transfers.ts (1 hunks)
- src/types/request/user-root.ts (1 hunks)
- src/types/request/web-push.ts (1 hunks)
- src/types/response/agent.ts (1 hunks)
- src/types/response/bankAccount.ts (1 hunks)
- src/types/response/jwt.ts (1 hunks)
- src/types/response/players.ts (1 hunks)
- src/types/response/transactions.ts (1 hunks)
- src/types/response/transfers.ts (1 hunks)
- src/utils/auth.ts (1 hunks)
- src/utils/crypt.ts (2 hunks)
- src/utils/parser.ts (1 hunks)
Files not reviewed due to errors (6)
- (no review received)
- (no review received)
- (no review received)
- (no review received)
- (no review received)
- (no review received)
Files skipped from review due to trivial changes (7)
- src/components/agent/index.ts
- src/components/bank-accounts/index.ts
- src/components/players/index.ts
- src/components/transactions/index.ts
- src/types/bot/bot-whatsapp-provider-mock.d.ts
- src/types/request/token.ts
- src/types/response/transactions.ts
Additional comments: 104
src/types/bot/bot-whatsapp-database-baileys.d.ts (1)
- 1-1: Declaring the module
@bot-whatsapp/provider/baileysis a good practice for ensuring type safety and enhancing developer experience with IntelliSense. Ensure that these type definitions are kept up-to-date with the actual implementation of the package.prisma/migrations/20240226180926_add_dirty_flag_to_deposits/migration.sql (1)
- 1-2: Adding a
dirtyBOOLEAN column to theDEPOSITStable with a default value of true is a good practice for tracking records that require further processing or verification. Ensure that the default value aligns with the intended workflow, where new deposit records are considered "dirty" until processed.prisma/migrations/20240223184220_add_currency_to_deposits/migration.sql (1)
- 1-2: Adding a
currencycolumn to theDEPOSITStable with a default value of 'MXN' is a crucial update for handling financial transactions in multiple currencies. Ensure that the default currency aligns with the primary currency of the application's user base or the most common transaction currency.prisma/migrations/20240223185921_add_currency_to_payments/migration.sql (1)
- 1-2: Adding a
currencycolumn to thePAYMENTStable with a default value of 'MXN' mirrors the update made to theDEPOSITStable, ensuring consistency in handling financial transactions across the application. This consistency is crucial for a coherent financial management system.src/types/response/transfers.ts (1)
- 1-5: The
TransferResulttype is well-structured for representing the outcomes of transfer operations, including success, incomplete status, and potential errors. Ensure that error handling is comprehensive and consider documenting possible values for theerrorfield to aid in debugging and consumer understanding.prisma/migrations/20240304214515_stretch_endpoint_and_add_exp_time_to_push_subscriptions/migration.sql (1)
- 1-3: Modifying the
WEB_PUSH_SUBSCRIPTIONStable to add anexpirationTimecolumn and extend theendpointcolumn size to VARCHAR(512) are sensible updates for managing the lifecycle of web push subscriptions and accommodating longer endpoint URLs. Ensure that the application logic properly handles the expiration of subscriptions.src/routes/auth.router.ts (1)
- 1-8: Setting up the authentication router with a POST route for token refreshing is a good practice for maintaining secure user sessions. Ensure that the token refresh mechanism is secure, well-documented, and tested to prevent potential security vulnerabilities.
src/middlewares/requestErrorHandler.ts (1)
- 1-8: The
throwIfBadRequestmiddleware function is correctly implemented for handling request validation errors. However, the parametersReq,Res, andNextFnare used without being explicitly imported or defined. Ensure that these types are correctly imported from Express or defined elsewhere in the codebase to avoid potential type errors.Verification successful
The verification process has confirmed that the types
Req,Res, andNextFnare indeed defined in the codebase withinsrc/types/global.d.ts, where they are aliased toRequest,Response, andNextFunctionfrom theexpresspackage, respectively. This directly addresses the concern raised in the review comment about ensuring these types are correctly imported or defined to avoid potential type errors. Therefore, the original comment's concern has been addressed by the presence of these type definitions.Scripts Executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Verify if Req, Res, and NextFn types are defined or imported rg --type ts "import .* from 'express'"Length of output: 47
Script:
#!/bin/bash # Broaden the search for Req, Res, and NextFn types across the codebase rg --type ts "type Req |type Res |type NextFn"Length of output: 189
Script:
#!/bin/bash # Additionally, search for any import or export statements that might include these types rg --type ts "import .*\(Req|Res|NextFn\).*"Length of output: 11744
prisma/migrations/20240228123536_add_tokens_table/migration.sql (1)
- 1-12: The migration script correctly creates the
TOKENStable with appropriate fields and establishes a foreign key relationship with thePLAYERStable. Ensure that theplayer_idcolumn in thePLAYERStable is of typeINTEGERand that there are appropriate indexes on theplayer_idcolumn for performance optimization, especially if thePLAYERStable is expected to grow significantly.prisma/migrations/20240223113516_make_user_root_id_int/migration.sql (1)
- 1-11: The migration script for altering the
USERS_ROOTtable's primary key fromVarChar(191)toINTEGERand setting it to auto-increment is correctly implemented. However, the warnings about potential data loss and the removal of the primary key constraint during the operation are significant. Ensure that this migration is thoroughly tested in a staging environment and that there's a backup of theUSERS_ROOTtable before applying this change in production.prisma/migrations/20240222132000_drop_bank_accounts/migration.sql (1)
- 1-17: The migration script for dropping the
BANK_ACCOUNTStable and its related foreign keys is correctly structured. Dropping a table is a significant operation, especially if it contains data. Ensure that the decision to remove theBANK_ACCOUNTStable is well-justified and that any necessary data migrations or backups have been performed prior to executing this script.src/types/request/user-root.ts (1)
- 1-22: The interfaces
RootUpdatablePropsandRootRequestare well-defined, covering various properties that can be updated or required in a request. However, it's important to ensure that sensitive information such aspasswordis handled securely throughout the application, especially when updating or transmitting such data. Consider implementing additional security measures, such as hashing passwords before storing them in the database.src/components/auth/controller.ts (1)
- 6-17: The
refreshmethod in theAuthControllerclass is correctly implemented to handle token refreshing. It uses theAuthServiceto refresh the token and sends the response using theapiResponsehelper function. Ensure that error handling is robust, especially for cases where the token might be invalid or expired. The current implementation correctly forwards errors to the next middleware, which is good practice.prisma/migrations/20240222133838_drop_bank_account_indexes/migration.sql (1)
- 1-18: The migration script for dropping indexes and columns related to bank accounts in the
DEPOSITSandPAYMENTStables is correctly structured. This change appears to be part of a larger restructuring of how financial transactions are handled in the application. Ensure that the removal of these columns and indexes does not adversely affect the application's functionality or data integrity. It's also important to verify that any necessary data migrations have been performed prior to executing this script.src/types/global.d.ts (1)
- 12-25: > 📝 NOTE
This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [1-24]
The changes to global type definitions, including the introduction of
AuthedReqand the extension of theExpress.Userinterface, are well-implemented and align with the objectives of enhancing authentication and user management within the application.prisma/migrations/20240305132627_add_timestamps_to_token_and_pushsub/migration.sql (1)
- 8-14: The addition of
created_atandupdated_atcolumns to theTOKENSandWEB_PUSH_SUBSCRIPTIONStables is correctly implemented, with appropriate default values forcreated_at. Ensure that the application logic appropriately manages theupdated_atcolumn to reflect the last modification time accurately.src/routes/index.ts (1)
- 2-20: The refactoring of the main router to use separate routers for different endpoints is a significant improvement, enhancing modularity and organization within the application's routing system.
prisma/migrations/20240222203552_replace_panel_id_foreign_key_with_id/migration.sql (1)
- 1-20: The migration script correctly handles the replacement of foreign key constraints and the management of indexes for
BANK_ACCOUNTS,DEPOSITS, andPAYMENTStables. These changes are necessary for maintaining referential integrity and align with the database schema evolution..vscode/settings.json (1)
- 2-22: The adjustments to VSCode settings, including sticky scroll and color customizations for various UI elements, are correctly implemented and enhance the visual aspects of the development environment. These changes are subjective and do not impact the application's functionality or code quality.
src/routes/web-push.ts (4)
- 14-16: Ensure that the JWT authentication middleware is correctly configured for your application's security requirements. The
session: falseandfailWithError: trueoptions are typically used for stateless API authentication, which is appropriate for most REST APIs.- 17-17: The use of
requireAgentRolemiddleware after JWT authentication ensures that only users with the agent role can access the web push routes. This is a good practice for role-based access control (RBAC).- 19-25: The POST route for
/subscriptioncorrectly chains middleware for validation (validatePushSubscriptionRequest()), exact check (checkExact()), error handling (throwIfBadRequest), and finally calls the controller method (WebPushController.create). This is a well-structured approach to handling requests and validating input data.- 26-26: The DELETE route for subscriptions does not specify a resource identifier in the URL, which means it operates on a collection rather than a specific resource. Ensure that the implementation of
WebPushController.deleteandvalidateDeleteRequest()correctly handles this scenario, possibly by using request body or query parameters to identify the subscription to delete.src/components/agent/validators.ts (1)
- 28-47: The
validateBankAccountUpdatemiddleware uses a well-structured approach to define optional string validation rules for various bank account fields. This approach promotes code reuse and readability. Ensure that all fields that can be updated are included and correctly validated.ecosystem.config.js (2)
- 4-4: Changing the application name to
timba-apiin the PM2 configuration aligns with the project's rebranding efforts. This is a straightforward change that helps maintain consistency across the project.- 22-22: Dynamically setting the port using
process.env.PORTin theenv_productionconfiguration is a best practice for cloud deployments, as it allows the port to be configured through the environment rather than being hardcoded. This change enhances the flexibility and portability of the application deployment.src/routes/transactions.router.ts (3)
- 11-13: The use of JWT authentication middleware with
session: falseandfailWithError: trueoptions is correctly applied for stateless API authentication. This ensures that only authenticated users can access the transaction routes.- 14-14: Applying
requireUserRolemiddleware after JWT authentication ensures that only users with specific roles can access the transaction routes. This is a good practice for implementing role-based access control (RBAC) in the application.- 15-21: The POST route for
/deposit/:id?correctly chains middleware for validation (validateTransferRequest()), exact check (checkExact()), error handling (throwIfBadRequest), and finally calls the controller method (TransactionsController.deposit). This structured approach is commendable for handling requests and validating input data.src/routes/players.router.ts (3)
- 14-21: The POST route for creating players correctly chains middleware for validation (
validatePlayerRequest()), exact check (checkExact()), error handling (throwIfBadRequest), and finally calls the controller method (PlayersController.create). This is a well-structured approach to handling requests and validating input data.- 23-29: The POST route for player login correctly uses
validateCredentials()middleware for input validation, followed bycheckExact(),throwIfBadRequest, and the controller method (PlayersController.login). This ensures that login requests are properly validated and handled.- 30-32: The use of JWT authentication middleware for routes that require user authentication is correctly configured. This ensures that only authenticated players can access certain player routes.
src/components/web-push/controller.ts (1)
- 6-44: The
WebPushControllerclass methods (index,create,delete) are well-implemented, with clear separation of concerns and appropriate error handling. Each method uses atry-catchblock to handle exceptions and passes them to the next middleware for centralized error handling. This is a good practice for maintaining clean and maintainable code.src/app.ts (4)
- 6-6: The import of
passportis correctly added to support authentication strategies.- 9-9: The import and instantiation of
AuthServiceare correctly added to set up authentication services.- 16-18: The CORS setup based on the environment is a good practice for security, ensuring that only allowed origins can access the API in production.
- 45-46: The setup of the passport strategy using
AuthServiceis correctly implemented. Ensure that thejwtStrategymethod inAuthServiceis properly defined and returns a valid passport strategy.Verification successful
The
AuthServiceclass and itsjwtStrategymethod have been successfully located within the codebase, specifically insrc/components/auth/services.ts. The methodjwtStrategyis implemented to configure and return a new instance ofpassport-jwt.Strategy, which is a valid passport strategy. This confirms that the setup of the passport strategy usingAuthServiceis correctly implemented, as thejwtStrategymethod is properly defined and returns a valid passport strategy.Scripts Executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Search for the jwtStrategy method definition in AuthService to ensure it returns a valid passport strategy. ast-grep --lang javascript --pattern $'class AuthService { $$$ jwtStrategy($_) { $$$ } $$$ }'Length of output: 108
Script:
#!/bin/bash # Search for the AuthService class definition to verify its existence and list its methods. ast-grep --lang javascript --pattern $'class AuthService { $$$ }'Length of output: 68
Script:
#!/bin/bash # Use ripgrep to search for references to AuthService across all JavaScript or TypeScript files. rg "AuthService" --type js rg "AuthService" --type tsLength of output: 726
Script:
#!/bin/bash # Extract the jwtStrategy method's implementation from AuthService in src/components/auth/services.ts rg "jwtStrategy" src/components/auth/services.tsLength of output: 378
src/components/transactions/validators.ts (3)
- 3-3: The
emptyBodycustom validator correctly checks if the request body is empty. This is a useful validation for ensuring that requests contain necessary data.- 6-35: The
validateTransferRequestfunction correctly sets up validation rules for transfer requests. It ensures that theidis provided in the URL parameters only if the body is empty, and validatesamount,currency, andbank_accountfields in the body. The use of custom validators and error messages enhances the clarity and robustness of request validation.- 38-44: The
validateDepositIdfunction correctly sets up validation for theidparameter in deposit-related requests. It ensures that theidis an integer and not empty, which is crucial for identifying specific deposits..env.example (1)
- 15-31: > 📝 NOTE
This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [18-50]
The addition of new environment variables for database connection details, encryption settings, web push keys, AWS credentials, Cognito client ID, 3rd-party API keys, and agent-related information is comprehensive and well-organized. Ensure that sensitive information such as passwords, keys, and credentials are never hardcoded in the codebase and are always securely managed through environment variables or secure secrets management tools.
src/routes/bank-accounts.router.ts (2)
- 15-18: The use of
passport.authenticatemiddleware for JWT authentication on all bank account routes is correctly implemented, ensuring that these routes are protected and accessible only by authenticated users.- 19-45: The setup of CRUD operations for bank accounts with appropriate validation and error handling middleware is well-structured and follows best practices for REST API design. The use of
validateBankAccount,validateAccountUpdate, andvalidateBankAccountIndexvalidators along withcheckExactandthrowIfBadRequestmiddleware ensures robust input validation and error handling.src/server.ts (2)
- 3-5: The imports for the WhatsApp bot functionality (
BotWhatsapp,MockAdapter, andProviderWS) are correctly added. Ensure that these modules are properly installed and configured in the project.- 30-42: The
startWhatsappBotfunction correctly sets up and starts the WhatsApp bot with a mock database adapter, a provider, and a predefined flow. Ensure that the bot's functionality is thoroughly tested, especially the integration with theProviderWSand the handling of keywords and responses.src/routes/agent.router.ts (1)
- 15-43: The setup of agent-related routes with appropriate validation and error handling middleware is well-structured. The use of
passport.authenticateandrequireAgentRolemiddleware ensures that these routes are protected and accessible only by agents with the correct role. The validators such asvalidateCredentialsandvalidateBankAccountUpdateare correctly applied to relevant routes, enhancing the robustness of request validation.src/components/web-push/services.ts (1)
- 8-53: The
WebPushServicesclass methods for managing web push subscriptions and sending notifications are correctly implemented. The use ofWebPushDAOfor database operations and theweb-pushlibrary for sending notifications is appropriate. Ensure that the VAPID details (publicKey,privateKey, andsubject) are correctly configured in the environment and that theparseSubscriptionutility function accurately processes subscription data..gitignore (3)
- 74-75: Adding
.env.developmentand.env.productionto the.gitignorefile is a good practice to ensure that environment-specific configurations, which might contain sensitive information, are not accidentally committed to the version control system.- 112-112: Including
mysql-datain the.gitignorefile is appropriate if you're using a local MySQL database for development purposes. This prevents the database files from being tracked by Git, which is important for security and to avoid unnecessary clutter in your repository.- 114-114: Adding
test.txtto the.gitignorefile seems to be a specific case. If this file is used for temporary testing or contains sensitive information, ignoring it is justified. However, iftest.txtwas added by mistake or is not relevant to the project, consider removing this entry to avoid confusion.src/db/bank-accounts.ts (1)
- 82-91: The authorization methods (
authorizeUpdate,authorizeDelete, andauthorizeView) do not explicitly disconnect the Prisma client, which is consistent with the recommended practice of managing connections at a higher level or leveraging Prisma's connection pooling. However, ensure that the overall connection management strategy is optimized to avoid performance issues.src/utils/crypt.ts (4)
- 18-23: The
hashfunction has been modified to use SHA256 hashing instead of bcrypt. Ensure that this change aligns with the application's security requirements and that all places using thehashfunction are updated accordingly to handle the new hash format.- 44-68: The
encryptfunction introduces AES192 encryption. Verify that the encryption key length and algorithm meet the application's security requirements. Additionally, ensure that the initialization vector (IV) is securely generated and that the serialized IV and ciphertext are handled securely.- 75-88: The
decryptfunction is responsible for decrypting data encrypted with AES192. Ensure that the decryption process securely handles the initialization vector and ciphertext, and that the decrypted data is properly sanitized before use in the application.- 90-106: The
getConfigfunction generates the encryption key for AES192 encryption. Verify that the password used for key generation is securely stored and that thescryptSyncfunction's parameters (e.g., salt) are appropriately configured for security.src/components/agent/controller.ts (7)
- 10-20: The
loginmethod correctly handles the login process and returns a token. Ensure that error handling is comprehensive and that sensitive information is not leaked in error messages or logs.- 22-30: The
showPaymentsmethod retrieves and returns payment information. Verify that the data returned does not include sensitive information and that access control checks are in place to ensure that agents can only access their own payment information.- 32-42: The
markAsPaidmethod updates the payment status. Ensure that proper validation and access control checks are performed to prevent unauthorized updates to payment statuses.- 44-52: The
showDepositsmethod retrieves and returns deposit information. Similar toshowPayments, verify that sensitive information is not included in the response and that access control is enforced.- 54-64: The
qrmethod serves a QR code image from the filesystem. Ensure that the file path is securely handled to prevent directory traversal attacks and that access to the QR code is appropriately restricted.- 66-76: The
getBankAccountandupdateBankAccountmethods manage bank account information. Verify that these methods include robust validation and access control to prevent unauthorized access or modifications to bank account data.- 88-96: The
getBalanceandcompletePendingDepositsmethods handle sensitive financial operations. Ensure that these methods implement strict access control and validation to safeguard against unauthorized access and manipulation.src/services/http.service.ts (6)
- 13-21: The
agentAxiosInstancegetter creates a new axios instance with authorization headers. Ensure that the token is securely handled and that the instance is reused when possible to avoid unnecessary overhead.- 26-32: The
authedAgentApiproperty exposes methods for authenticated requests. Verify that these methods are used appropriately and that sensitive operations are protected by adequate security checks.- 38-43: The
plainAgentApigetter creates an axios instance for non-authenticated requests. Ensure that this instance is used only for operations that do not require authentication and that security implications are considered.- 48-53: The
playerApigetter creates an axios instance for player requests. Verify that this instance is used in a secure manner and that player-related operations enforce proper authentication and authorization.- 71-91: The
sendmethod handles the actual sending of requests and includes logic for token expiration handling. Ensure that the token refresh logic is secure and that retries are managed appropriately to prevent potential denial-of-service scenarios.- 93-106: The
handleTokenExpirationmethod attempts to refresh the token upon expiration. Verify that the token refresh process is secure and that it properly invalidates the old token to prevent reuse.src/components/auth/services.ts (4)
- 12-22: The
cypherPassgetter ensures that the encryption password is present in the environment variables. Verify that the environment variable is securely managed and that error handling is appropriate for missing configuration.- 29-35: The
tokensmethod generates access and refresh token pairs. Ensure that the token generation process is secure and that tokens are properly linked to database objects for tracking and invalidation.- 40-63: The
refreshmethod handles token refresh operations. Verify that the refresh token validation is secure, that tokens are properly invalidated upon use, and that potential token reuse is mitigated.- 69-94: The
jwtStrategymethod configures the JWT strategy for passport authentication. Ensure that the strategy properly validates tokens, checks for token invalidation, and securely deserializes user information.src/types/bot/bot-whatsapp.d.ts (1)
- 1-134: The type definitions for the WhatsApp bot module appear to be comprehensive and correctly defined. Ensure that these types accurately represent the bot's functionality and that they are used consistently throughout the application to facilitate type safety and code readability.
src/components/players/services.ts (3)
- 24-29: The
getPlayerByIdmethod retrieves player information by ID and useshidePasswordto remove sensitive information. Verify that this method correctly handles non-existent players and that access control is enforced.- 34-70: The
createmethod handles player creation, including interactions with external services. Ensure that the player creation process is secure, that input validation is performed, and that error handling is comprehensive to prevent information leakage or unintended behavior.- 75-100: The
loginmethod manages player login, including validation against local and external databases. Verify that password comparison is secure, that external API interactions are handled securely, and that tokens are generated and returned in a secure manner.src/components/agent/services.ts (9)
- 18-27: The method
usernameretrieves the encrypted username from the environment variables, decrypts it, and returns the decrypted username. It throws aCustomErrorif the username is not found in the environment variables.
This is a secure way to handle sensitive information. However, ensure that the decryption key is securely managed and not exposed in the code or version control.
- 30-45: The
loginmethod performs authentication by comparing the provided credentials with the expected ones. It uses hashing for password comparison and throws aCustomErrorif the credentials are invalid.
The use of hashing for password comparison is a good security practice. However, consider implementing rate limiting or account lockout mechanisms to prevent brute-force attacks.
- 48-50: The
showPaymentsmethod retrieves all payments from the database.
This method is straightforward and correctly retrieves the payments. Ensure that appropriate permissions checks are in place to prevent unauthorized access to payment information.
- 56-60: The
markAsPaidmethod updates a payment's status to paid by setting thepaidfield to the current date and time.
Correctly marks a payment as paid. Ensure that this operation is idempotent to prevent any unintended consequences if called multiple times for the same payment.
- 63-65: The
showDepositsmethod retrieves all deposits from the database.
This method is straightforward and correctly retrieves the deposits. Similar to the
showPaymentsmethod, ensure that appropriate permissions checks are in place.
- 68-70: The
getBankAccountmethod retrieves the bank account information for the agent.
Correctly retrieves the bank account information. Ensure that sensitive information such as account numbers is handled securely.
- 73-80: The
updateBankAccountmethod updates the bank account information for the agent.
Correctly updates the bank account information. Ensure that validation checks are in place to prevent invalid data from being saved.
- 83-96: The
getBalancemethod retrieves the balance information for the agent by making an authenticated API call.
Correctly retrieves balance information. Ensure that error handling is robust and that the external API's availability and response times are considered to prevent service degradation.
- 99-115: The
completePendingDepositsmethod processes pending deposits by transferring coins and marking the transfer date.
This method correctly processes pending deposits. However, consider adding transactional integrity checks to ensure that all steps of the process complete successfully or are rolled back in case of failure.
src/db/deposits.ts (9)
- 15-22: The
createmethod creates a new deposit entry in the database and includes the associated player in the response.
Correctly creates a deposit entry. Ensure that input validation is performed to prevent invalid data from being inserted into the database.
- 25-35: The
indexmethod retrieves all deposits or only unconfirmed deposits based on theallparameter.
This method provides flexibility in retrieving deposits. Ensure that appropriate permissions checks are in place to prevent unauthorized access to deposit information.
- 43-52: The
getByIdmethod retrieves a specific deposit by its ID.
Correctly retrieves a deposit by ID. Ensure that appropriate permissions checks are in place to prevent unauthorized access to deposit information.
- 56-63: The
getPendingmethod retrieves all pending deposits for a specific player.
Correctly retrieves pending deposits for a player. Ensure that appropriate permissions checks are in place to prevent unauthorized access to deposit information.
- 66-75: The
getPendingCoinTransfersmethod retrieves all deposits with pending coin transfers.
Correctly retrieves deposits with pending coin transfers. Ensure that appropriate permissions checks are in place to prevent unauthorized access to deposit information.
- 79-85: The
updatemethod updates a deposit's information based on the provided data.
Correctly updates a deposit's information. Ensure that input validation is performed to prevent invalid data from being updated in the database.
- 89-95: The
deletemethod deletes a deposit by its ID.
Correctly deletes a deposit by ID. Ensure that appropriate permissions checks are in place to prevent unauthorized deletion of deposit information.
- 103-115: The
authorizeTransactionmethod ensures a deposit exists and belongs to a specific player.
Correctly authorizes a transaction. Ensure that this method is used consistently to prevent unauthorized access or manipulation of deposit information.
- 128-147: The
authorizeConfirmationmethod ensures a deposit exists, belongs to a specific player, is not already confirmed, and is not being confirmed.
Correctly authorizes a confirmation. Ensure that this method is used consistently to prevent unauthorized access or manipulation of deposit information.
prisma/migrations/20240220155527_initial_migration/migration.sql (1)
- 95-107: When adding foreign keys, it's important to consider the
ON DELETEandON UPDATEactions. The current setup usesRESTRICTforON DELETE, which is generally safe. However, ensure that this behavior aligns with the application's data management strategy, especially for entities likePAYMENTSandDEPOSITSthat are closely related toPLAYERSandBANK_ACCOUNTS.Consider if
CASCADEorSET NULLmight be more appropriate for your use case, depending on how you want to handle deletions of related entities.prisma/schema.prisma (1)
- 97-112: The
Depositmodel includes adirtyfield with a default value oftrue. This design choice should be carefully considered, as it implies new deposits are initially marked as "dirty" by default. Ensure this aligns with the intended business logic and handling of deposit records.Confirm the business logic behind the default
truevalue for thedirtyfield in theDepositmodel.src/services/token.service.ts (1)
- 127-140: The
loginmethod sets the agent'sdirtyflag totruebefore attempting login and resets it tofalseafterward. Ensure that this flag is correctly managed in all scenarios, including when exceptions occur, to avoid leaving the agent in an incorrect state.Verify that the
dirtyflag is correctly managed in all scenarios to avoid leaving the agent in an incorrect state.src/middlewares/errorHandler.ts (1)
- 44-50: The handling of Prisma errors in the
genericErrorHandlermiddleware is a good practice. However, ensure that all possible Prisma error types are covered and that the error handling logic is comprehensive enough to provide meaningful feedback for all error scenarios.Verify that the Prisma error handling covers all necessary cases and provides meaningful feedback.
seed.sql (5)
- 2-5: The configuration settings, including disabling foreign key checks, are noted. Ensure that data integrity is maintained when using
SET foreign_key_checks = 0, especially in a production environment.- 9-13: Insert statements for the
BANK_ACCOUNTStable use fictional characters, indicating this is seed data for testing or development. Ensure the purpose of this seed data is clearly documented to avoid confusion.- 15-20: The
DEPOSITStable insert statements include a mix of NULL and non-NULLconfirmedcolumn values, indicating a design where deposits can be pending confirmation. This pattern is appropriate for financial applications.- 22-29: The
PAYMENTStable insert statements also include a mix of NULL and non-NULLpaidcolumn values, indicating a consistent design choice with theDEPOSITStable where transactions can be pending.- 31-42: The insert statements for the
PLAYERSandTRANSACTIONStables demonstrate good security practices with hashed passwords and a system capable of tracking transaction states. This is essential for financial applications.README.md (1)
- 1-1: The project name "Timba Api" might be mistaken for a spelling error. Consider confirming the project name's spelling to ensure clarity and avoid confusion.
| | ||
| **TEN stack** is a `Typescript` + `Express` + `Node` starter kit to develop `REST API` server apps. | ||
| **Timba Api** is a `Typescript` + `Express` + `Node` starter kit to develop `REST API` server apps. | ||
| Nothing new under the sun, just a straight forward combo to make server development a little bit faster. And of course, this make my freelancing days more enjoyable 😎 |
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.
The phrase "just a straight forward combo" should be corrected to "just a straightforward combo" for proper grammar.
Additionally, "this make my freelancing days more enjoyable" should be corrected to "this makes my freelancing days more enjoyable" to ensure subject-verb agreement.
- just a straight forward combo to make server development a little bit faster. And of course, this make my freelancing days more enjoyable + just a straightforward combo to make server development a little bit faster. And of course, this makes my freelancing days more enjoyableCommittable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.
| Nothing new under the sun, just a straight forward combo to make server development a little bit faster. And of course, this make my freelancing days more enjoyable 😎 | |
| Nothing new under the sun, just a straightforward combo to make server development a little bit faster. And of course, this makes my freelancing days more enjoyable 😎 |
| **Timba Api** is a `Typescript` + `Express` + `Node` starter kit to develop `REST API` server apps. | ||
| Nothing new under the sun, just a straight forward combo to make server development a little bit faster. And of course, this make my freelancing days more enjoyable 😎 | ||
| Comes with: | ||
| |
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.
📝 NOTE
This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [13-13]
The word "proccess" should be corrected to "process" to fix the typo.
- Manage production app proccess with [PM2](https://pm2.keymetrics.io/) + Manage production app process with [PM2](https://pm2.keymetrics.io/)| # Docs | ||
| | ||
| ## Prerequisites | ||
| ## Contenidos | ||
| | ||
| - [Node.js](https://nodejs.org) (`>= 16.0.0`) | ||
| - [Yarn](https://yarnpkg.com/en/docs/install) or [NPM](https://docs.npmjs.com/getting-started/installing-node) | ||
| ### Endpoints Jugadores | ||
| + [Ver Jugador](#ver-jugador) | ||
| + [Crear Jugador](#crear-jugador) | ||
| + [Login de Jugador](#login-jugador) | ||
| | ||
| ## Install | ||
| ### Endpoints Cuentas Bancarias | ||
| + [Ver Cuentas Bancarias](#ver-cuentas-bancarias) | ||
| + [Crear Cuenta Bancaria](#crear-cuenta-bancaria) | ||
| + [Actualizar Cuenta Bancaria](#actualizar-cuenta-bancaria) | ||
| + [Eliminar Cuenta Bancaria](#eliminar-cuenta-bancaria) | ||
| | ||
| - Fork or Use [this](https://github.com/filoscoder/tenstack-starter/generate) template repository. | ||
| - [Clone](https://github.com/git-guides/git-clone) the forked repository. | ||
| - Install the dependencies with [yarn](https://yarnpkg.com/getting-started/usage) or [npm](https://docs.npmjs.com/cli/v7/commands/npm-install). | ||
| ### Endpoints Transferencias | ||
| + [Cargar Fichas](#cargar-fichas) | ||
| + [Retirar Premios](#retirar-premios) | ||
| + [Ver Depósitos Pendientes](#ver-depósitos-pendientes) | ||
| + [Confirmar Depósito Pendiente](#confirmar-depósito-pendiente) | ||
| + [Eliminar Depósito Pendiente](#eliminar-depósito-pendiente) | ||
| | ||
| > Make sure you already have [`node.js`](https://github.com/filoscoder/tenstack-starter#prerequisites) and [`npm`](https://github.com/filoscoder/tenstack-starter#prerequisites) or [`yarn`](https://github.com/filoscoder/tenstack-starter#prerequisites) installed in your system. | ||
| ### [Interfaces](#interfaces) | ||
| | ||
| - Set your `git remote add origin` path | ||
| ### Ver Jugador | ||
| | ||
| ```bash | ||
| git remote add origin ${forked-and-cloned-path} | ||
| ``` | ||
| |Endpoint:| `/players/:id`| | ||
| ---|---| | ||
| Método | `GET` | ||
| Devuelve | [`Player & { bank_accounts: BankAccount[] }`](#player) | ||
| | ||
| > [Update the url](https://docs.github.com/en/get-started/getting-started-with-git/managing-remote-repositories#changing-a-remote-repositorys-url) if you already have an `origin` | ||
| ### Crear Jugador | ||
| | ||
| <br> | ||
| <br> | ||
| |Endpoint:| `/players`| | ||
| ---|---| | ||
| Método | `POST` | ||
| Body (json) | [`PlayerRequest`](#playerrequest) | ||
| Devuelve | [`Player`](#Player) | ||
| | ||
| ## Config | ||
| ### Login Jugador | ||
| | ||
| - Copy `.env.example` a file at the root of the application. | ||
| - Add or modify specific variables and update it according to your need. | ||
| |Endpoint| `/players/login`| | ||
| ---|---| | ||
| Método |`POST` | ||
| Body (json) | [`Credenciales`](#credenciales) | ||
| Devuelve | [`Player`](#player) | ||
| | ||
| ```bash | ||
| cp .env.example .env | ||
| ``` | ||
| ### Ver Cuentas Bancarias | ||
| | ||
| > Check the `config` folder to customize your settings (`/src/config`) | ||
| | ||
| <br> | ||
| <br> | ||
| |Endpoint| `/bank-account/:id?`| | ||
| ---|---| | ||
| Método |`GET` | ||
| Devuelve | [`BankAccount[]`](#bankaccount) | ||
| | ||
| ## Alias @ | ||
| > **Nota:** Siempre devuleve un array | ||
| To make paths clean and ease to access `@` is setup up for `/src` path | ||
| > **Nota:** Omitir el parámetro `id` para ver todas las cuentas bancarias del usuario | ||
| ```javascript | ||
| // BEFORE | ||
| import config from './config'; | ||
| import routes from './routes'; | ||
| ### Crear Cuenta Bancaria | ||
| | ||
| // NOW | ||
| import config from '@/config'; | ||
| import routes from '@/routes'; | ||
| ``` | ||
| | ||
| > You can customize this setup: | ||
| > `/tsconfig.json` > compilerOptions.paths | ||
| > `/eslintrc.yml` > rules.settings.alias.map | ||
| |Endpoint| `/bank-account`| | ||
| ---|---| | ||
| Método |`POST` | ||
| Body (json) | [`BankAccountRequest`](#bankaccountrequest) | ||
| Devuelve | [`BankAccount`](#bankaccount) | ||
| | ||
| <br> | ||
| <br> | ||
| ### Actualizar Cuenta Bancaria | ||
| | ||
| ## Local Development | ||
| |Endpoint| `/bank-account`| | ||
| ---|---| | ||
| Método |`PUT` | ||
| Body (json) | [`BankAccountRequest`](#bankaccountrequest) | ||
| Devuelve | [`BankAccount`](#bankaccount) | ||
| | ||
| Run the server locally. It will be run with Nodemon and ready to serve on port `8080` (unless you specify it on your `.env`) | ||
| > **Nota:** Los campos son opcionales. Incluir los que se quiera modificar | ||
| ```bash | ||
| yarn start # or npm start | ||
| ``` | ||
| ### Eliminar Cuenta Bancaria | ||
| | ||
| |Endpoint| `/bank-account`| | ||
| ---|---| | ||
| Método |`DELETE` | ||
| Devuelve | 200 OK | ||
| | ||
| ### Cargar Fichas | ||
| Incluir el id en la URL y omitir el body para confirmar un depósito pendiente | ||
| Omitir el id en la URL e incluir los datos en el body para crear un depósito nuevo | ||
| | ||
| |Endpoint| `/transactions/deposit/:id?`| | ||
| ---|---| | ||
| Método |`POST` | ||
| Body (json) |[`TransferRequest`](#transferrequest) | ||
| Devuelve |[`TransferResult & { deposit: Deposit }`](#transferresult) | ||
| | ||
| > Check [`package.json`](https://github.com/filoscoder/tenstack-starter/blob/master/package.json) to see more "scripts" | ||
| ### Retirar Premios | ||
| | ||
| <br> | ||
| <br> | ||
| |Endpoint| `/transactions/cashout`| | ||
| ---|---| | ||
| Método |`POST` | ||
| Body (json) |[`TransferRequest`](#transferrequest) | ||
| Devuelve |[`TransferResult`](#transferresult) | ||
| | ||
| ## Production | ||
| ### Ver Depósitos Pendientes | ||
| | ||
| First, build the application. | ||
| |Endpoint| `/transactions/deposit/pending`| | ||
| ---|---| | ||
| Método |`GET` | ||
| Devuelve |[`Deposit[]`](#deposit) | ||
| | ||
| ```bash | ||
| yarn build # or npm run build | ||
| > **Nota:** siempre devuelve un array | ||
| ### Confirmar Depósito Pendiente | ||
| | ||
| |Endpoint| `/transactions/deposit/:id/confirm`| | ||
| ---|---| | ||
| Método |`PUT` | ||
| Devuelve |[`TransferResult`](#transferresult) | ||
| | ||
| ### Eliminar Depósito Pendiente | ||
| |Endpoint| `/transactions/deposit/:id`| | ||
| ---|---| | ||
| Método |`DELETE` | ||
| Devuelve | 200 OK | ||
| | ||
| ## Interfaces | ||
| | ||
| ### Player | ||
| ```typescript | ||
| { | ||
| id: number; | ||
| panel_id: number; | ||
| username: string; | ||
| email?: string; | ||
| first_name?: string; | ||
| last_name?: string; | ||
| date_of_birth?: string; | ||
| movile_number?: string; | ||
| country?: string; | ||
| balance_currency: string; | ||
| status: string; | ||
| created_at: string; // 2024-01-29T18:14:41.534Z | ||
| } | ||
| ``` | ||
| | ||
| ### PlayerRequest | ||
| ```typescript | ||
| { | ||
| username: string, | ||
| password: string, | ||
| email: string, | ||
| first_name?: string, | ||
| last_name?: string, | ||
| date_of_birth?: DateTime, | ||
| movile_number?: string, | ||
| country?: string | ||
| } | ||
| ``` | ||
| | ||
| ### BankAccountRequest | ||
| ```typescript | ||
| { | ||
| owner: string // Nombre del beneficiario | ||
| owner_id: number // DNI | ||
| bankName: string // Nombre del banco | ||
| bankNumber: string // CBU | ||
| bankAlias: string? | ||
| } | ||
| ``` | ||
| Then, use [`pm2`](https://github.com/Unitech/pm2) to start the application as a service. | ||
| ### BankAccount | ||
| ```typescript | ||
| { | ||
| id: number | ||
| owner: string // Nombre del beneficiario | ||
| owner_id: number // DNI | ||
| player_id: number // ID de Player | ||
| bankName: string // Nombre del banco | ||
| bankNumber: string // CBU | ||
| bankAlias: string? | ||
| created_at: // 2024-01-29T18:14:41.534Z | ||
| updated_at: // 2024-01-29T18:14:41.534Z | ||
| } | ||
| ``` | ||
| ```bash | ||
| yarn service:start # or npm run service:start | ||
| ### Credenciales | ||
| ```typescript | ||
| { | ||
| username: string | ||
| password: string | ||
| } | ||
| ``` | ||
| <br> | ||
| <br> | ||
| ### TransferRequest | ||
| ```typescript | ||
| { | ||
| amount: number | ||
| currency: string | ||
| bank_account: number // ID de cuenta bancaria | ||
| } | ||
| ``` | ||
| # Contribution | ||
| ### TransferResult | ||
| ```typescript | ||
| { | ||
| status: "COMPLETED" | "INCOMPLETE" | ||
| player_balance?: number // undefined en caso de deposito incompleto | ||
| error?: string // En caso de error, el motivo | ||
| deposit: Deposit | ||
| } | ||
| ``` | ||
| This repository will be managed as an `open-source`. <br> | ||
| Please feel free to open an `issue` or a `pull request` to suggest changes or additions. | ||
| ### Deposit | ||
| ```typescript | ||
| { | ||
| id: number | ||
| player_id: number | ||
| amount: number | ||
| confirmed?: datetime // 2024-02-23T12:35:51.017Z | ||
| bank_account: number | ||
| currency: string | ||
| dirty: boolean | ||
| created_at: datetime // 2024-02-23T12:35:51.017Z | ||
| updated_at: datetime // 2024-02-23T12:35:51.017Z | ||
| } | ||
| ``` | ||
| # Support & Contact | ||
| ### RootBankAccount | ||
| ```typescript | ||
| { | ||
| name: string | ||
| dni: string | ||
| bankName: string | ||
| accountNumber: string | ||
| clabe: string | ||
| alias: string | ||
| } | ||
| ``` | ||
| If you have any question or suggestion, don't hesitate to contact me: | ||
| ## TODO | ||
| ✉️ [filoscoder.io@gmail.com](mailto:filoscoder.io@gmail.com) | ||
| - Instanciar servicios en lugar de usar metodos estaticos | ||
| - Cambiar contraseña (no funciona en el casino, vamos por este lado) | ||
| - Endpoint https://agent.casinomex.vip/api/users/5941/change-password/ | ||
| - Body: `{ new_password:string }` | ||
| - Recibir clave de rastreo en endpoints de cashIn y confirmarDeposito | ||
| - Hacer email opcional en player request validator | ||
| - Documentar endpoints agente | ||
| - Inhabilitar tokens anteriores al loguear un usuario (borrarlos de la bbdd, seleccionando por player_id) | ||
| - **Que pasa cuando un pago se verifica pero el agente no tiene fichas suficientes? o algo sale mal en el servidor del casino?** | ||
| + Si el agente no tiene fichas, mandar push al panel de agente con total pendiente | ||
| + Botón liberar fichas | ||
| + Chequear que total pendiente sea menor a nuevo stock | ||
| + Liberar transferencias | ||
| - Encriptar JWT | ||
| # Author & Credits | ||
| ## Optimizaciones | ||
| <a src="https://github.com/filoscoder"> | ||
| <img width="60px" style="border-radius: 50%;" src="https://avatars.githubusercontent.com/filoscoder"> | ||
| </a> | ||
| - Invalidar tokens en conjunto con una sola petición SQL |
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.
The documentation of endpoints and interfaces is comprehensive and well-structured. However, there are several instances of possible spelling mistakes and grammatical errors throughout the document. It's recommended to go through the document and correct these errors for clarity and professionalism. For example, "devuleve" should be "devuelve" in the context of returning an array, and "metodos estaticos" should be "métodos estáticos" to maintain consistency with Spanish language accents and spelling.
Consider using a spell checker or a grammar correction tool to identify and correct these errors throughout the document.
| - Instanciar servicios en lugar de usar metodos estaticos | ||
| - Cambiar contraseña (no funciona en el casino, vamos por este lado) | ||
| - Endpoint https://agent.casinomex.vip/api/users/5941/change-password/ | ||
| - Body: `{ new_password:string }` | ||
| - Recibir clave de rastreo en endpoints de cashIn y confirmarDeposito | ||
| - Hacer email opcional en player request validator | ||
| - Documentar endpoints agente | ||
| - Inhabilitar tokens anteriores al loguear un usuario (borrarlos de la bbdd, seleccionando por player_id) | ||
| - **Que pasa cuando un pago se verifica pero el agente no tiene fichas suficientes? o algo sale mal en el servidor del casino?** | ||
| + Si el agente no tiene fichas, mandar push al panel de agente con total pendiente | ||
| + Botón liberar fichas | ||
| + Chequear que total pendiente sea menor a nuevo stock | ||
| + Liberar transferencias | ||
| - Encriptar JWT | ||
| # Author & Credits | ||
| ## Optimizaciones | ||
| <a src="https://github.com/filoscoder"> | ||
| <img width="60px" style="border-radius: 50%;" src="https://avatars.githubusercontent.com/filoscoder"> | ||
| </a> | ||
| - Invalidar tokens en conjunto con una sola petición SQL |
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.
The TODO and Optimizations sections contain valuable insights into future improvements and optimizations. It's crucial to track these tasks in a project management tool or issue tracker to ensure they are addressed in a timely manner. Additionally, consider translating these sections into English if the project aims for a broader international audience.
Would you like assistance in creating GitHub issues for these tasks or translating these sections?
| INSERT INTO `USERS_ROOT` (`id`, `username`, `password`, `panel_id`, `access`, `refresh`, `json_response`, `dirty`, `created_at`, `updated_at`) VALUES | ||
| (3, 'luquin', '{\"ivArray\":[\"98\",\"178\",\"232\",\"94\",\"155\",\"6\",\"15\",\"40\",\"39\",\"234\",\"143\",\"28\",\"44\",\"43\",\"56\",\"92\"],\"ciphertext\":\"a2b3df852669cf01f9983953dc67cf43\"}', 414, 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNzA4Njk1MTIwLCJqdGkiOiJlN2IzNTcyZTEzNTA0ZDcyYWQyNDA0YzdmOWQzYTNlNSIsInVzZXJfaWQiOjQxNCwicmVmcmVzaF9zaGlmdCI6MTIwLCJ1dWlkIjoiOGE2OGM0ZTgwNGY4NDc2Zjk1OGM0NTJiZjE0YzcxN2YifQ.gOf5JEObwX24EEloDfDzawJX0pavbLssb_xL2vUkccI', 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImV4cCI6MTcwODY5ODEyMCwianRpIjoiODVjNDI1Mjg2M2IxNDRkNTlmZGY3MWFiNmE5ZDQwNTUiLCJ1c2VyX2lkIjo0MTQsInJlZnJlc2hfc2hpZnQiOjEyMCwidXVpZCI6IjhhNjhjNGU4MDRmODQ3NmY5NThjNDUyYmYxNGM3MTdmIn0.g2TDjCxGLBFot0LE1h1WYVCAoXSKKHNAaeHg9wVedmk', '{\"id\":414,\"jackpots_won\":[],\"is_email_verified\":true,\"info\":{\"first_name\":\"lucas\",\"last_name\":\"lucas\",\"date_of_birth\":null,\"mobile_number\":\"\",\"country\":\"\",\"city\":\"\",\"street_address\":\"\",\"postal_code\":\"\",\"state\":null},\"bonus_balance\":\"0.00\",\"balance\":\"9.27\",\"role\":\"PA\",\"email\":\"luquin@gmail.com\",\"is_withdraw_allowed\":true,\"is_banned\":false,\"access\":\"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNzA4Njk1MTIwLCJqdGkiOiJlN2IzNTcyZTEzNTA0ZDcyYWQyNDA0YzdmOWQzYTNlNSIsInVzZXJfaWQiOjQxNCwicmVmcmVzaF9zaGlmdCI6MTIwLCJ1dWlkIjoiOGE2OGM0ZTgwNGY4NDc2Zjk1OGM0NTJiZjE0YzcxN2YifQ.gOf5JEObwX24EEloDfDzawJX0pavbLssb_xL2vUkccI\",\"refresh\":\"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImV4cCI6MTcwODY5ODEyMCwianRpIjoiODVjNDI1Mjg2M2IxNDRkNTlmZGY3MWFiNmE5ZDQwNTUiLCJ1c2VyX2lkIjo0MTQsInJlZnJlc2hfc2hpZnQiOjEyMCwidXVpZCI6IjhhNjhjNGU4MDRmODQ3NmY5NThjNDUyYmYxNGM3MTdmIn0.g2TDjCxGLBFot0LE1h1WYVCAoXSKKHNAaeHg9wVedmk\",\"last_login\":\"2024-02-23T13:22:00.225711Z\",\"username\":\"luquin\",\"first_name\":\"\",\"last_name\":\"\",\"date_joined\":\"2023-11-15T16:52:59.768862Z\",\"balance_currency\":\"MXN\",\"bonus_balance_currency\":\"MXN\",\"is_self_registered\":false,\"language\":\"en-US\",\"needs_document_approve\":true,\"affise_data\":null,\"pap_data\":null,\"cpf_document\":null,\"parent\":3}', 0, '2024-02-23 13:22:00.401', '2024-02-23 13:22:00.401'); |
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.
Storing JWT tokens in the database, as seen in the USERS_ROOT table insert, raises security concerns. Ensure these tokens are placeholders and not valid tokens. Additionally, consider whether storing large JSON responses in the database is necessary, as it might indicate a need for normalization or a different storage strategy.
| static async index(player_id: number) { | ||
| try { | ||
| const accounts = await prisma.bankAccount.findMany({ | ||
| where: { player_id }, | ||
| }); | ||
| return accounts; | ||
| } catch (error: any) { | ||
| // Prisma errors handled by prismaErrorHandler() | ||
| throw error; | ||
| } finally { | ||
| prisma.$disconnect(); | ||
| } |
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.
The index method disconnects the Prisma client after fetching bank accounts. This could lead to unnecessary disconnections and reconnections, affecting performance. Consider optimizing the connection management strategy.
| static async show(account_id: number, player_id: number) { | ||
| try { | ||
| await this.authorizeView(account_id, player_id); | ||
| | ||
| const account = await prisma.bankAccount.findUnique({ | ||
| where: { id: account_id }, | ||
| }); | ||
| return account; | ||
| } catch (error: any) { | ||
| throw error; | ||
| } finally { | ||
| prisma.$disconnect(); | ||
| } |
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.
The show method follows the same pattern of disconnecting the Prisma client after each operation. This is not recommended for performance reasons. Evaluate the connection management approach to ensure efficient resource use.
| static async create(player_id: number, request: BankAccountRequest) { | ||
| try { | ||
| const account = await prisma.bankAccount.create({ | ||
| data: { player_id, ...request }, | ||
| }); | ||
| return account; | ||
| } catch (error: any) { | ||
| throw error; | ||
| } finally { | ||
| prisma.$disconnect(); | ||
| } | ||
| } |
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.
Similar to previous methods, the create method disconnects the Prisma client in a finally block. This practice can lead to performance issues. Reconsider the connection management strategy for better performance.
| static async update( | ||
| account_id: number, | ||
| player_id: number, | ||
| request: BankAccountRequest, | ||
| ) { | ||
| try { | ||
| await this.authorizeUpdate(account_id, player_id); | ||
| | ||
| const updated = await prisma.bankAccount.update({ | ||
| where: { id: account_id, player_id }, | ||
| data: request, | ||
| }); | ||
| return updated; | ||
| } catch (error: any) { | ||
| throw error; | ||
| } finally { | ||
| prisma.$disconnect(); | ||
| } | ||
| } |
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.
The update method also disconnects the Prisma client after each operation. This could negatively impact performance due to frequent disconnections and reconnections. Optimize connection management to enhance efficiency.
| static async delete(account_id: number, player_id: number) { | ||
| try { | ||
| await this.authorizeDelete(account_id, player_id); | ||
| | ||
| await prisma.bankAccount.delete({ where: { id: account_id } }); | ||
| } catch (error: any) { | ||
| throw error; | ||
| } finally { | ||
| prisma.$disconnect(); | ||
| } | ||
| } |
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.
The delete method exhibits the same issue with disconnecting the Prisma client after each operation. This is not optimal for performance. Reevaluate the connection management approach to improve application efficiency.
Description
Mejorado el flujo de carga de fichas para soportar el caso en el que el agente no tenga saldo suficiente.
Summary by CodeRabbit
New Features
Bug Fixes
Documentation
Refactor
Chores
.gitignoreand.env.examplefiles to align with current project needs.