0.0.4 • Published 1 year ago

@airsoko/auth v0.0.4

Weekly downloads
-
License
UNLICENSED
Repository
-
Last release
1 year ago

Airsoko auth package

📑 Table of Contents

Overview

The npm package provides essential utilities for handling authentication within the Airsoko application.

Installation

npm install @airsoko/auth

Prerequisites

  • Node.js (version 16 or higher)
  • npm (or yarn)

Uninstalling

If you wish to uninstall Airsoko next, use:

npm uninstall  @airsoko/auth

API Reference

Example

Step 1: Wrap the Application with AuthProvider

To enable authentication within your React application, you need to wrap it with the AuthProvider component provided by the Macive Auth package. This component sets up the necessary authentication context, allowing your components to access authentication-related information.

Here's an example of how to use the AuthProvider:

import { AuthProvider } from "@airsoko/auth;

<AuthProvider
  domain='my-shop.airsoko.com'
  clientId="YOUR_AUTH_CLIENT_ID"
  redirectUri='https://my-shop.airsoko.com'
  audience="CUSTOMER"
>
  {/* Your application components */}
</AuthProvider>

Parameters:

  • domain: The Airsoko domain associated with your application. .

  • clientId: Your Airsoko client ID. Replace "YOUR_AUTH0_CLIENT_ID" with the actual client ID for your application.

  • redirectUri: The URI to which the user will be redirected after authentication. It is usually set to the application's domain or https://my-shop.airsoko.com/my-auth-dwstination'.

  • audience: The audience parameter for Auth0, typically representing the target audience for authentication. In this example, it is set to "CUSTOMER".

Step 2: Authentication Hook use with useAuth

The useAuth hook provides a convenient way to integrate authentication functionalities into your React application. This hook allows you to access user information, check authentication status, and perform actions based on the authentication state.

Usage Example: Private Route Component

Here's an example of how you can use the useAuth hook to create a private route component using Next.js:

import { useAuth } from "@airsoko/auth";
import Link from "next/link";
import React from "react";

type AuthPropsType = {
  permissions?: string[];
};

interface PrivateRouteProps {
  authProps: AuthPropsType;
  children: React.ReactNode;
}

const PrivateRoute: React.FC<PrivateRouteProps> = ({ children, authProps }) => {
  const { user, goLogin, sessionLoading, isAuthenticated } = useAuth();
  const isUser = user?.id;

  React.useEffect(() => {
    if (!sessionLoading) {
      if (!isAuthenticated) {
        if (!isUser) goLogin();
      } else {
        // Additional logic for authenticated users, if needed.
      }
    }
  }, [isUser, sessionLoading]);

  // If the user is authenticated and has the required permissions.
  // Replace with your own permission checking logic if needed.
  if (isUser) {
    // Render the protected content.
    return <>{children}</>;
  }

  // Session is being fetched, or no user.
  // If no user, useEffect() will redirect to the login page.
  return <GlobalLoader />;
};

Functions

1. goLogin Function - Redirect to Login

The goLogin function is designed to redirect users to the login page. This function can be useful in scenarios where you want to ensure users are authenticated before accessing certain parts of your application.

import { useAuth } from "@airsoko/auth";

const YourComponent: React.FC = () => {
  const { goLogin } = useAuth();

  const handleLoginButtonClick = () => {
    goLogin();
  };

  return (
    <div>
      <p>Welcome to your application!</p>
      <button onClick={handleLoginButtonClick}>Login</button>
    </div>
  );
};

2. signIn Function - Sign In and Redirect

The signIn function is designed to sign in the user to the application using a provided token and redirect them to a specific destination. This function is useful when you want to handle custom authentication logic and redirect users after successful sign-in.

import { useAuth } from "@airsoko/auth";

const YourComponent: React.FC = () => {
  const { signIn } = useAuth();

  const handleSignInButtonClick = async () => {
    try {
      // Perform your authentication logic to obtain a token.
      const authToken = "YOUR_OBTAINED_TOKEN";

      // Use the signIn function to sign in the user and redirect.
      await signIn(authToken);

      // After successful sign-in, the user will be redirected.
    } catch (error) {
      console.error("Authentication failed:", error);
      // Handle authentication failure.
    }
  };

  return (
    <div>
      <p>Welcome to your application!</p>
      <button onClick={handleSignInButtonClick}>Sign In</button>
    </div>
  );
};

3. logout Function - Log Out User

The logout function is designed to log out the user from the application. This function can be used to initiate the logout process, which may include clearing session data and redirecting the user to a specified destination.

import { useAuth } from "@airsoko/auth";

const YourComponent: React.FC = () => {
  const { logout } = useAuth();

  const handleLogoutButtonClick = async () => {
    try {
      // Use the logout function to log out the user.
      await logout();

      // After successful logout, you can perform additional actions or redirect the user.
      console.log("User successfully logged out.");
    } catch (error) {
      console.error("Logout failed:", error);
      // Handle logout failure.
    }
  };

  return (
    <div>
      <p>Welcome to your application!</p>
      <button onClick={handleLogoutButtonClick}>Logout</button>
    </div>
  );
};

🤝 Contributing

Contributions to improve this package are welcome. Please adhere to the project's coding standards and commit guidelines.

License

MIT License

⚒️ Built With

  • @types/node
  • typescript


    🌟 This README was generated with 💖 by Airsoko

0.0.4

1 year ago

0.0.3

1 year ago

0.0.2

1 year ago

0.0.1

1 year ago