Socket
Book a DemoInstallSign in
Socket

securiti-consent-sdk

Package Overview
Dependencies
Maintainers
1
Versions
54
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

securiti-consent-sdk

A React Native Library for managing user consent preferences and compliance with privacy regulations. Integrates with Securiti's Consent Management Platform.

1.136.0
latest
Source
npmnpm
Version published
Weekly downloads
525
14.63%
Maintainers
1
Weekly downloads
 
Created
Source

A React Native Library for managing user consent preferences and compliance with privacy regulations. Integrates with Securiti's Consent Management Platform.

Requirements

  • iOS 15.0+
  • Android API 24+
  • React Native 0.73.0+

Table of Contents

Important

This document contains information related to the React Native Consent SDK by Securiti, including installation, configuration, and usage of all available methods. The SDK name and API are subject to change.

Step 1: Installation Steps

  • Add the SDK to your package.json:
    npm i react-native-nitro-modules
    npm i securiti-consent-sdk@latest
    
  • Run:
    npm install
    
  • Ensure node_modules/securiti-consent-sdk exists.

Step 2: Android Installation Steps

  • In your app's android/app/build.gradle, add the following above the dependencies block:
    repositories {
        google()
        mavenCentral()
        maven {
            url 'https://cdn-prod.securiti.ai/consent/maven'
        }
    }
    

iOS Installation Steps

  • In your iOS folder "ios", run the command:
    pod install
    

Methods

initialize(options)

Description:
Initializes the Consent SDK with configuration options. Must be called before using any other SDK methods.

Parameters:

ParameterTypeRequiredDescription
optionsCmpSDKOptionsYesConfiguration options for the SDK

CmpSDKOptions:

OptionTypeRequiredDescription
appURLstringYesBase URL for the Securiti application
cdnURLstringYesURL for the Securiti CDN resources
tenantIDstringYesYour tenant identifier from Securiti
appIDstringYesYour application identifier from Securiti
testingModebooleanYesEnable testing mode
loggerLevelstringYesLog level: "DEBUG", "INFO", "WARNING", "ERROR"
consentsCheckIntervalnumberYesTime in seconds between consent checks
subjectIdstringNoUser identifier for consent tracking
languageCodestringNoLanguage code for UI elements (e.g., "en")
locationCodestringNoLocation code for regional compliance (e.g., "US")
modestringNoMode: "draft" or "live"

Return Value:
void

Example:

import { initialize, LoggerLevel, ModeValues } from 'securiti-consent-sdk';

const options = {
  appURL: 'your APP Url',
  cdnURL: 'Your CDN Url',
  tenantID: 'your-tenant-id',
  appID: 'your-app-id',
  testingMode: false,
  loggerLevel: LoggerLevel.DEBUG,
  consentsCheckInterval: 60,
  subjectId: 'user-123',
  languageCode: 'en',
  locationCode: 'US',
  mode: ModeValues.LIVE
};

initialize(options);

getConsentByPurposeId(purposeId)

Description:
Retrieves the consent status for a specific purpose by its ID.

Parameters:

ParameterTypeDescription
purposeIdnumberThe unique identifier of the purpose

Return Value:
Promise<ConsentStatus>

ConsentStatus Values:

  • granted
  • declined
  • not_determined
  • withdrawn

Example:

import { getConsentByPurposeId, ConsentStatusValues } from 'securiti-consent-sdk';

getConsentByPurposeId(12345)
  .then((status) => {
    if (status === ConsentStatusValues.GRANTED) {
      // Consent is granted
    }
  });

getConsentByPermissionId(permissionId)

Description:
Retrieves the consent status for a specific app permission by its ID.

Parameters:

ParameterTypeDescription
permissionIdstringThe unique identifier of the permission

Return Value:
Promise<ConsentStatus>

ConsentStatus Values:
Same as above.

Example:

import { getConsentByPermissionId, ConsentStatusValues } from 'securiti-consent-sdk';

getConsentByPermissionId('location')
  .then((status) => {
    if (status === ConsentStatusValues.GRANTED) {
      // Permission consent is granted
    }
  });

getPermissions()

Description:
Retrieves all available app permissions defined in the consent configuration.

Return Value:
Promise<AppPermission[]>

AppPermission Properties:

PropertyTypeDescription
idnumberThe numeric identifier
namestringThe permission name
permissionIdstringThe permission identifier string
descriptionstringLocalized permission descriptions
groupstringThe permission group name
groupIdnumberThe permission group identifier
consentStatusstringThe current consent status
nameMapstringLocalized permission names
isSettingsPromptEnabledbooleanWhether settings prompt is enabled

Example:

import { getPermissions, ConsentStatusValues } from 'securiti-consent-sdk';

getPermissions()
  .then((permissions) => {
    const grantedPermissions = permissions.filter(
      permission => permission.consentStatus === ConsentStatusValues.GRANTED
    );
  });

getPurposes()

Description:
Retrieves all available purposes defined in the consent configuration.

Return Value:
Promise<Purpose[]>

Purpose Properties:

PropertyTypeDescription
purposeIdnumberThe unique identifier for the purpose
purposeNamestringLocalized purpose names
purposeDescriptionstringLocalized purpose descriptions
sdksSDK[]SDKs associated with this purpose
consentStatusstringThe current consent status
disableOptOutbooleanWhether opt-out is disabled
optOutTextstringLocalized opt-out text
hideDetailsbooleanWhether details should be hidden in the UI
isGADMappedbooleanWhether mapped to Google Ads
gadDescriptionstringLocalized Google Ads description

Example:

import { getPurposes, ConsentStatusValues } from 'securiti-consent-sdk';

getPurposes()
  .then((purposes) => {
    const grantedPurposes = purposes.filter(
      purpose => purpose.consentStatus === ConsentStatusValues.GRANTED
    );
  });

getSdksInPurpose(purposeId)

Description:
Retrieves all SDKs associated with a specific purpose.

Parameters:

ParameterTypeDescription
purposeIdnumberThe unique identifier of the purpose

Return Value:
Promise<SDK[]>

SDK Properties:

PropertyTypeDescription
sdkIdnumberThe unique identifier for the SDK
namespaceIdstringThe namespace identifier string
sdkNamestringLocalized SDK names
sdkDescriptionstringLocalized SDK descriptions
vendorstringThe vendor or provider of the SDK
logoBase64stringBase64-encoded logo image
websitestringThe SDK vendor's website URL
matchedBystring[]How the SDK was matched in the application
collectingDatabooleanWhether the SDK is collecting data

Example:

import { getSdksInPurpose } from 'securiti-consent-sdk';

getSdksInPurpose(12345)
  .then((sdks) => {
    // Use SDKs
  });

Description:
Sets the consent status for a specific purpose.

Parameters:

ParameterTypeDescription
purposePurposeThe purpose object to set consent for
consentstringThe consent status to set

ConsentStatus Values:

  • granted
  • declined
  • not_determined
  • withdrawn

Return Value:
boolean

Example:

import { setPurposeConsent, getPurposes, ConsentStatusValues } from 'securiti-consent-sdk';

getPurposes()
  .then((purposes) => {
    const analyticsPurpose = purposes.find(p => p.purposeId === 12345);
    if (analyticsPurpose) {
      const success = setPurposeConsent(analyticsPurpose, ConsentStatusValues.GRANTED);
    }
  });

Description:
Sets the consent status for a specific app permission.

Parameters:

ParameterTypeDescription
appPermissionAppPermissionThe permission object to set consent for
consentstringThe consent status to set

ConsentStatus Values:
Same as above.

Return Value:
boolean

Example:

import { setPermissionConsent, getPermissions, ConsentStatusValues } from 'securiti-consent-sdk';

getPermissions()
  .then((permissions) => {
    const locationPermission = permissions.find(p => p.permissionId === 'location');
    if (locationPermission) {
      const success = setPermissionConsent(locationPermission, ConsentStatusValues.GRANTED);
    }
  });

resetConsents()

Description:
Resets all consents to their default state.

Parameters:
None

Return Value:
void

Example:

import { resetConsents } from 'securiti-consent-sdk';

resetConsents();

isReady(callback)

Description:
Checks if the React Native SDK is ready to use (asynchronous version).

Parameters:

ParameterTypeDescription
callback(status: boolean) => voidCallback function that receives the ready status

Return Value:
void

Example:

import { isReady, presentConsentBanner } from 'securiti-consent-sdk';

isReady((isReady) => {
  if (isReady) {
    presentConsentBanner();
  }
});

getBannerConfig()

Description:
Retrieves the banner configuration.

Return Value:
Promise<BannerConfig | null>

BannerConfig Properties:
(See Types and Properties section)

Example:

import { getBannerConfig } from 'securiti-consent-sdk';

getBannerConfig()
  .then((config) => {
    if (config) {
      // Use config
    }
  });

options()

Description:
Retrieves the current SDK configuration options.

Return Value:
CmpSDKOptions | null

Example:

import { options } from 'securiti-consent-sdk';

const currentOptions = options();

getSettingsPrompt()

Description:
Retrieves the settings prompt configuration.

Return Value:
Promise<SettingsPrompt | null>

SettingsPrompt Properties:
(See Types and Properties section)

Example:

import { getSettingsPrompt } from 'securiti-consent-sdk';

getSettingsPrompt()
  .then((prompt) => {
    if (prompt) {
      // Use prompt
    }
  });

uploadConsents(request)

Description:
Uploads consents to the server.

Parameters:

ParameterTypeDescription
requestPostConsentsRequestThe consent data to upload

Return Value:
Promise<boolean>

Example:

import { uploadConsents, ConsentStatusValues } from 'securiti-consent-sdk';

const timestamp = Date.now();
const consentRequest = {
  uuid: 'user-123',
  appUUID: 'app-456',
  device: 'iPhone 12',
  implicitConsent: false,
  version: 1,
  purposeConsents: [
    {
      purposeID: 12345,
      consentStatus: ConsentStatusValues.GRANTED,
      timestamp: timestamp,
      isEssential: false
    }
  ],
  permissions: [
    {
      permission: 'location',
      consentStatus: ConsentStatusValues.GRANTED,
      timestamp: timestamp
    }
  ],
  isTestMode: false,
  adId: 'advertising-id-789',
  bannerInfo: 'Banner version 2.0',
  sdkVersion: '1.132.0',
  platform: 'iOS'
};

uploadConsents(consentRequest)
  .then((success) => {
    if (success) {
      // Success
    }
  });

presentConsentBanner()

Description:
Displays the consent banner UI to the user.

Parameters:
None

Return Value:
void

Example:

import { presentConsentBanner } from 'securiti-consent-sdk';

presentConsentBanner();

presentPreferenceCenter()

Description:
Displays the preference center UI to the user.

Parameters:
None

Return Value:
void

Example:

import { presentPreferenceCenter } from 'securiti-consent-sdk';

presentPreferenceCenter();

Types and Properties

ConsentStatus Values

  • granted
  • declined
  • not_determined
  • withdrawn

CmpSDKOptions

See initialize(options).

AppPermission

See getPermissions().

Purpose

See getPurposes().

SDK

See getSdksInPurpose(purposeId).

BannerConfig

PropertyTypeDescription
hideCloseButtonbooleanWhether to hide the close button
hideAcceptButtonbooleanWhether to hide the accept button
embedDSRPortalLinkbooleanWhether to embed DSR portal link
recordConsentUponAppStartbooleanWhether to record consent on app start
hideToggleForEssentialCategoriesbooleanHide toggles for essential categories
namestringThe banner name
dsrPortalLinkstringLink to the DSR portal
complianceTypestring"notice-only", "opt-in", or "opt-out"
bannerReappearanceTimestringWhen the banner should reappear
privacyNoticeLinkstringLink to privacy notice
acceptstringLocalized accept button text
rejectstringLocalized reject button text
bannerTextstringLocalized banner text
bannerHeadingstringLocalized banner heading
sdkTabHeadingstringLocalized SDK tab heading
privacyNoticeTextstringLocalized privacy notice text
preferenceCenterLinkstringLocalized preference center link text
bannerPositionstring"bottom" or "center"
buttonShapestring"rounded", "square", "pill", "outlined"
customPaletteThemeobjectCustom color theme for banner

SettingsPrompt

PropertyTypeDescription
promptHeadingstringLocalized prompt heading text
promptMessagestringLocalized prompt message text
settingsButtonTextstringLocalized settings button text
notNowButtonTextstringLocalized "not now" button text
permissionsstring[]Permissions with settings prompt enabled

PostConsentsRequest

PropertyTypeRequiredDescription
uuidstringYesUnique user identifier
appUUIDstringYesApplication UUID
devicestringYesDevice information
implicitConsentbooleanYesWhether consent was implicit
versionnumberYesVersion of consent data
purposeConsentsPurposeConsent[]YesArray of purpose consent data
permissionsPermissionConsent[]YesArray of permission consent data
isTestModebooleanYesWhether in test mode
adIdstringYesAdvertising identifier
bannerInfostringYesBanner information
sdkVersionstringNoSDK version
platformstringNoPlatform information

Using Methods

Example usage in a React Native app:

import React, { useEffect, useState } from 'react';
import {
  View,
  StyleSheet,
  Text,
  ScrollView,
  ActivityIndicator,
  SafeAreaView,
  TouchableOpacity,
  Platform,
  Alert,
} from 'react-native';

// Import the functions from the library
import {
  initialize,
  presentConsentBanner,
  presentPreferenceCenter,
  isSdkReady,
  isReady,
  resetConsents,
  getConsentByPurposeId,
  getConsentByPermissionId,
  getPermissions,
  getPurposes,
  getSdksInPurpose,
  setPurposeConsent,
  setPermissionConsent,
  getBannerConfig,
  getSettingsPrompt,
  options,
  LoggerLevel,
  ConsentStatusValues,
} from 'securiti-consent-sdk';

// For types
import type {
  Purpose,
  AppPermission,
  SDK,
  BannerConfig,
  SettingsPrompt,
  CmpSDKOptions
} from 'securiti-consent-sdk';

// We'll use the isReady callback instead of native events

export default function App() {
  const [sdkReady, setSdkReady] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [response, setResponse] = useState<null | any>(null);
  const [purposes, setPurposes] = useState<Purpose[]>([]);
  const [permissions, setPermissions] = useState<AppPermission[]>([]);

  useEffect(() => {
    // Initialize SDK with appropriate options based on platform
   const initOptions: CmpSDKOptions = Platform.OS === 'android'
      ? {
          appURL: 'Your Android App URL',
          cdnURL: 'Your Android CDN URL',
          tenantID: 'Your Tenant ID',
          appID: 'Your Android App ID',
          testingMode: true,
          loggerLevel: LoggerLevel.DEBUG,
          consentsCheckInterval: 3600,
          subjectId: 'reactNativeAndroidSubject',
          languageCode: 'Your Language Code',
          locationCode: 'Your Location Code',
        }
      : {
          appURL: 'Your iOS App URL',
          cdnURL: 'Your iOS CDN URL',
          tenantID: 'Your Tenant ID',
          appID: 'Your iOS App ID',
          testingMode: true,
          loggerLevel: LoggerLevel.DEBUG,
          consentsCheckInterval: 3600,
          subjectId: 'reactNativeiOSSubject',
          languageCode: 'Your Language Code',
          locationCode: 'Your Location Code',
        };

    initialize(initOptions);

    // Use the isReady callback instead of events
    isReady((status) => {
      console.log('SDK ready callback received:', status);
      setSdkReady(status);
      if (status) {
        loadInitialData();
      }
    });

    // Also check using the synchronous method
    checkSdkReadiness();

    // No event listeners to clean up
    return () => {};
  }, []);

  const checkSdkReadiness = () => {
    // Synchronous check
    try {
      const ready = isSdkReady();
      setSdkReady(ready);
      console.log('SDK ready (sync check):', ready);

      if (ready) {
        handleShowBanner();
        loadInitialData();
      } else {
        // Also try the callback-based method
        isReady((ready) => {
          console.log('SDK ready (callback):', ready);
          setSdkReady(ready);
          if (ready) {
            handleShowBanner();
            loadInitialData();
          }
        });
      }
    } catch (error) {
      console.error('Error checking SDK readiness:', error);
    }
  };

  const loadInitialData = async () => {
    try {
      setIsLoading(true);
      console.log('Loading initial data...');

      // Load purposes and permissions in parallel
      const [purposesResult, permissionsResult] = await Promise.all([
        getPurposes(),
        getPermissions()
      ]);

      console.log('Purposes loaded:', purposesResult?.length || 0);
      console.log('Permissions loaded:', permissionsResult?.length || 0);

      setPurposes(purposesResult || []);
      setPermissions(permissionsResult || []);
    } catch (error) {
      console.error('Failed to load initial data:', error);
      Alert.alert('Error', 'Failed to load initial data');
    } finally {
      setIsLoading(false);
    }
  };

  const handleShowBanner = () => {
    try {
      presentConsentBanner();
      console.log('Consent banner presented');
    } catch (error) {
      console.error('Error presenting consent banner:', error);
      Alert.alert('Error', 'Failed to show consent banner');
    }
  };

  const handleShowPreferenceCenter = () => {
    try {
      presentPreferenceCenter();
      console.log('Preference center presented');
    } catch (error) {
      console.error('Error presenting preference center:', error);
      Alert.alert('Error', 'Failed to show preference center');
    }
  };

  const handleResetConsents = () => {
    setResponse(null);
    try {
      resetConsents();
      setResponse({
        message: 'Consents have been reset',
        timestamp: new Date().toISOString()
      });
      loadInitialData(); // Refresh data
    } catch (error) {
      console.error('Error resetting consents:', error);
      setResponse({ error: 'Failed to reset consents: ' + error });
    }
  };

  const handleGetPurposes = async () => {
    setResponse(null);
    setIsLoading(true);
    try {
      const result = await getPurposes();
      setResponse({
        purposes: result,
        timestamp: new Date().toISOString()
      });
      setPurposes(result || []);
    } catch (error) {
      console.error('Error getting purposes:', error);
      setResponse({ error: 'Failed to get purposes: ' + error });
    } finally {
      setIsLoading(false);
    }
  };

  const handleGetPermissions = async () => {
    setResponse(null);
    setIsLoading(true);
    try {
      const result = await getPermissions();
      setResponse({
        permissions: result,
        timestamp: new Date().toISOString()
      });
      setPermissions(result || []);
    } catch (error) {
      console.error('Error getting permissions:', error);
      setResponse({ error: 'Failed to get permissions: ' + error });
    } finally {
      setIsLoading(false);
    }
  };

  const handleGetSdksInPurpose = async (purposeId: number) => {
    setResponse(null);
    setIsLoading(true);
    try {
      const result = await getSdksInPurpose(purposeId);
      setResponse({
        purposeId,
        sdks: result,
        timestamp: new Date().toISOString()
      });
    } catch (error) {
      console.error('Error getting SDKs:', error);
      setResponse({ error: `Failed to get SDKs for purpose ${purposeId}: ` + error });
    } finally {
      setIsLoading(false);
    }
  };

  const handleGetBannerConfig = async () => {
    setResponse(null);
    setIsLoading(true);
    try {
      const result = await getBannerConfig(null);
      setResponse({
        bannerConfig: result,
        timestamp: new Date().toISOString()
      });
    } catch (error) {
      console.error('Error getting banner config:', error);
      setResponse({ error: 'Failed to get banner config: ' + error });
    } finally {
      setIsLoading(false);
    }
  };

  const handleGetSettingsPrompt = async () => {
    setResponse(null);
    setIsLoading(true);
    try {
      const result = await getSettingsPrompt();
      setResponse({
        settingsPrompt: result,
        timestamp: new Date().toISOString()
      });
    } catch (error) {
      console.error('Error getting settings prompt:', error);
      setResponse({ error: 'Failed to get settings prompt: ' + error });
    } finally {
      setIsLoading(false);
    }
  };

  const handleGetOptions = () => {
    setResponse(null);
    try {
      const sdkOptions = options();
      setResponse({
        options: sdkOptions,
        timestamp: new Date().toISOString()
      });
    } catch (error) {
      console.error('Error getting options:', error);
      setResponse({ error: 'Failed to get options: ' + error });
    }
  };

  const handleGetConsentForPurpose = async (purposeId: number) => {
    setResponse(null);
    setIsLoading(true);
    try {
      const result = await getConsentByPurposeId(purposeId);
      setResponse({
        purposeId,
        consentStatus: result,
        timestamp: new Date().toISOString()
      });
    } catch (error) {
      console.error('Error getting purpose consent:', error);
      setResponse({ error: `Failed to get consent for purpose ${purposeId}: ` + error });
    } finally {
      setIsLoading(false);
    }
  };

  const handleGetConsentForPermission = async (permissionId: string) => {
    setResponse(null);
    setIsLoading(true);
    try {
      const result = await getConsentByPermissionId(permissionId);
      setResponse({
        permissionId,
        consentStatus: result,
        timestamp: new Date().toISOString()
      });
    } catch (error) {
      console.error('Error getting permission consent:', error);
      setResponse({ error: `Failed to get consent for permission ${permissionId}: ` + error });
    } finally {
      setIsLoading(false);
    }
  };

  const handleSetConsentForPurpose = async (purpose: Purpose, consent: string) => {
    setResponse(null);
    setIsLoading(true);
    try {
      const success = setPurposeConsent(purpose, consent);
      console.log(`Set purpose consent result: ${success}`);

      // Give time for consent to apply
      await new Promise(resolve => setTimeout(resolve, 500));

      // Get updated status
      const newStatus = await getConsentByPurposeId(purpose.purposeId || 0);

      setResponse({
        message: `Set consent for purpose ${purpose.purposeId} to ${consent}`,
        success,
        newStatus,
        timestamp: new Date().toISOString()
      });

      // Refresh purposes list
      const updatedPurposes = await getPurposes();
      setPurposes(updatedPurposes || []);
    } catch (error) {
      console.error('Error setting purpose consent:', error);
      setResponse({ error: `Failed to set consent for purpose ${purpose.purposeId}: ` + error });
    } finally {
      setIsLoading(false);
    }
  };

  const handleSetConsentForPermission = async (permission: AppPermission, consent: string) => {
    setResponse(null);
    setIsLoading(true);
    try {
      const success = setPermissionConsent(permission, consent);
      console.log(`Set permission consent result: ${success}`);

      // Give time for consent to apply
      await new Promise(resolve => setTimeout(resolve, 500));

      // Get updated status
      const newStatus = await getConsentByPermissionId(permission.permissionId || '');

      setResponse({
        message: `Set consent for permission ${permission.permissionId} to ${consent}`,
        success,
        newStatus,
        timestamp: new Date().toISOString()
      });

      // Refresh permissions list
      const updatedPermissions = await getPermissions();
      setPermissions(updatedPermissions || []);
    } catch (error) {
      console.error('Error setting permission consent:', error);
      setResponse({ error: `Failed to set consent for permission ${permission.permissionId}: ` + error });
    } finally {
      setIsLoading(false);
    }
  };


  const renderPurposeItem = (purpose: Purpose) => {
    const purposeName = purpose.purposeName?.['en'] || `Purpose ${purpose.purposeId}`;

    return (
      <View style={styles.itemContainer} key={purpose.purposeId}>
        <Text style={styles.itemTitle}>{purposeName}</Text>
        <Text style={styles.itemSubtitle}>ID: {purpose.purposeId}</Text>
        <Text style={styles.itemSubtitle}>Status: {purpose.consentStatus || 'unknown'}</Text>

        <View style={styles.buttonRow}>
          <TouchableOpacity
            style={[styles.smallButton, styles.detailButton]}
            onPress={() => handleGetConsentForPurpose(purpose.purposeId || 0)}
          >
            <Text style={styles.smallButtonText}>Get Status</Text>
          </TouchableOpacity>

          <TouchableOpacity
            style={[styles.smallButton, styles.detailButton]}
            onPress={() => handleGetSdksInPurpose(purpose.purposeId || 0)}
          >
            <Text style={styles.smallButtonText}>Get SDKs</Text>
          </TouchableOpacity>

          <TouchableOpacity
            style={[styles.smallButton, styles.grantButton]}
            onPress={() => handleSetConsentForPurpose(purpose, ConsentStatusValues.GRANTED)}
          >
            <Text style={styles.smallButtonText}>Grant</Text>
          </TouchableOpacity>

          <TouchableOpacity
            style={[styles.smallButton, styles.declineButton]}
            onPress={() => handleSetConsentForPurpose(purpose, ConsentStatusValues.DECLINED)}
          >
            <Text style={styles.smallButtonText}>Decline</Text>
          </TouchableOpacity>
        </View>
      </View>
    );
  };

  const renderPermissionItem = (permission: AppPermission) => {
    const permissionName = permission.name || permission.permissionId || 'Unknown Permission';

    return (
      <View style={styles.itemContainer} key={permission.permissionId}>
        <Text style={styles.itemTitle}>{permissionName}</Text>
        <Text style={styles.itemSubtitle}>ID: {permission.permissionId}</Text>
        <Text style={styles.itemSubtitle}>Status: {permission.consentStatus || 'unknown'}</Text>

        <View style={styles.buttonRow}>
          <TouchableOpacity
            style={[styles.smallButton, styles.detailButton]}
            onPress={() => handleGetConsentForPermission(permission.permissionId || '')}
          >
            <Text style={styles.smallButtonText}>Get Status</Text>
          </TouchableOpacity>

          <TouchableOpacity
            style={[styles.smallButton, styles.grantButton]}
            onPress={() => handleSetConsentForPermission(permission, ConsentStatusValues.GRANTED)}
          >
            <Text style={styles.smallButtonText}>Grant</Text>
          </TouchableOpacity>

          <TouchableOpacity
            style={[styles.smallButton, styles.declineButton]}
            onPress={() => handleSetConsentForPermission(permission, ConsentStatusValues.DECLINED)}
          >
            <Text style={styles.smallButtonText}>Decline</Text>
          </TouchableOpacity>
        </View>
      </View>
    );
  };

  return (
    <SafeAreaView style={styles.container}>
      <ScrollView
        contentContainerStyle={styles.scrollContent}
        nestedScrollEnabled={true}>
        <View style={styles.header}>
          <Text style={styles.title}>Securiti Consent SDK Demo</Text>
          <Text style={styles.subtitle}>
            SDK Status: {sdkReady ? 'Ready' : 'Initializing...'}
          </Text>
        </View>

        <View style={styles.section}>
          <Text style={styles.sectionTitle}>Banner Controls</Text>
          <View style={styles.buttonRow}>
            <TouchableOpacity
              style={[styles.button, styles.primaryButton]}
              onPress={handleShowPreferenceCenter}
            >
              <Text style={styles.buttonText}>Preference Center</Text>
            </TouchableOpacity>
          </View>
        </View>

        <View style={styles.section}>
          <Text style={styles.sectionTitle}>Get Configuration</Text>
          <View style={styles.buttonRow}>
            <TouchableOpacity
              style={[styles.button, styles.secondaryButton]}
              onPress={handleGetBannerConfig}
            >
              <Text style={styles.buttonText}>Banner Config</Text>
            </TouchableOpacity>

            <TouchableOpacity
              style={[styles.button, styles.secondaryButton]}
              onPress={handleGetSettingsPrompt}
            >
              <Text style={styles.buttonText}>Settings Prompt</Text>
            </TouchableOpacity>

            <TouchableOpacity
              style={[styles.button, styles.secondaryButton]}
              onPress={handleGetOptions}
            >
              <Text style={styles.buttonText}>SDK Options</Text>
            </TouchableOpacity>
          </View>
        </View>

        <View style={styles.section}>
          <Text style={styles.sectionTitle}>Manage Data</Text>
          <View style={styles.buttonRow}>
            <TouchableOpacity
              style={[styles.button, styles.secondaryButton]}
              onPress={handleGetPurposes}
            >
              <Text style={styles.buttonText}>Get Purposes</Text>
            </TouchableOpacity>

            <TouchableOpacity
              style={[styles.button, styles.secondaryButton]}
              onPress={handleGetPermissions}
            >
              <Text style={styles.buttonText}>Get Permissions</Text>
            </TouchableOpacity>


            <TouchableOpacity
              style={[styles.button, styles.warningButton]}
              onPress={handleResetConsents}
            >
              <Text style={styles.buttonText}>Reset Consents</Text>
            </TouchableOpacity>
          </View>
        </View>

        {isLoading && (
          <View style={styles.loaderContainer}>
            <ActivityIndicator size="large" color="#0000ff" />
          </View>
        )}

        {response && (
          <View style={styles.responseContainer}>
            <Text style={styles.sectionTitle}>Response:</Text>
            <ScrollView
              style={styles.responseScrollView}
              contentContainerStyle={styles.responseScrollContent}
              nestedScrollEnabled={true}
            >
              <Text selectable={true} style={styles.responseText}>
                {JSON.stringify(response, null, 2)}
              </Text>
            </ScrollView>
          </View>
        )}

        {/* Purposes Section */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>Purposes</Text>
          {purposes.length === 0 ? (
            <Text style={styles.emptyText}>No purposes available</Text>
          ) : (
            purposes.map(renderPurposeItem)
          )}
        </View>

        {/* Permissions Section */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>Permissions</Text>
          {permissions.length === 0 ? (
            <Text style={styles.emptyText}>No permissions available</Text>
          ) : (
            permissions.map(renderPermissionItem)
          )}
        </View>
      </ScrollView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f5f5f5',
  },
  scrollContent: {
    padding: 16,
  },
  header: {
    marginBottom: 20,
    alignItems: 'center',
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    marginBottom: 8,
  },
  subtitle: {
    fontSize: 16,
    color: '#666',
    marginBottom: 8,
  },
  section: {
    marginBottom: 24,
    backgroundColor: '#fff',
    borderRadius: 8,
    padding: 16,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 4,
    elevation: 2,
  },
  sectionTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    marginBottom: 12,
  },
  buttonRow: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent: 'space-between',
    marginHorizontal: -4,
  },
  button: {
    margin: 4,
    padding: 12,
    borderRadius: 6,
    minWidth: 100,
    alignItems: 'center',
  },
  buttonText: {
    color: '#fff',
    fontWeight: 'bold',
  },
  primaryButton: {
    backgroundColor: '#2196F3',
  },
  secondaryButton: {
    backgroundColor: '#4CAF50',
  },
  actionButton: {
    backgroundColor: '#9C27B0',
  },
  warningButton: {
    backgroundColor: '#FF5722',
  },
  smallButton: {
    margin: 2,
    padding: 6,
    borderRadius: 4,
    minWidth: 60,
    alignItems: 'center',
  },
  smallButtonText: {
    fontSize: 12,
    color: '#fff',
    fontWeight: 'bold',
  },
  detailButton: {
    backgroundColor: '#607D8B',
  },
  grantButton: {
    backgroundColor: '#4CAF50',
  },
  declineButton: {
    backgroundColor: '#F44336',
  },
  loaderContainer: {
    padding: 20,
    alignItems: 'center',
  },
  responseContainer: {
    backgroundColor: '#fff',
    borderRadius: 8,
    padding: 16,
    marginBottom: 24,
    height: 300,
  },
  responseScrollView: {
    flex: 1,
    marginTop: 8,
    backgroundColor: '#f5f5f5',
    borderRadius: 4,
    borderWidth: 1,
    borderColor: '#e0e0e0',
  },
  responseScrollContent: {
    padding: 8,
  },
  responseText: {
    fontFamily: 'monospace',
    fontSize: 12,
    color: '#333',
  },
  itemContainer: {
    padding: 12,
    borderWidth: 1,
    borderColor: '#e0e0e0',
    borderRadius: 6,
    marginBottom: 8,
  },
  itemTitle: {
    fontSize: 16,
    fontWeight: 'bold',
    marginBottom: 4,
  },
  itemSubtitle: {
    fontSize: 14,
    color: '#666',
    marginBottom: 4,
  },
  emptyText: {
    padding: 16,
    textAlign: 'center',
    color: '#666',
  },
});

Go to the terminal and run:

npx react-native run-android

or

npx react-native run-ios

to see the consent banner on app start, and the preference center on click of the "Open Preference Center" button.

Keywords

react-native

FAQs

Package last updated on 28 Aug 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

About

Packages

Stay in touch

Get open source security insights delivered straight into your inbox.

  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc

U.S. Patent No. 12,346,443 & 12,314,394. Other pending.