2.0.3 • Published 1 month ago

ajna-auth-sdk v2.0.3

Weekly downloads
-
License
-
Repository
-
Last release
1 month ago

JS SDK

Here's a documentation for the functions in your auth-sdk module along with example code on how to call each function:

Authentication SDK Documentation

This module provides functions for handling user authentication and related operations. The SDK includes functions for user registration, login, logout, password management, and profile updates etc.

1. initializeAuth

This function initializes the authentication configuration.

  • Parameters:
    • config: An object containing authentication configuration.
      • url: Url of the auth service.
      • clientId: The client ID for the application.
      • userPlatform: The user's platform.
      • deviceId: The user's device ID.
  • Example:
import { initializeAuth } from './auth-sdk';

const authConfig = {
	url: "https://example.com",
  clientId: 'your-client-id',
  userPlatform: 'web',
  deviceId: 'device-123',
};

const isInitialized = initializeAuth(authConfig);

2. createUserWithEmailAndPassword

This function allows users to create an account with an email and password.

  • Parameters:
    • firstName: First name of the user.
    • lastName: Last name of the user.
    • email: User's email address.
    • password: User's chosen password.
    • phoneNumber: User's phone number.
    • profilePhotoURL: User's profile photo url (Optional).
    • organizationPhotoURL: User's organization photo url (Optional).
  • Example:
import { createUserWithEmailAndPassword } from './auth-sdk';

const userRegistration = async () => {
	const userData = {
    firstName: "sampl",
    lastName: "name",
    email: "test@test.com",
    password: "Testing@123",
	  phoneNumber: "7896574583",
    profilePhotoURL: "https://img.freepik.com/premium-vector/man-avatar-profile-picture-vector-illustration_268834-538.jpg",
    organizationPhotoURL: "https://img.freepik.com/premium-vector/man-avatar-profile-picture-vector-illustration_268834-538.jpg"
  }
  const registrationResult = await createUserWithEmailAndPassword(userData);

  if (registrationResult.success) {
    // Registration successful
    console.log(registrationResult.message);
  } else {
    // Registration failed
    console.error(registrationResult.message);
  }
};

3. logInWithUsernameAndPassword

This function allows users to log in using their username and password.

  • Parameters:
    • username: User's username or email.
    • password: User's password.
  • Example:
import { logInWithUsernameAndPassword } from './auth-sdk';

const userLogin = async () => {
  const loginResult = await logInWithUsernameAndPassword(
    'test@test.com',
    'Testing@123'
  );

  if (loginResult.success) {
    // Login successful
    console.log(loginResult.message);
  } else {
    // Login failed
    console.error(loginResult.message);
  }
};

4. logInWithMpin

This function allows users to log in using an MPIN.

  • Parameters:
    • username: User's username or email.
    • mpin: User's MPIN.
  • Example:
import { logInWithMpin } from './auth-sdk';

const mpinLogin = async () => {
  const loginResult = await logInWithMpin('test@test.com', '0609');

  if (loginResult.success) {
    // Login successful
    console.log(loginResult.message);
  } else {
    // Login failed
    console.error(loginResult.message);
  }
};

5. logInWithTotp

This function allows users to log in using a Time-based One-Time Password (TOTP).

  • Parameters:
    • username: User's username or email.
    • totp: User's TOTP.
  • Example:
import { logInWithTotp } from './auth-sdk';

const totpLogin = async () => {
  const loginResult = await logInWithTotp('test@test.com', '123456');

  if (loginResult.success) {
    // Login successful
    console.log(loginResult.message);
  } else {
    // Login failed
    console.error(loginResult.message);
  }
};

6. getQRCode

This function retrieves a QR code for user authentication.

  • Example:
import { getQRCode } from './auth-sdk';

const fetchQRCode = async () => {
  const qrCodeResult = await getQRCode();

  if (qrCodeResult.success) {
    // QR code fetched successfully
    console.log(qrCodeResult.message);
    console.log('QR Code URL:', qrCodeResult.qrCodeUrl);
  } else {
    // QR code retrieval failed
    console.error(qrCodeResult.message);
  }
};

7. refreshToken

This function serves the purpose of refreshing an access token for authenticated users. It's a crucial part of your application's authentication system to ensure continuous access to protected resources without requiring users to log in again.

  • Example:
import { refreshToken } from './auth-sdk';

const refreshAuthToken = async () => {
  const refreshResult = await refreshToken();

  if (refreshResult.success) {
    // Token refresh was successful
    console.log(refreshResult.message);
  } else {
    // Token refresh failed
    console.error(refreshResult.message);
  }
};

refreshAuthToken();

8. logout

This function logs the user out.

  • Example:
import { logout } from './auth-sdk';

const userLogout = async () => {
  const logoutResult = await logout();

  if (logoutResult.success) {
    // Logout successful
    console.log(logoutResult.message);
  } else {
    // Logout failed
    console.error(logoutResult.message);
  }
};

9. getMpin

This function retrieves the MPIN for the user.

  • Example:
import { getMpin } from './auth-sdk';

const fetchMpin = async () => {
  const mpinResult = await getMpin();

  if (mpinResult.success) {
    // MPIN fetched successfully
    console.log(mpinResult.message);
    console.log('MPIN:', mpinResult.data);
  } else {
    // MPIN retrieval failed
    console.error(mpinResult.message);
  }
};

10. refreshMpin

This function refreshes the user's MPIN.

  • Example:
import { refreshMpin } from './auth-sdk';

const refreshUserMpin = async () => {
  const refreshResult = await refreshMpin();

  if (refreshResult.success) {
    // MPIN refreshed successfully
    console.log(refreshResult.message);
  } else {
    // MPIN refresh failed
    console.error(refreshResult.message);
  }
};

11. changePassword

This function allows users to change their password.

  • Parameters:
    • newPassword: The new password.
  • Example:
import { changePassword } from './auth-sdk';

const changeUserPassword = async () => {
  const passwordChangeResult = await changePassword('newSecurePassword');

  if (passwordChangeResult.success) {
    // Password changed successfully
    console.log(passwordChangeResult.message);
  } else {
    // Password change failed
    console.error(passwordChangeResult.message);
  }
};

12. forgotPassword

This function initiates the password reset process by generating a forget password OTP.

  • Parameters:
    • email: User's email address.
  • Example:
import { forgotPassword } from './auth-sdk';

const initiatePasswordReset = async () => {
  const resetResult = await forgotPassword('test@test.com');

  if (resetResult.success) {
    // OTP sent successfully
    console.log(resetResult.message);
  } else {
    // OTP generation failed
    console.error(resetResult.message);
  }
};

13. createNewPasswordWithOtp

This function allows users to set a new password using an OTP received via email.

  • Parameters:

    • email: User's email address.
    • otp: The OTP received via email.
    • newPassword: The new password.
    • confirmPassword: Confirmation of the new password.

      Example:

      import { createNewPasswordWithOtp } from './auth-sdk';
      
      const resetPasswordWithOtp = async () => {
        const passwordResetResult = await createNewPasswordWithOtp(
          'johndoe@example.com',
          '123456', // OTP received via email
          'newSecurePassword',
          'newSecurePassword' // Confirmation of the new password
        );
      
        if (passwordResetResult.success) {
          // Password reset successful
          console.log(passwordResetResult.message);
        } else {
          // Password reset failed
          console.error(passwordResetResult.message);
        }
      };

      14. profileUpdate

      This function allows users to update their profile information.

    • Parameters:

      • userData: An object containing the user's data.
        • firstName: New first name (optional).
        • lastName: New last name (optional).
        • phoneNumber: New phone number (optional).
        • profilePhotoURL: New URL link of the profile photo (optional).
        • organizationPhotoURL: New URL link of the organization photo(optional).
    • Example:

      import { profileUpdate } from './auth-sdk';
      
      const updateUserProfile = async () => {
        const userData = {
          firstName: 'sample',
          lastName: 'name',
          phoneNumber: '9886789148',
      		profilePhotoURL: "https://img.freepik.com/premium-vector/man-avatar-profile-picture-vector-illustration_268834-538.jpg",
      		organizationPhotoURL: "https://img.freepik.com/premium-vector/man-avatar-profile-picture-vector-illustration_268834-538.jpg"
        };
      
        const profileUpdateResult = await profileUpdate(userData);
      
        if (profileUpdateResult.success) {
          // Profile updated successfully
          console.log(profileUpdateResult.message);
        } else {
          // Profile update failed
          console.error(profileUpdateResult.message);
        }
      };

      15. isAuthenticated

      This function allow user to check if they are authenticated or not.

      Parameters:

    • None

      Return Value:

    • The function returns a boolean value: - true if a user is authenticated, which means there is a valid access token, and the authentication configuration is present. - false if there is no authentication data, no access token, or a missing authentication configuration.

      Usage:

      You can use the isAuthenticated function to conditionally control access to certain parts of your application that require authentication. For example, if you have protected routes or specific features that should only be accessible to authenticated users, you can use this function to check the user's authentication status.

      Example:

      import { isAuthenticated } from './auth-utils';
      
      if (isAuthenticated()) {
        // The user is authenticated, grant access to protected content.
        console.log('User is authenticated');
      } else {
        // The user is not authenticated, restrict access to protected content.
        console.log('User is not authenticated');
      }

      16. validateEmail

      This function validates the format of an email address by making a request to the authentication server.

    • Parameters:

      • email: The email address to be validated.
    • Returns:
      • A Promise that resolves to an object with the following properties:
        • success: A boolean indicating whether the email is valid.
        • message: A string providing additional information about the validation status.
    • Example:

      import { validateEmail } from './auth-sdk';
      
      const checkEmailValidity = async () => {
        const email = 'test@example.com';
        const validationResult = await validateEmail(email);
      
        if (validationResult.success) {
          // Email is valid
          console.log(validationResult.message);
        } else {
          // Email is invalid
          console.error(validationResult.message);
        }
      };

      This function checks the validity of an email address by sending a request to the authentication server. The server responds with information about the email's validity, and the function returns a Promise that resolves to an object containing the success status and a message. The message provides additional details about the validation outcome.

      17. getProfileInfo

      This function retrieves the profile information for the authenticated user.

    • Parameters: None

    • Returns:
      • A Promise that resolves to an object with the following properties:
        • success: A boolean indicating whether the profile information retrieval was successful.
        • message: A string providing additional information about the retrieval status.
        • data: An object containing the user's profile information if successful.
    • Example:

      import { getProfileInfo } from './auth-sdk';
      
      const fetchUserProfileInfo = async () => {
        const profileInfoResult = await getProfileInfo();
      
        if (profileInfoResult.success) {
          // Profile information fetched successfully
          console.log(profileInfoResult.message);
          console.log('User Profile:', profileInfoResult.data);
        } else {
          // Profile information retrieval failed
          console.error(profileInfoResult.message);
        }
      };

      This function makes an API request to retrieve the profile information for the authenticated user. It uses the access token stored in the local storage to authenticate the request. The function returns a Promise that resolves to an object with the success status, a message providing additional details, and the user's profile information if the retrieval was successful.

      18. getUserSession

      This function provides you with all the session of a particular account.

    • Parameters:

      • email: The email address of the account
    • Returns:
      • A Promise that resolves to an object with the following properties:
        • success: A boolean indicating whether the email is valid.
        • message: A string providing additional information about the validation status.
    • Example:

      import { getUserSession } from './auth-sdk';
      
      const fetchSessions = async () => {
        const userSession = await getUserSession();
      
        if (userSession.success) {
          // userSession fetched successfully
          console.log(userSession.message);
          console.log('User Sessions:', userSession.data);
        } else {
          // MPIN retrieval failed
          console.error(useSession.message);
        }
      };

      This documentation provides an overview of the functions available in the Authentication SDK, their purposes, and example code for using each function. You can call these functions in your application to manage user authentication and related tasks.


      Ajna Auth SDK React Implementation

      This documentation explains how to integrate and use the ajna-auth-sdk in a React project for user authentication. The example code demonstrates a basic setup for user registration, login, and routing based on authentication status.

      Prerequisites

      Before implementing the ajna-auth-sdk in your React project, make sure you have the following prerequisites:

    • Node.js and npm installed on your machine.

    • A React project already set up.

      Installation

      You can install the ajna-auth-sdk package using npm:

      npm install ajna-auth-sdk

      Configuration

      To use the ajna-auth-sdk, you need to configure it with your authentication settings. In your main application file (e.g., App.js), initialize the configuration as follows:

      // App.js
      
      import React, { useEffect } from "react";
      import {
        BrowserRouter as Router,
        Route,
        Routes,
        Navigate,
      } from "react-router-dom";
      import Login from "./pages/login";
      import Dashboard from "./pages/deviceManagement.js";
      import Home from "./pages/home";
      import SignUp from "./pages/signup";
      import { initializeAuth, isAuthenticated } from "ajna-auth-sdk";
      
      // Configuration for authentication
      const config = {
        url: "https://your-auth-api.com", // Replace with your API URL
        clientId: "your-client-id", // Replace with your Client ID
        userPlatform: "web",
      };
      
      function App() {
        useEffect(() => {
          // Initialize authentication setup
          initializeAuth(config);
        }, []);
      
        // ...
      }
      
      export default App;

      Replace "https://your-auth-api.com" and "your-client-id" with your authentication server URL and client ID.

      User Registration (Signup Component)

      Create a component for user registration (e.g., Signup.js). This component allows users to sign up using their credentials.

      // Signup.js
      
      import React, { useState } from "react";
      import { useNavigate } from "react-router-dom";
      import { createUserWithEmailAndPassword } from "ajna-auth-sdk";
      
      function Signup() {
        const navigate = useNavigate();
        const [userData, setUserData] = useState({
          firstName: "",
          lastName: "",
          email: "",
          password: "",
          phoneNumber: "",
      		profilePhotoURL: "",
      		organizationPhotoURL: "",
        });
      
        const [message, setMessage] = useState("");
      
        const handleInputChange = (e) => {
          const { name, value } = e.target;
          setUserData({ ...userData, [name]: value });
        };
      
        const handleSubmit = async (e) => {
          e.preventDefault();
      
          const { firstName, lastName, email, password, phoneNumber } = userData;
      
          if (!firstName || !lastName || !email || !password || !phoneNumber) {
            setMessage("All fields are required");
            return;
          }
      
          const response = createUserWithEmailAndPassword(userData);
      
          if (response.success) {
            setMessage("User Created");
            navigate("/");
          } else {
            setMessage("Error creating user: " + response.message);
          }
        };
      
        return (
          // ...
        );
      }
      
      export default Signup;

      User Login (Login Component)

      Create a component for user login (e.g., Login.js). This component allows users to log in with their credentials.

      j
      // Login.js
      
      import React, { useState } from "react";
      import { useNavigate } from "react-router-dom";
      import { logInWithUsernameAndPassword } from "ajna-auth-sdk";
      
      function Login() {
        const navigate = useNavigate();
        const [username, setUsername] = useState("");
        const [password, setPassword] = useState("");
        const [message, setMessage] = useState("");
      
        const handleLogin = async () => {
          const response = logInWithUsernameAndPassword(username, password);
      
          if (response.success) {
            navigate("/device-management");
          } else {
            setMessage("Login failed: " + response.message);
          }
        };
      
        return (
          // ...
        );
      }
      
      export default Login;

      Protected Routes

      In your main application file (App.js), you can define routes that are protected and require authentication to access.

      // App.js
      
      import React, { useEffect } from "react";
      import {
        BrowserRouter as Router,
        Route,
        Routes,
        Navigate,
      } from "react-router-dom";
      import Login from "./pages/login";
      import Dashboard from "./pages/deviceManagement.js";
      import Home from "./pages/home";
      import SignUp from "./pages/signup";
      import { initializeAuth, isAuthenticated } from "ajna-auth-sdk";
      
      function App() {
        useEffect(() => {
          // Initialize authentication setup
          initializeAuth(config);
        }, []);
      
        return (
          <Router>
            <div>
              <Routes>
                <Route path="/" element={<Home />} />
                <Route path="/login" element={<Login />} />
                <Route path="/signup" element={<SignUp />} />
                <Route
                  path="/device-management"
                  element={
                    isAuthenticated() ? <Dashboard /> : <Navigate to="/login" />
                  }
                />
                {/* Add more protected routes as needed */}
              </Routes>
            </div>
          </Router>
        );
      }
      
      export default App;

      Usage

      With this setup, your React application will have user registration, login, and protected routes based on user authentication status.

    1. Users can sign up for an account using the Signup component.
    2. Users can log in using the Login component.
    3. Protected routes (e.g., /device-management) will only be accessible to authenticated users. If the user is not authenticated, they will be redirected to the login page.

      This documentation provides a basic example of implementing the ajna-auth-sdk in a React project. You can extend and customize it to suit your project's specific requirements.

2.0.3

1 month ago

2.0.2

1 month ago

2.0.1

1 month ago

2.0.0

2 months ago

1.1.9

2 months ago

1.1.8

2 months ago

1.1.7

2 months ago

1.1.6

5 months ago

1.1.5

5 months ago

1.1.4

5 months ago

1.1.3

6 months ago

1.1.2

6 months ago

1.1.1

6 months ago

1.1.0

7 months ago

1.0.2

7 months ago

1.0.5

7 months ago

1.0.1

7 months ago

1.0.0

7 months ago