Skip to content

Feat: Authentication to Tauri and Web simulator #554

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

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

Conversation

ThatDeparted2061
Copy link
Member

@ThatDeparted2061 ThatDeparted2061 commented Apr 28, 2025

Implemented the Authentication model for the Desktop and the Vue simulator

Fixes #557

Describe the changes you have made in this PR -

Screenshot from 2025-06-14 17-49-26
Screenshot from 2025-06-14 17-50-01

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Introduced an authentication modal for sign-in and registration, allowing users to log in or register without leaving the current page.
    • Added inline error notifications for authentication actions via a snackbar component.
    • Users can toggle between login and registration modes within the modal.
    • Added user join date display in the avatar menu.
    • Locale selector restyled with translucent background and white text.
  • Improvements

    • Authentication now uses asynchronous API calls with real-time feedback.
    • Sign-out now updates the user state immediately without redirecting.
    • Enhanced user state management with token decoding and automatic session handling.
    • Drawer width fixed with a close button for improved navigation.
    • Replaced navigation-based authentication flow with a modal-based approach.
  • Style

    • Updated UI with new modal and form styles for a smoother authentication experience.
    • Added new user menu styles with semi-transparent backgrounds, blur effects, and consistent white-themed elements.

Copy link
Contributor

coderabbitai bot commented Apr 28, 2025

"""

Walkthrough

The changes refactor the authentication flow in the user interface by replacing direct navigation to sign-in and registration pages with a modal dialog for authentication. The modal supports both login and registration, handling form submissions with asynchronous API calls and providing inline user feedback via a snackbar component. The authentication state management in the store is extended with new actions to set the token and sign out, updating user information and resetting state as needed. The sign-out process is also changed to use the store's method instead of redirecting. UI elements and logic are updated to accommodate these new behaviors.

Changes

Files/Paths Change Summary
src/components/Navbar/User/UserMenu.vue Refactored authentication to use a modal dialog for login/register instead of navigation; added reactive state, modal, and snackbar for feedback; updated sign-out to use store method; UI and logic updated accordingly.
src/store/authStore.ts Added setToken and signOut actions to manage authentication state via token decoding and state reset; complements existing user info management.
src/components/Navbar/User/User.scss Added new SCSS stylesheet for user menu styling including modal, avatar, and locale selector styles with a white-on-transparent theme.

Assessment against linked issues

Objective Addressed Explanation
Implement authentication with modal-based login and registration UI instead of navigation (#557)
Handle authentication API calls asynchronously with proper form validation and error handling (#557)
Extend auth store with token-based login state setting and sign-out state reset (#557)
Change sign-out flow to use store method instead of page redirect (#557)

Assessment against linked issues: Out-of-scope changes

No out-of-scope changes detected. All code modifications relate directly to the authentication feature requirements described in the linked issue #557.

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

npm error Exit handler never called!
npm error This is an error with npm itself. Please report this error at:
npm error https://github.com/npm/cli/issues
npm error A complete log of this run can be found in: /.npm/_logs/2025-06-14T12_59_47_373Z-debug-0.log


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this 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

netlify bot commented Apr 28, 2025

Deploy Preview for circuitverse ready!

Name Link
🔨 Latest commit 48c89c2
🔍 Latest deploy log https://app.netlify.com/projects/circuitverse/deploys/686161c644a1c00008c4826c
😎 Deploy Preview https://deploy-preview-554--circuitverse.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.
Lighthouse
Lighthouse
1 paths audited
Performance: 47 (no change from production)
Accessibility: 72 (no change from production)
Best Practices: 92 (no change from production)
SEO: 80 (no change from production)
PWA: -
View the detailed breakdown and full score reports

To edit notification comments on pull requests, go to your Netlify project configuration.

Copy link
Contributor

@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

🧹 Nitpick comments (3)
src/store/authStore.ts (1)

83-84: Open TODO warrants tracking ticket

The // TODO: extract store verify and check better ways to impliment comment is vague and easy to forget. Consider opening an issue that precisely describes what must be improved (token verification, persistence strategy, typings, etc.) so it can be prioritised.

src/components/Navbar/User/UserMenu.vue (2)

233-242: Hard-coded localhost URLs hinder production builds & Tauri packages

Endpoints are currently fixed to http://localhost:4000/....
This will fail in production, in the web simulator behind a different origin, and in a Tauri-packaged desktop app.

-const url = isLoginMode.value
-  ? 'http://localhost:4000/api/v1/auth/login'
-  : 'http://localhost:4000/api/v1/auth/signup'
+const base = import.meta.env.VITE_API_BASE_URL ?? 'https://api.circuitverse.org/'
+const url  = isLoginMode.value
+  ? `${base}/api/v1/auth/login`
+  : `${base}/api/v1/auth/signup`

Also add credentials:'include' if you later switch to cookie-based sessions.


314-315: Logging out leaves stale token in storage

You’ve wired authStore.signOut(), but if the JWT was persisted (e.g., localStorage to survive refreshes) it should be removed here as well—otherwise the next page load will automatically set the user back to logged-in.

function signout() {
   authStore.signOut()
+  localStorage.removeItem('jwt')
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 31c8a47 and 27a2b3d.

📒 Files selected for processing (2)
  • src/components/Navbar/User/UserMenu.vue (2 hunks)
  • src/store/authStore.ts (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Analyze (javascript)

Copy link
Contributor

@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: 1

🧹 Nitpick comments (2)
src/components/Navbar/User/UserMenu.vue (2)

270-275: Consider more detailed error logging

While the catch block handles errors, the console.error could provide more context to help with debugging.

- console.error('Authentication error:', error)
+ console.error('Authentication error:', { error, email: email.value ? '[REDACTED]' : 'empty', formMode: isLoginMode.value ? 'login' : 'register' })

297-303: Simplify snackbar type handling

The snackbar type logic could be more flexible to support additional notification types.

function showSnackbar(message: string, type: string) {
  snackbar.value = {
    visible: true,
    message,
-   color: type === 'error' ? 'error' : 'success'
+   color: type
  }
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 27a2b3d and 11feed0.

📒 Files selected for processing (2)
  • src/components/Navbar/User/UserMenu.vue (2 hunks)
  • src/store/authStore.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/store/authStore.ts
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Analyze (javascript)
🔇 Additional comments (10)
src/components/Navbar/User/UserMenu.vue (10)

44-59: Good implementation of authentication modal triggers

The refactoring from direct navigation to a modal-based approach is a good improvement that keeps users in context. The implementation properly sets the authentication mode and manages the drawer state.


115-171: Modal implementation follows good practices

The authentication modal is well-structured with appropriate form validation, conditional rendering based on mode, and proper button states for loading feedback. This enhances user experience by providing immediate visual feedback.


173-188: Good implementation of feedback mechanism

The snackbar component provides clear user feedback for both successful operations and errors, which is essential for a good UX. The timeout and close button give users control over notifications.


200-213: Well-structured reactive state

The reactive state variables are clearly defined and organized logically. The snackbar state object is well-designed with all necessary properties grouped together.


251-256: Error handling implementation looks good

The error handling has been properly implemented according to previous review comments. The code now safely parses JSON responses and falls back gracefully when receiving non-JSON responses.


258-269: Token management and success handling

The authentication success flow is well implemented. It properly:

  1. Sets the authentication token in the store
  2. Displays success feedback
  3. Clears form fields
  4. Closes the modal

This creates a smooth user experience.


278-295: Good error handling with specific messages

The error handling function properly categorizes different error scenarios and displays appropriate messages to guide the user. This is a good practice for improving user experience.


314-316: Sign out implementation improved

The sign out implementation has been improved to use the store's method instead of a redirect. This is a better approach for maintaining consistent state management.


359-403: Well-organized styles

The modal styles are well-organized and use proper specificity. The dark theme styling looks good and maintains consistency with the rest of the UI.


225-276:

❌ Incorrect review comment

Consider adding CSRF protection for authentication requests

For improved security, consider adding CSRF token protection to your authentication requests.

You could implement CSRF protection like this:

const response = await fetch(url, {
  method: 'POST',
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json',
+   'X-CSRF-Token': document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '',
  },
  body: JSON.stringify(body),
})

🌐 Web query:

Is CSRF protection necessary for authentication endpoints?

💡 Result:

Yes, CSRF protection is necessary for authentication endpoints, despite some common misconceptions about this topic. While it might seem that CSRF protection is only needed after a user is authenticated, there are important security considerations for login forms as well.

Why Login Forms Need CSRF Protection

Protection Against Login CSRF Attacks

A login CSRF attack occurs when an attacker tricks a victim into logging into a website using the attacker's credentials without their knowledge[6][7]. This type of attack can have serious consequences:

  1. The attacker can track the victim's activities within the application
  2. The attacker may gain access to the victim's personal information or stored financial data
  3. The attacker could potentially perform actions on behalf of the victim, such as making purchases using stored payment methods[3]

Framework Recommendations

Many security-focused frameworks explicitly include CSRF protection for login endpoints:

  • Spring Security protects against CSRF attacks by default for login requests[5]
  • Django documentation emphasizes protection against "login CSRF" attacks where users might be tricked into logging in with someone else's credentials[8]

Implementation Approaches

For authentication endpoints, CSRF protection can be implemented using several methods:

Synchronizer Token Pattern (STP) is the most common approach for protecting against CSRF attacks. This involves generating a unique token that must be included with form submissions[10].

Double Submit Cookie Pattern uses a cryptographically strong random value both as a cookie and as a request parameter. The server verifies that these values match before processing the request[1].

For login forms specifically:

  • Generate a CSRF token before the user authenticates
  • Include the token in the login form
  • Verify the token server-side before processing login credentials

Special Considerations for APIs

For REST APIs, CSRF protection requirements depend on the authentication method:

  • APIs using token authentication typically don't need CSRF protection unless the token is stored in a cookie[7]
  • If using cookie-based authentication for APIs, CSRF protection becomes necessary

Conclusion

CSRF protection for authentication endpoints is an important security measure that prevents attackers from forcing users to log in with malicious credentials. While the specific implementation may vary based on your application architecture, including CSRF protection for login forms is considered a security best practice by major frameworks and security organizations.

Citations:


Ignore CSRF token for this JSON-based login request

This endpoint accepts only JSON and returns a token that’s stored client-side (not in cookies), so it isn’t vulnerable to CSRF. You can safely omit the X-CSRF-Token header and keep your current implementation.

Likely an incorrect or invalid review comment.

@ThatDeparted2061 ThatDeparted2061 changed the title chore: add Authentication to Tauri and Web simulator Feat: Authentication to Tauri and Web simulator Apr 28, 2025
@ThatDeparted2061
Copy link
Member Author

@ThatDeparted2061
Copy link
Member Author

I ll perform some more tests on this, while @aryanndwi123 @Arnabdaz let me know the update on the api changes i need to do

Copy link
Contributor

@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: 1

♻️ Duplicate comments (1)
src/components/Navbar/User/UserMenu.vue (1)

293-301: Hard-coded API base URL resurfaced

The login / signup endpoints are still pinned to http://localhost:4000/*. This breaks in prod/staging and was already called out previously. Please read the earlier suggestion and move the base URL to a central config or env variable.

🧹 Nitpick comments (1)
src/components/Navbar/User/UserMenu.vue (1)

230-237: v-btn icon prop misuse – icon may not render

<v-btn ... :icon="mdiClose"> expects a boolean or string when icon style is required.
Here you only need a close icon inside the button:

-<v-btn
-  variant="text"
-  @click="snackbar.visible = false"
-  :icon="mdiClose"
-  color="white"
-></v-btn>
+<v-btn variant="text" @click="snackbar.visible = false" icon color="white">
+  <v-icon :icon="mdiClose" />
+</v-btn>

Prevents Vuetify prop warning and guarantees the icon shows up.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 11feed0 and f49dc69.

📒 Files selected for processing (2)
  • src/components/Navbar/User/User.scss (1 hunks)
  • src/components/Navbar/User/UserMenu.vue (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • src/components/Navbar/User/User.scss
🔇 Additional comments (1)
src/components/Navbar/User/UserMenu.vue (1)

350-356:

❌ Incorrect review comment

JWT storage strategy unclear ‑ verify XSS exposure

authStore.setToken(data.token) blindly hands the raw JWT to the store. If the store persists it in localStorage, any XSS compromise grants full account takeover. Evaluate:

  1. Prefer HttpOnly secure cookies issued by the backend.
  2. If you must keep the token client-side, at least place it in sessionStorage, add XSS mitigation (CSP, strict sanitisation) and rotate tokens frequently.

🏁 Script executed:

#!/bin/bash
# Locate occurrences of setToken and inspect related store implementation
rg -n "setToken" -C2 src

Length of output: 714


🏁 Script executed:

#!/bin/bash
# Display the authStore implementation to see how the token is stored
sed -n '1,100p' src/store/authStore.ts

Length of output: 2654


authStore.setToken does not persist the JWT

The setToken action merely decodes the JWT payload and updates in-memory state—it does not write the token to localStorage (or sessionStorage). As a result, the XSS risk outlined around client-side storage does not apply here.

If you later introduce persistent storage for the token (e.g. to survive page reloads), consider switching to HttpOnly secure cookies issued by the backend or, at minimum, using sessionStorage with strong CSP and token rotation.

Likely an incorrect or invalid review comment.

Comment on lines 358 to 368
function dashboard() {
window.location.href = `/users/${authStore.getUserId}`
}

function my_groups() {
window.location.href = `/users/${authStore.getUserId}/groups`
}

function notifications() {
window.location.href = `/users/${authStore.getUserId}/notifications`
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Use the router instead of window.location.href

Direct page reloads defeat SPA benefits (state loss, slower navigation). Replace with Vue-Router:

-import router from '@/router'   // wherever your router lives
-
-function dashboard() {
-  window.location.href = `/users/${authStore.getUserId}`
-}
+function dashboard() {
+  router.push({ name: 'user-dashboard', params: { id: authStore.getUserId } })
+}

Apply the same change to my_groups() and notifications().

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

🤖 Prompt for AI Agents
In src/components/Navbar/User/UserMenu.vue lines 358 to 368, replace all
instances of direct URL assignment using window.location.href in the
dashboard(), my_groups(), and notifications() functions with Vue-Router
navigation methods. Use the router's push method to navigate programmatically to
the respective routes, ensuring SPA benefits like state preservation and faster
navigation without full page reloads.

Comment on lines +330 to +334

function handleLoginError(status: number, errorData: any) {
switch (status) {
case 401:
showSnackbar('Invalid credentials', 'error')
Copy link
Member

@niladrix719 niladrix719 Jun 14, 2025

Choose a reason for hiding this comment

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

This function should be in some common folder like utils, and may be instead of login make it generic

@tachyons
Copy link
Member

UI for the sign in model looks weird, use the same UI/UX pattern, do not introduce new colours or other UI elements

@ThatDeparted2061
Copy link
Member Author

UI for the sign in model looks weird, use the same UI/UX pattern, do not introduce new colours or other UI elements

okay

@ThatDeparted2061
Copy link
Member Author

@senbo1 Could you help me out with a better UI here if you have time?

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.

Feature : Authentication for simulator - Web and Tauri
3 participants