Skip to content

chore: add telegram handle callback route#424

Merged
Behzad-rabiei merged 1 commit intomainfrom
test-telegram-login
Jan 21, 2025
Merged

chore: add telegram handle callback route#424
Behzad-rabiei merged 1 commit intomainfrom
test-telegram-login

Conversation

@Behzad-rabiei
Copy link
Member

@Behzad-rabiei Behzad-rabiei commented Jan 21, 2025

Summary by CodeRabbit

  • New Features

    • Added Telegram authorization callback support to the authentication system
    • Expanded routing to handle Telegram authorization callbacks
  • Chores

    • Reorganized and consolidated import statements in authentication controller and routes

@coderabbitai
Copy link

coderabbitai bot commented Jan 21, 2025

Walkthrough

The pull request introduces modifications to the authentication controller and routes, focusing on adding Telegram authorization support. A new function telegramAuthorizeCallback is added to the authentication controller, and a corresponding route is created in the authentication routes file. The changes primarily involve expanding the existing authentication infrastructure to include Telegram-related callback handling.

Changes

File Change Summary
src/controllers/auth.controller.ts - Reorganized imports
- Added new telegramAuthorizeCallback function
- Function logs request details and sends a simple response
src/routes/v1/auth.route.ts - Consolidated middleware imports
- Added new route /telegram/authorize/callback
- Uses existing discordAuthorizeCallback method

Poem

🐰 A Telegram tale of auth delight,
Rabbits hopping through routes so bright!
Callbacks dancing, middleware clean,
A new path opens, authorization's scene!
Code hops forward with playful might 🚀

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

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 using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d4c0c61 and b355dcf.

📒 Files selected for processing (2)
  • src/controllers/auth.controller.ts (2 hunks)
  • src/routes/v1/auth.route.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: ci / lint / Lint
🔇 Additional comments (2)
src/controllers/auth.controller.ts (2)

81-84: Add input validation for Telegram callback data

The callback handler should validate the incoming Telegram authentication data before processing it.

Consider adding:

  1. Validation middleware using your existing validate middleware
  2. Type definitions for Telegram auth data
  3. Hash verification of Telegram data

Would you like me to provide an example implementation of the validation logic?


5-10: Verify required imports for Telegram authentication

The current imports might not include all necessary modules for Telegram authentication. Consider adding:

  • Telegram auth configuration
  • Telegram service (if separate from auth service)
  • Hash verification utilities for Telegram

Run this script to check for existing Telegram-related modules:

✅ Verification successful

Current imports are sufficient for Telegram authentication

The telegramAuthorizeCallback implementation is a simple placeholder that only logs request data. The current imports provide all necessary dependencies, and the verification token is already accessible through the general config import. No additional Telegram-specific imports are required at this stage.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for existing Telegram-related files and imports
echo "Searching for Telegram-related files..."
fd -e ts -e js telegram

echo "Searching for Telegram-related imports..."
rg -i "import.*telegram" -g "*.ts"

Length of output: 1256


Script:

#!/bin/bash
# Check telegram config exports and auth controller usage
echo "Checking telegram config exports..."
cat src/config/telegram.ts

echo -e "\nChecking auth controller for Telegram patterns..."
rg -A 5 "telegram" src/controllers/auth.controller.ts

Length of output: 684

// Routes
router.get('/discord/authorize', authController.discordAuthorize);
router.get('/discord/authorize/callback', authController.discordAuthorizeCallback);
router.get('/telegram/authorize/callback', authController.discordAuthorizeCallback);
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Critical: Incorrect callback handler used for Telegram route

The Telegram callback route is incorrectly using Discord's callback handler (discordAuthorizeCallback). This will not work as Telegram and Discord have different OAuth flows and data structures. Use the newly added telegramAuthorizeCallback instead.

Apply this fix:

-router.get('/telegram/authorize/callback', authController.discordAuthorizeCallback);
+router.get('/telegram/authorize/callback', authController.telegramAuthorizeCallback);

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +81 to +84
const telegramAuthorizeCallback = catchAsync(async function (req: Request, res: Response) {
console.log(req.body, req.query, req.params);
res.send('Hi');
});
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Implementation incomplete: Add proper Telegram authorization logic

The current implementation is a placeholder that only logs data and returns "Hi". This needs to be replaced with proper Telegram authorization logic including:

  • Validation of Telegram authentication data
  • User creation/lookup logic
  • Token generation
  • Error handling similar to discordAuthorizeCallback

Here's a suggested structure:

const telegramAuthorizeCallback = catchAsync(async function (req: Request, res: Response) {
  const STATUS_CODE_SIGNIN = 1001;
  const STATUS_CODE_LOGIN = 1002;
  const STATUS_CODE_ERROR = 1003;
  
  try {
    // Validate Telegram auth data
    const telegramData = validateTelegramAuth(req.query);
    
    // Find or create user
    let user = await userService.getUserByFilter({ telegramId: telegramData.id });
    let statusCode = STATUS_CODE_LOGIN;
    
    if (!user) {
      user = await userService.createUser({ telegramId: telegramData.id });
      statusCode = STATUS_CODE_SIGNIN;
    }
    
    // Generate tokens
    const tokens = await tokenService.generateAuthTokens(user);
    
    // Return response
    const params = {
      statusCode,
      accessToken: tokens.access.token,
      accessExp: tokens.access.expires.toString(),
      refreshToken: tokens.refresh.token,
      refreshExp: tokens.refresh.expires.toString(),
    };
    
    const query = querystring.stringify(params);
    res.redirect(`${config.frontend.url}/callback?${query}`);
    
  } catch (err) {
    logger.error({ err }, 'Failed to authorize telegram account');
    
    const params = {
      statusCode: STATUS_CODE_ERROR,
    };
    const query = querystring.stringify(params);
    res.redirect(`${config.frontend.url}/callback?${query}`);
  }
});


const telegramAuthorizeCallback = catchAsync(async function (req: Request, res: Response) {
console.log(req.body, req.query, req.params);
res.send('Hi');
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Remove console.log statement

Using console.log is not recommended in production code. Use the logger instead if debugging is needed.

-  console.log(req.body, req.query, req.params);
+  logger.debug({ body: req.body, query: req.query, params: req.params }, 'Telegram callback received');

Committable suggestion skipped: line range outside the PR's diff.

@Behzad-rabiei Behzad-rabiei merged commit e12d312 into main Jan 21, 2025
13 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant