1.0.1 • Published 6 months ago

@dos.me/authen-sdk v1.0.1

Weekly downloads
-
License
MIT
Repository
-
Last release
6 months ago

DOS Authentication SDK

DOS Authentication SDK is a TypeScript/JavaScript library that allows you to integrate DOSafe authentication into your web application seamlessly.

Getting Started

Before you can use the DOS Authentication SDK, you need to obtain your specific configuration parameters from our team.

Request Configuration

To get your configuration values, please contact us with the following information:

  1. Your application details:

    • Application name
    • Application domain/URL
    • Brief description of your use case
  2. Contact us at: help@doschain.com

  3. What you'll receive:

    • backendUrl - Your dedicated backend endpoint
    • apiKey - Your unique API key
    • authDomain - Your authentication domain
    • projectId - Your project identifier
    • storageBucket - Your storage bucket URL
    • messagingSenderId - Your messaging service ID
    • appId - Your application ID
    • measurementId - Your analytics measurement ID

Installation

Using npm

npm install @dos.me/authen-sdk

Or using CDN

<script src="https://unpkg.com/@dos.me/authen-sdk@latest/dist/react-sdk.js"></script>

TypeScript Support

The SDK includes TypeScript definitions. Here's how to define the user information type:

export interface UserInfo {
  uid?: string;
  email?: string;
  isAuthen?: boolean;
  idToken?: string;
  displayName?: string;
  [key: string]: any;
}

Configuration

Initialize SDK

import DOSAuthSDK from '@dos.me/authen-sdk';

const dosAuthenSDK = new DOSAuthSDK({
    appName: 'YOUR_APP_NAME',
    backendUrl: '', // Contact us to get your backend URL
    apiKey: '', // Contact us to get your API key
    authDomain: '', // Contact us to get your auth domain
    projectId: '', // Contact us to get your project ID
    storageBucket: '', // Contact us to get your storage bucket
    messagingSenderId: '', // Contact us to get your messaging sender ID
    appId: '', // Contact us to get your app ID
    measurementId: '' // Contact us to get your measurement ID
});

⚠️ Important: All configuration values above need to be obtained by contacting our support team. Please reach out to us at help@doschain.com to get your specific configuration parameters for your application.

Usage

1. Sign In

// Method 1: Using Promise
const userInfo = await dosAuthenSDK.openSignin();

// Method 2: Using callback, User to check User Authen
dosAuthenSDK.registerAuthenCallback((userInfo) => {
    console.log('Received user info:', userInfo);
    // Update UI or perform actions with user info
});

2. Sign Up

const result = await dosAuthenSDK.openSignup();

3. Logout

const result = dosAuthenSDK.onLogout();

4. Get User Information

const userInfo = await dosAuthenSDK.getUserInfo();

5. Get ID Token

const tokenInfo = await dosAuthenSDK.getIdToken();

6. Refresh Token

const tokenInfo = await dosAuthenSDK.refreshIdToken();

7. Unlink Provider

// Supported providers: 'Google', 'Facebook', 'Apple'
dosAuthenSDK.unlinkProvider('Google');

React Integration Example

Here's a complete example of integrating the SDK with a React TypeScript application:

import React, { useEffect, useState, useRef } from 'react';
import './App.css';
import DOSAuthSDK from '@dos.me/authen-sdk';

export interface UserInfo {
  uid?: string;
  email?: string;
  isAuthen?: boolean;
  idToken?: string;
  displayName?: string;
  [key: string]: any;
}

function App() {
  const [statusMessage, setStatusMessage] = useState<string>('Not authenticated');
  const [userInfo, setUserInfo] = useState<UserInfo | null>(null);
  const authSDKRef = useRef<DOSAuthSDK | null>(null);

  useEffect(() => {
    // Initialize the SDK
    const dosAuthenSDK = new DOSAuthSDK({
      appName: 'YOUR_APP_NAME',
      backendUrl: 'YOUR_BACKEND_URL',
      apiKey: 'YOUR_API_KEY',
      authDomain: 'YOUR_AUTH_DOMAIN',
      projectId: 'YOUR_PROJECT_ID',
      storageBucket: 'YOUR_STORAGE_BUCKET',
      messagingSenderId: 'YOUR_MESSAGING_SENDER_ID',
      appId: 'YOUR_APP_ID',
      measurementId: 'YOUR_MEASUREMENT_ID'
    });

    // Store the SDK instance in the ref
    authSDKRef.current = dosAuthenSDK;

    // Register authentication callback
    dosAuthenSDK.registerAuthenCallback((userInfo: UserInfo) => {
      console.log('Received user info via callback:', userInfo);
      setUserInfo(userInfo);
      setStatusMessage(`Authenticated as: ${userInfo.email || 'Unknown user'}`);
    });

    // Check if user is already authenticated
    dosAuthenSDK.getUserInfo()
      .then((info: any) => {
        if (info) {
          setUserInfo(info);
          setStatusMessage(`Already authenticated as: ${info.email || 'Unknown user'}`);
        }
      })
      .catch((error: any) => {
        console.log('Not authenticated yet', error);
      });
  }, []);

  const handleSignIn = async () => {
    if (!authSDKRef.current) return;
    
    try {
      const info = await authSDKRef.current.openSignin();
      console.log('User successfully logged in:', info);
      setUserInfo(info);
    } catch (error) {
      console.error('Login failed:', error);
    }
  };

  // More handler functions...

  return (
    <div className="App">
      <button onClick={handleSignIn}>Sign In</button>
      {/* More UI elements */}
    </div>
  );
}

export default App;

API Reference

Constructor

new DOSAuthSDK(config)

Initialize the SDK with configuration.

Parameters:

  • config (Object): Configuration object
    • appName (string): Application name
    • backendUrl (string): Backend URL (Contact us to obtain)
    • apiKey (string): API key (Contact us to obtain)
    • authDomain (string): Auth domain (Contact us to obtain)
    • projectId (string): Project ID (Contact us to obtain)
    • storageBucket (string): Storage bucket (Contact us to obtain)
    • messagingSenderId (string): Messaging sender ID (Contact us to obtain)
    • appId (string): App ID (Contact us to obtain)
    • measurementId (string): Measurement ID (Contact us to obtain)

Methods

openSignin()

Open the sign-in popup.

Returns: Promise<UserInfo> - User information after successful login

openSignup()

Open the sign-up popup.

Returns: Promise<UserInfo> - Signup result

onLogout()

Perform logout.

Returns: boolean - Logout status

getUserInfo()

Get current user information.

Returns: Promise<UserInfo> - User information with format:

{
    code: number;
    success: boolean;
    message: string;
    data: UserInfo;
}

getIdToken()

Get the current user's ID token.

Returns: Promise<Object> - Token information

refreshIdToken()

Refresh the ID token.

Returns: Promise<Object> - Refreshed token

unlinkProvider(provider)

Unlink authentication provider.

Parameters:

  • provider (string): Provider name ('Google', 'Facebook', 'Apple')

Returns: Promise<Object> - Unlink result

registerAuthenCallback(callback)

Register a callback function to be called when authentication is successful.

Parameters:

  • callback (function): Callback function that receives user information

TypeScript signature:

registerAuthenCallback(callback: (userInfo: UserInfo) => void): void

Error Handling

The SDK returns the following error codes:

  • 200: Success
  • -1: Environment error (window undefined)
  • -2: Token expired
  • -3: User not logged in

Browser Support

  • Chrome 60+
  • Firefox 55+
  • Safari 12+
  • Edge 79+

Best Practices

  1. Always handle errors: Wrap SDK calls in try-catch blocks
  2. Check authentication status: Verify user is logged in before calling protected methods
  3. Token management: Implement automatic token refresh logic
  4. Security: Never expose sensitive configuration in client-side code
  5. User experience: Provide loading states during authentication flows

Troubleshooting

Common Issues

1. SDK not initializing

  • Make sure all required configuration parameters are provided
  • Check console for error messages
  • Verify the SDK script is loaded correctly

2. Authentication popup not appearing

  • Check if popup blockers are enabled
  • Ensure the button click event is properly bound
  • Verify the SDK is initialized before calling methods

3. Token expired errors

  • Implement automatic token refresh using refreshIdToken()
  • Handle token expiration gracefully in your application

4. Cross-origin issues

  • Configure proper CORS settings on your backend
  • Ensure the backend URL in configuration is correct

Support

Contributing

We welcome contributions! Please see our Contributing Guide for details.

License

MIT License - see the LICENSE file for details.

1.0.1

6 months ago