Skip to content
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

Logout #22

Merged
merged 6 commits into from
Oct 1, 2024
Merged

Logout #22

merged 6 commits into from
Oct 1, 2024

Conversation

likui628
Copy link
Owner

@likui628 likui628 commented Oct 1, 2024

Summary by CodeRabbit

  • New Features

    • Introduced a new logout endpoint for user authentication.
    • Added a function to calculate token expiration based on specified duration.
    • Enhanced token management with the ability to save, delete, and retrieve tokens from the database.
  • Bug Fixes

    • Updated token handling during user registration and login processes to ensure proper asynchronous behavior.
  • Chores

    • Updated dependencies in the project configuration for improved functionality.

Copy link

coderabbitai bot commented Oct 1, 2024

Warning

Rate limit exceeded

@likui628 has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 13 minutes and 14 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Files that changed from the base of the PR and between 3c113ac and 27ecb51.

Walkthrough

The changes encompass updates to the authentication system, including modifications to token handling, the introduction of a logout feature, and enhancements to token management. The package.json file has been adjusted to reflect changes in dependencies. New functions have been added to manage token expiration and database interactions, while existing functions have been updated to support asynchronous operations.

Changes

File Change Summary
package.json Removed @types/bcrypt from dependencies, added it to devDependencies, and introduced date-fns as a new dependency.
src/controllers/auth.ts Updated handleTokens to be asynchronous and added a new logout function to manage token removal from cookies.
src/routes/v1/auth.ts Added a new POST route for /logout to handle user logout functionality.
src/services/token.ts Introduced saveToken, deleteToken, and getTokenInfo functions for managing tokens in the database. Updated generateAuthTokens to be asynchronous and save refresh tokens.
src/utils/misc.ts Added getTokenExpiration function to calculate token expiration dates based on duration.

Possibly related PRs

  • Saving tokens to the database #21: The changes in this PR involve modifications to the handleTokens function in src/controllers/auth.ts, which is also updated in the main PR to be asynchronous and handle token generation. Additionally, both PRs introduce the getTokenExpiration function in src/utils/misc.ts, linking them through their focus on token management.

Poem

🐰 In the code where tokens play,
A logout path has found its way.
With date-fns to mark the time,
Our tokens now will surely shine!
Async functions dance and twirl,
In this rabbit's coding world! 🐇


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 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: 2

🧹 Outside diff range and nitpick comments (5)
src/controllers/auth.ts (3)

6-7: LGTM! Consider adding error handling.

The change to make handleTokens an async function and await the token generation is correct. This aligns well with asynchronous best practices.

Consider adding a try-catch block to handle potential errors from tokenService.generateAuthTokens(user). This would improve error handling and make the function more robust.


32-54: Good implementation. Consider adding explicit error handling.

The logout function is well-implemented, covering various scenarios and consistently clearing the refresh token cookie. However, there are a few areas for improvement:

  1. Add explicit error handling for tokenService.getTokenInfo and tokenService.deleteToken calls.
  2. Consider using a constant for the cookie name to maintain consistency across the file.
  3. The success response is repeated three times, which could be refactored.

Here's a suggested refactoring that addresses these points:

const REFRESH_TOKEN_COOKIE = 'refreshToken';

export const logout = asyncHandler(async (req: Request, res: Response) => {
  const refreshToken = req.cookies[REFRESH_TOKEN_COOKIE];
  if (!refreshToken) {
    return successResponse(res, null, 200);
  }

  try {
    const foundToken = await tokenService.getTokenInfo(refreshToken);
    if (foundToken) {
      await tokenService.deleteToken(refreshToken);
    }
  } catch (error) {
    console.error('Error during logout:', error);
    // Optionally handle the error differently
  } finally {
    res.clearCookie(REFRESH_TOKEN_COOKIE, {
      httpOnly: true,
      secure: process.env.NODE_ENV === 'production',
    });
    return successResponse(res, null, 200);
  }
});

This refactoring:

  1. Adds try-catch for error handling.
  2. Uses a constant for the cookie name.
  3. Reduces repetition by always clearing the cookie and sending the success response.

Line range hint 1-54: Overall, good implementation of logout functionality and async improvements.

The changes in this file successfully implement the logout functionality and improve the asynchronous handling of tokens, aligning well with the PR objectives. The modifications to handleTokens, register, and login functions ensure consistent async behavior, while the new logout function provides a comprehensive logout mechanism.

To further enhance the code:

  1. Consider implementing the suggested refactoring for the logout function.
  2. Add error handling in the handleTokens function.
  3. Ensure that all token-related operations (generation, retrieval, deletion) are properly logged for auditing purposes.

As the authentication system grows, consider implementing a separate middleware for token validation and refresh, which could be used across different routes requiring authentication.

src/services/token.ts (2)

Line range hint 24-39: Consider handling the case when token generation fails.

The generateAuthTokens function should handle the scenario where token generation fails. You can wrap the token generation and saving logic in a try-catch block to catch any potential errors and handle them appropriately.

Here's an example of how you can modify the function to handle errors:

export const generateAuthTokens = async (user: User) => {
  try {
    const payload = { id: user.id, username: user.name, role: user.role }
    const token = jwt.sign(payload, env.ACCESS_TOKEN_SECRET, {
      expiresIn: '1h',
    })

    const refreshToken = jwt.sign(payload, env.REFRESH_TOKEN_SECRET, {
      expiresIn: '7d',
    })

    await saveToken(
      refreshToken,
      user.id,
      getTokenExpiration(7, 'days'),
      TokenType.REFRESH,
    )

    return { token, refreshToken }
  } catch (error) {
    console.error('Error generating auth tokens:', error)
    throw error
  }
}

51-59: Consider returning null when the token is not found.

The getTokenInfo function should handle the case when the token is not found in the database. Instead of returning undefined, you can explicitly return null to indicate that the token was not found.

Here's an example of how you can modify the function:

export const getTokenInfo = async (token: string) => {
  const tokenInfo = await prisma.token.findFirst({
    where: {
      token,
    },
  })

  return tokenInfo ?? null
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between b3a8b7a and 3c113ac.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (5)
  • package.json (2 hunks)
  • src/controllers/auth.ts (2 hunks)
  • src/routes/v1/auth.ts (1 hunks)
  • src/services/token.ts (2 hunks)
  • src/utils/misc.ts (1 hunks)
🔇 Additional comments (9)
src/utils/misc.ts (2)

1-1: LGTM: Import statement is correct.

The import statement correctly imports the necessary functions from the 'date-fns' library.


3-11: 🛠️ Refactor suggestion

Consider enhancing error handling and type safety.

The getTokenExpiration function is well-implemented, but there are a few areas for improvement:

  1. The error message could be more specific. Consider including the valid range for val.
  2. Add a runtime check for valid duration keys to prevent potential runtime errors.
  3. Explicitly define the return type of the function for better type safety.

Here's a suggested implementation with these improvements:

import { add, Duration } from 'date-fns'

export const getTokenExpiration = (
  val: number,
  duration: keyof Duration = 'days',
): Date => {
  if (val <= 0) {
    throw new Error('Duration value must be a positive number greater than 0')
  }
  
  const validDurations: (keyof Duration)[] = ['years', 'months', 'weeks', 'days', 'hours', 'minutes', 'seconds']
  if (!validDurations.includes(duration)) {
    throw new Error(`Invalid duration: ${duration}. Must be one of ${validDurations.join(', ')}`)
  }

  return add(new Date(), { [duration]: val })
}

This implementation:

  1. Improves the error message for invalid val.
  2. Adds a runtime check for valid duration keys.
  3. Explicitly defines the return type as Date.

To ensure this function is used correctly throughout the codebase, we can run the following check:

This will help identify any potential misuse of the function in other parts of the codebase.

✅ Verification successful

Usage of getTokenExpiration is correctly implemented in src/services/token.ts. No further issues found.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for proper usage of getTokenExpiration function

# Test: Search for function calls to getTokenExpiration
echo "Checking usage of getTokenExpiration:"
rg --type typescript "getTokenExpiration\(" -A 2

Length of output: 170


Script:

#!/bin/bash
# Description: Recheck usage of getTokenExpiration function in TypeScript (.ts) files

# Test: Search for function calls to getTokenExpiration in .ts files
echo "Rechecking usage of getTokenExpiration in .ts files:"
rg "getTokenExpiration\(" -g "*.ts" -A 2

Length of output: 285

src/routes/v1/auth.ts (2)

Line range hint 1-23: Overall, good addition of logout functionality.

The changes to this file are minimal and focused on adding the logout functionality. The implementation is consistent with the existing code structure and follows the established patterns for route definition.

To further improve the implementation:

  1. Consider adding authentication middleware to the logout route.
  2. Ensure that the authController.logout method handles token invalidation or session termination properly.
  3. Update any relevant documentation or API specifications to include the new logout endpoint.

20-21: Good addition of logout functionality, consider adding authentication middleware.

The addition of a logout route is a good improvement to the authentication system. However, there are a few considerations:

  1. Consider adding authentication middleware to ensure only authenticated users can access this route. This prevents potential misuse of the logout functionality.

  2. Verify if any validation is needed for the logout request. If no request body is expected, the current implementation is fine. Otherwise, consider adding validation similar to the login and register routes.

To ensure proper implementation of the logout functionality, let's verify the authController.logout method:

src/controllers/auth.ts (2)

19-19: LGTM! Proper async handling.

The change to await handleTokens is correct and consistent with the updates made to the handleTokens function. This ensures that the token is properly generated before sending the response.


27-27: LGTM! Consistent async handling.

The change to await handleTokens in the login function is correct and consistent with the updates made to both the handleTokens function and the register function. This ensures proper token generation before sending the response.

package.json (2)

28-28: LGTM: Addition of date-fns library

The addition of the date-fns library (version 4.1.0) is a good choice. This library is commonly used for date manipulation in JavaScript and could be beneficial for handling token expiration in the authentication system updates mentioned in the PR objectives.


42-42: LGTM: Moving @types/bcrypt to devDependencies

Adding @types/bcrypt to the devDependencies is a good practice. Type definitions are only needed during development and not in production, so this move helps to keep the production dependencies lean.

src/services/token.ts (1)

Line range hint 1-59: Verify the usage of the new token-related functions in the codebase.

The changes introduce new functions for token management, such as saveToken, deleteToken, and getTokenInfo. It's important to ensure that these functions are being used correctly throughout the codebase.

Here's a script to help verify the usage of these functions:

Review the search results to ensure that the functions are being called with the correct arguments and in the appropriate contexts.

✅ Verification successful

New token-related functions are correctly implemented and used in the codebase.

The verification process has confirmed that the new token-related functions (saveToken, deleteToken, and getTokenInfo) are being used correctly throughout the codebase:

  • saveToken is properly defined in src/services/token.ts and used within the generateAuthTokens function with the correct arguments.
  • deleteToken is defined in src/services/token.ts and utilized in src/controllers/auth.ts, likely for user logout or token revocation purposes.
  • getTokenInfo is defined in src/services/token.ts and used in src/controllers/auth.ts, probably for token validation or refresh operations.

The implementation and usage of these functions appear to be consistent with their intended purposes and are correctly integrated into the authentication flow.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash

# Search for the usage of saveToken function
echo "Verifying saveToken usage:"
rg --type typescript -A 5 $'saveToken'

# Search for the usage of deleteToken function  
echo "Verifying deleteToken usage:"
rg --type typescript -A 5 $'deleteToken'

# Search for the usage of getTokenInfo function
echo "Verifying getTokenInfo usage:"  
rg --type typescript -A 5 $'getTokenInfo'

Length of output: 422


Script:

#!/bin/bash

# Search for the usage of saveToken function
echo "Verifying saveToken usage:"
rg 'saveToken' -g '*.ts' -A 5

# Search for the usage of deleteToken function  
echo "Verifying deleteToken usage:"
rg 'deleteToken' -g '*.ts' -A 5

# Search for the usage of getTokenInfo function
echo "Verifying getTokenInfo usage:"  
rg 'getTokenInfo' -g '*.ts' -A 5

Length of output: 2039

Comment on lines 7 to 22
export const saveToken = async (
token: string,
userId: User['id'],
expires: Date,
type: TokenType = TokenType.REFRESH,
) => {
const newToken = await prisma.token.create({
data: {
userId,
token,
type,
expires,
},
})
return newToken
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Ensure the saveToken function handles potential errors.

The saveToken function should handle potential errors that may occur during the token creation process. Consider wrapping the Prisma query in a try-catch block to catch and handle any errors gracefully.

Here's an example of how you can modify the function to handle errors:

export const saveToken = async (
  token: string,
  userId: User['id'],
  expires: Date,
  type: TokenType = TokenType.REFRESH,
) => {
  try {
    const newToken = await prisma.token.create({
      data: {
        userId,
        token,
        type,
        expires,
      },
    })
    return newToken
  } catch (error) {
    console.error('Error saving token:', error)
    throw error
  }
}

Comment on lines 43 to 49
export const deleteToken = async (token: string) => {
await prisma.token.delete({
where: {
token,
},
})
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Handle the case when the token doesn't exist.

The deleteToken function should handle the scenario where the token being deleted doesn't exist in the database. You can use Prisma's deleteMany method instead of delete to avoid throwing an error if the token doesn't exist.

Here's an example of how you can modify the function:

export const deleteToken = async (token: string) => {
  await prisma.token.deleteMany({
    where: {
      token,
    },
  })
}

@likui628 likui628 merged commit b68059d into main Oct 1, 2024
3 checks passed
@likui628 likui628 deleted the logout branch October 1, 2024 07:01
This was referenced Oct 1, 2024
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