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

docs: add example for handling authentication with useCookie in Nuxt docs #29538

Open
wants to merge 4 commits into
base: main
Choose a base branch
from

Conversation

AngeloSchulerPiletti
Copy link
Contributor

@AngeloSchulerPiletti AngeloSchulerPiletti commented Oct 15, 2024

🔗 Linked issue

I haven't found an issue for it, but this doc can be enhanced once #20652 is closed.

📚 Description

Adds an example to the Nuxt documentation demonstrating how to manage authentication tokens using the useCookie composable.

By providing a concrete use case for handling accessToken with cookies, this helps developers better understand how to manage authentication tokens in their Nuxt apps through a plugin. The example includes cookie configuration, login, and logout functionality, making it easier for users to implement token-based authentication in their projects.

This addition aims to improve the documentation by offering practical guidance on a common use case.

Summary by CodeRabbit

  • Documentation
    • Updated the useCookie composable documentation to include a new section on handling authentication with cookies.
    • Added examples for managing authentication tokens, including setting and retrieving access tokens.

Copy link

stackblitz bot commented Oct 15, 2024

Review PR in StackBlitz Codeflow Run & review this pull request in StackBlitz Codeflow.

@github-actions github-actions bot added the 3.x label Oct 15, 2024
@AngeloSchulerPiletti AngeloSchulerPiletti changed the title Add example for handling authentication with useCookie in Nuxt docs docs: Add example for handling authentication with useCookie in Nuxt docs Oct 15, 2024
@AngeloSchulerPiletti AngeloSchulerPiletti changed the title docs: Add example for handling authentication with useCookie in Nuxt docs docs: add example for handling authentication with useCookie in Nuxt docs Oct 28, 2024
Copy link

coderabbitai bot commented Nov 2, 2024

Walkthrough

The documentation for the useCookie composable has been updated to include a new section focused on handling authentication with cookies. This section provides examples for managing authentication tokens, including how to set and retrieve an access token within a Nuxt plugin. It details the creation of an accessToken cookie with the sameSite option set to strict, and outlines methods for user login and logout through the authentication store.

Changes

File Path Change Summary
docs/3.api/2.composables/use-cookie.md Added a new section on handling authentication with cookies, including examples for managing access tokens.

Possibly related PRs

Poem

In the garden of code, we hop and play,
With cookies for tokens, we find our way.
Authentication's dance, so smooth and neat,
A useCookie treat, oh what a feat!
With sameSite set, our tokens secure,
In the world of Nuxt, we happily endure! 🐇✨


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

🧹 Outside diff range and nitpick comments (1)
docs/3.api/2.composables/use-cookie.md (1)

239-266: Add usage examples to the documentation.

The plugin provides authentication methods but doesn't show how to use them in components or pages.

Consider adding an example of how to use these methods:

<script setup lang="ts">
const { $loginUser, $logout } = useNuxtApp()

async function handleLogin(credentials) {
  try {
    const user = await $fetch('/api/login', {
      method: 'POST',
      body: credentials
    })
    await $loginUser(user)
    await navigateTo('/dashboard')
  } catch (error) {
    // Handle login error
  }
}

async function handleLogout() {
  await $logout()
}
</script>
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between c0a8549 and b7f0369.

📒 Files selected for processing (1)
  • docs/3.api/2.composables/use-cookie.md (1 hunks)

Comment on lines +239 to +266
```ts [plugins/auth.ts]
export default defineNuxtPlugin(() => {
const nuxtApp = useNuxtApp()
const authStore = useAuthStore()
const accessToken = useCookie('accessToken', {
sameSite: 'strict',
})

return {
provide: {
getAccessToken() {
return accessToken.value
},
setAccessToken(accessToken: string) {
accessToken.value = accessToken
},
loginUser(user: User) {
nuxtApp.$setAccessToken(user.accessToken)
authStore.setUser(user)
},
logout() {
nuxtApp.$setAccessToken('')
authStore.logout()
},
},
}
})
```
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add TypeScript types and improve error handling.

The plugin implementation needs better type safety and error handling:

+interface User {
+  accessToken: string;
+  // add other user properties
+}
+
 export default defineNuxtPlugin(() => {
   const nuxtApp = useNuxtApp()
   const authStore = useAuthStore()
   const accessToken = useCookie('accessToken', {
     sameSite: 'strict',
+    httpOnly: true,
+    secure: process.env.NODE_ENV === 'production',
   })

   return {
     provide: {
-      getAccessToken() { 
+      getAccessToken(): string | null { 
         return accessToken.value
       },
-      setAccessToken(accessToken: string) { 
+      setAccessToken(token: string): void { 
         try {
-          accessToken.value = accessToken
+          accessToken.value = token
+        } catch (error) {
+          console.error('Failed to set access token:', error)
+          throw new Error('Authentication failed')
+        }
       },
-      loginUser(user: User) {
+      async loginUser(user: User): Promise<void> {
+        if (!user?.accessToken) {
+          throw new Error('Invalid user data')
+        }
         nuxtApp.$setAccessToken(user.accessToken)
         authStore.setUser(user)
       },
-      logout() {
+      async logout(): Promise<void> {
         nuxtApp.$setAccessToken('')
+        accessToken.value = null
         authStore.logout()
+        await navigateTo('/login')  // Redirect to login page
       },
     },
   }
 })

Also, consider adding JSDoc comments to document the usage of these methods:

/**
 * Returns the current access token from the cookie
 * @returns {string | null} The access token or null if not set
 */
getAccessToken(): string | null

/**
 * Sets the access token in the cookie
 * @param {string} token - The access token to store
 * @throws {Error} If the token cannot be set
 */
setAccessToken(token: string): void

Comment on lines +234 to +238

## Handling Authentication with Cookies

You can manage authentication tokens using cookies like this:

Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance the authentication section with security considerations and best practices.

The introduction should provide more context and security considerations for handling authentication tokens with cookies. Consider adding:

  • Explanation of why cookies are preferred over localStorage for token storage
  • CSRF protection recommendations when using cookies for authentication
  • Token expiration and refresh token patterns
  • Security implications of different cookie configurations

Here's a suggested expansion of the introduction:

 ## Handling Authentication with Cookies

-You can manage authentication tokens using cookies like this:
+Cookies are often preferred over localStorage for storing authentication tokens due to their enhanced security features and protection against XSS attacks. Here's how to implement secure cookie-based authentication:
+
+::warning
+When implementing authentication, consider these security best practices:
+- Use `httpOnly: true` to prevent XSS attacks from accessing the token
+- Implement CSRF protection for cookie-based authentication
+- Consider token expiration and refresh token patterns
+- Use secure configurations like `secure: true` in production
+::
📝 Committable 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. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
## Handling Authentication with Cookies
You can manage authentication tokens using cookies like this:
## Handling Authentication with Cookies
Cookies are often preferred over localStorage for storing authentication tokens due to their enhanced security features and protection against XSS attacks. Here's how to implement secure cookie-based authentication:
::warning
When implementing authentication, consider these security best practices:
- Use `httpOnly: true` to prevent XSS attacks from accessing the token
- Implement CSRF protection for cookie-based authentication
- Consider token expiration and refresh token patterns
- Use secure configurations like `secure: true` in production
::

Comment on lines +243 to +245
const accessToken = useCookie('accessToken', {
sameSite: 'strict',
})
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Strengthen cookie security configuration.

The cookie configuration is missing important security options that are crucial for storing authentication tokens.

 const accessToken = useCookie('accessToken', {
   sameSite: 'strict',
+  httpOnly: true,      // Prevent XSS attacks from accessing the token
+  secure: process.env.NODE_ENV === 'production',  // Require HTTPS in production
+  maxAge: 7200,        // Token expiration in seconds
+  path: '/',           // Cookie accessibility path
 })
📝 Committable 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. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const accessToken = useCookie('accessToken', {
sameSite: 'strict',
})
const accessToken = useCookie('accessToken', {
sameSite: 'strict',
httpOnly: true, // Prevent XSS attacks from accessing the token
secure: process.env.NODE_ENV === 'production', // Require HTTPS in production
maxAge: 7200, // Token expiration in seconds
path: '/', // Cookie accessibility path
})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants