coderoyalty / pseudonym-app

An anonymous messaging application
https://pseudonym-app.vercel.app
MIT License
2 stars 0 forks source link

Integrate Authentication Feature #14

Closed coderoyalty closed 8 months ago

coderoyalty commented 8 months ago

Summary by CodeRabbit

vercel[bot] commented 8 months ago

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Updated (UTC)
pseudonym ✅ Ready (Inspect) Visit Preview Feb 16, 2024 4:50pm
coderoyalty commented 8 months ago

Closes #13

coderoyalty commented 5 months ago

@coderabbitai review commit 03b89e8

coderabbitai[bot] commented 5 months ago

@coderoyalty, I reviewed the commit abb118e which implements the authentication provider. Here are the key changes:

  1. App Component Update:

    • Wrapped the application with AuthProvider to manage authentication state.
      function App() {
      return (
      <>
       <AuthProvider>
         <Theme>
           <BrowserRouter>
             <Router />
           </BrowserRouter>
         </Theme>
       </AuthProvider>
      </>
      );
      }
  2. Axios Configuration:

    • Created a new Axios instance with the base URL and withCredentials option.
      
      import { config } from "@/utils/config";
      import _axios from "axios";

    const axios = _axios.create({ baseURL: config.BACKEND_URL, withCredentials: true, });

    export default axios;

  3. AuthProvider Component:

    • Implemented AuthProvider to manage user authentication state and provide context.
    • Added an AuthObserver class to handle authentication-related events.
    • Configured Axios interceptors to handle unauthorized responses.
      
      import axios from "@/api/axios";
      import { AxiosError } from "axios";
      import React from "react";

    export interface AuthContextType<T = any> { user: T; isLoggedIn: boolean; signin: (user: T) => void; signout: () => void; observer: AuthObserver; }

    const AuthContext = React.createContext(null!);

    interface IUser { id: string; email: string; }

    export enum ObserverType { UNAUTHORIZED = "unauthorized", SERVER_ERROR = "server_error", }

    class AuthObserver<T = string> { private observers: Map<T, VoidFunction[]> = new Map();

    subscribe(eventType: T, callback: VoidFunction) { const callbacks = this.observers.get(eventType); if (!callbacks) { this.observers.set(eventType, [callback]); return; } if (callbacks.find((value) => value.name === callback.name)) { return; } callbacks.push(callback); }

    async trigger(eventType: T) { const callbacks = this.observers.get(eventType); if (!callbacks) { return; } const promises = callbacks.map((callback) => callback()); await Promise.all(promises); } }

    export const AuthProvider = ({ children }: { children: React.JSX.Element }) => { const [user, setUser] = React.useState<IUser | null>(null); const [isLoggedIn, setLoggedIn] = React.useState(false);

    const observer = new AuthObserver();

    const signin = (user: any) => { setUser(user); setLoggedIn(true); };

    const signout = () => { setLoggedIn(false); setUser(null); };

    const value = { user, isLoggedIn, signin, signout, observer, };

    axios.interceptors.response.use( (response) => { return response; }, function (error) { if (error instanceof AxiosError) { if (error.response?.status === 401) { observer.trigger(ObserverType.UNAUTHORIZED); } } else { console.error(error); } return Promise.reject(error); } );

    return {children}</AuthContext.Provider>; };

    export const useAuth = () => { const auth = React.useContext(AuthContext); return auth; };

  4. Configuration File:

    • Added a configuration file to manage environment variables.
      export const config = {
      BACKEND_URL: import.meta.env.VITE_BACKEND_URL,
      };

The implementation looks solid, providing a comprehensive authentication context and handling unauthorized responses effectively. If you need any further adjustments or have specific questions, feel free to ask!

Analysis chain --- ---
Scripts executed The following scripts were executed for the analysis: --- Script: ```shell #!/bin/bash # Fetch the details of the commit 03b89e8 git show 03b89e8 ``` Length of output: 206 --- --- Script: ```shell #!/bin/bash # List the recent commits to find the correct commit hash git log --oneline -n 20 ``` Length of output: 1417 --- --- Script: ```shell #!/bin/bash # Fetch the details of the commit abb118e git show abb118e ``` Length of output: 4236
Actions Performed Review triggered. > Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.
coderabbitai[bot] commented 5 months ago

Walkthrough

This update introduces significant improvements to the application's authentication, user interface, and state management. Key additions include new dependencies for toast notifications, Axios for API calls, and loading spinners. The App component is refactored to support authentication context, and new components like ScreenLoader, ProtectedRoute, and toast notifications enhance user experience. Various components and hooks are updated to manage authentication, API interactions, and conditional rendering based on user state.

Changes

File/Path Change Summary
app/package.json Added dependencies for @radix-ui/react-toast, axios, and react-spinners.
app/src/App.tsx Refactored App component for authentication context, added AuthProvider, useAuth, and Toaster.
app/src/api/axios.ts Introduced Axios instance configuration for backend API requests.
app/src/components/ScreenLoader.tsx Added ScreenLoader component with loading spinner and optional info text.
app/src/components/auth-form/... Updated auth-form, login-form, and signup-form for state management, API calls, and toast notifications.
app/src/components/dashboard/... Updated home, layout, protected-route, route, and sidebar for authentication and user state handling.
app/src/components/header/navlink.tsx Added useAuth hook to conditionally set navigation based on user authentication status.
app/src/components/message-carousel.tsx Updated MessageCarousel to handle messages as objects with content and id properties.
app/src/components/message/message-form.tsx Modified MessageForm for async submission with Axios and toast notifications.
app/src/components/ui/toast.tsx Introduced components for customizable toast notifications.
app/src/components/ui/toaster.tsx Added Toaster component to render toast notifications.
app/src/components/ui/use-toast.ts Introduced custom toast notification system with useToast hook.
app/src/contexts/auth.observer.ts Added AuthObserver class for managing event subscriptions and triggers.
app/src/contexts/auth.tsx Introduced authentication context, AuthProvider, and useAuth hook for user state management.
app/src/hooks/useLocalStorage.ts Added useLocalStorage hook for managing local storage operations.
app/src/pages/AuthPage.tsx Updated to check for authenticated user and navigate to /dashboard if present.
app/src/pages/message-page.tsx Enhanced to fetch user data, handle messaging restrictions, and display loading or error states.
app/src/utils/config.ts Added config to store BACKEND_URL from environment variables.

In code's embrace, the app did grow,
With toasts and loaders, a smoother flow.
Auth and Axios, hand in hand,
Bringing joy to every land.
🐇✨
A rabbit's touch, in every line,
Making sure the app's divine.


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 - [X](https://twitter.com/intent/tweet?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A&url=https%3A//coderabbit.ai) - [Mastodon](https://mastodon.social/share?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A%20https%3A%2F%2Fcoderabbit.ai) - [Reddit](https://www.reddit.com/submit?title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&text=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code.%20Check%20it%20out%3A%20https%3A//coderabbit.ai) - [LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fcoderabbit.ai&mini=true&title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&summary=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code)
Tips ### Chat There are 3 ways to chat with [CodeRabbit](https://coderabbit.ai): - Review comments: Directly reply to a review comment made by CodeRabbit. Example: - `I pushed a fix in commit .` - `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 generate interesting stats about this repository and render them as a table.` - `@coderabbitai show all the console.log statements in this repository.` - `@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.` 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) - `@coderabbitai pause` to pause the reviews on a PR. - `@coderabbitai resume` to resume the paused reviews. - `@coderabbitai review` to trigger a review. This is useful when automatic reviews are disabled for the repository. - `@coderabbitai resolve` resolve all the CodeRabbit review comments. - `@coderabbitai help` to get help. Additionally, you can add `@coderabbitai ignore` anywhere in the PR description to prevent this PR from being reviewed. ### CodeRabbit Configration 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](https://docs.coderabbit.ai/guides/configure-coderabbit) 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](https://coderabbit.ai/docs) for detailed information on how to use CodeRabbit. - Join our [Discord Community](https://discord.com/invite/GsXnASn26c) to get help, request features, and share feedback. - Follow us on [X/Twitter](https://twitter.com/coderabbitai) for updates and announcements.