Socket
Socket
Sign inDemoInstall

@abl-solutions/wifi-connect

Package Overview
Dependencies
0
Maintainers
4
Versions
35
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    @abl-solutions/wifi-connect

The WiFi Connect React Native SDK enables the use of WiFi WPA2-Enterprise networks on mobile devices that are managed and operated by abl solutions GmbH


Version published
Weekly downloads
5
Maintainers
4
Created
Weekly downloads
 

Readme

Source

WiFi Connect - React Native SDK

npm npm

React Native SDK to configure and use WiFi networks managed and operated by abl solutions GmbH

Requirements

Android

Required permissions:

  • android.permission.INTERNET
  • android.permission.CHANGE_WIFI_STATE
  • android.permission.ACCESS_WIFI_STATE

Minimum required SDK version: 24 (Android 7 - Nougat)

iOS

Required entitlements (capabilities):

  • com.apple.developer.networking.HotspotConfiguration (Hotspot Configuration)
  • com.apple.developer.networking.wifi-info (Access WiFi Information)

Minimum required iOS version: 11.0

Release Note

In this version of SDK 0.8.1 - push notifications permission is not required. If you want to use this - use 0.8.0.

For SDK v.0.8.0 User should grant Push notifications permission to be abl connect to Wifi via SDK (e.g. save config for auto-connect). Android <= 12 - not required - it's enabled by default.

Installation

Run

npm install @abl-solutions/wifi-connect

or

yarn add @abl-solutions/wifi-connect
For IOS:
cd ./ios && pod install

Android 13 and higher (For 0.8.0)

You should add this line to your app level manifest file and ask permission for push notifications.

<uses-permission android:id="android.permission.POST_NOTIFICATIONS"/>

Configure the WifiConnectService

initWifiConnectService Options:

PropertyrequiredTypeDescription
accessTokenstringAn access token that allows access to the WiFi Connect API for the current user.
ignoreNetworkErrorOnSimulatorbooleanUsually, network and WiFi support is limited running on a simulator. Therefore, the WiFi configuration can not be stored on a simulated device. In such a case WifiConnect.connectToWifi() will reject with the error code E_NOT_SUPPORTED_ON_SIMULATOR. If you don't want to reject with this error but instead resolve successfully, set this value to true. Defaults to false.
wifiApiEndpointbooleanOptionally set a different REST API endpoint that should be used by this library
isHiddenSSIDbooleanSpecifies whether connection represents a hidden network. This value defaults to false if not specified.
androidobejctOptional Android specific options.
android.timeSpanToWaitForPermissionDialogConfirmationInSecondsnumberThis value is only used for connectToWifi on Android 10 devices. This time span is used to wait for granting/declining the permission dialog which is shown by the Operating System. If the user declines the permission dialog within the time span, connectToWifi will reject with the corresponding error code. If the user grants the permissions or the dialog is still opened, connectToWifi will resolve after the time span. This value defaults to 10 seconds if not specified.
import type { WifiConnectService } from '@abl-solutions/wifi-connect';
import { initWifiConnectService } from '@abl-solutions/wifi-connect';

const createWifiConnectService = (accessToken: string): WifiConnectService => {
  return initWifiConnectService({
    accessToken: accessToken,
    android: {
      timeSpanToWaitForPermissionDialogConfirmationInSeconds: 30,
    },
    ignoreNetworkErrorOnSimulator: true,
    isHiddenSSID: true,
    wifiApiEndpoint: 'https://api.wifi.connectivity.abl-solutions.io',
  });
};

wifiConnectService = createWifiConnectService(auth.accessToken);

WifiConnectService API

connectToWifi(deviceId: string, user: User): Promise<void>;

Register this device to get direct access to abl's WiFi networks. The device will be configured to use this WiFi connection. This operation is an asynchrnous process and might take a few seconds to complete. @param deviceId A string that uniquely identifies this device. @param user Details about the user that owns the device. @returns A void promise that resolves if the devices registration was successful and the WiFi configuration is stored in the device settings. Rejects if configuring the WiFi network failed for any reason. Rejects if push notifications permission not granted by user.

Interfaces User
PropertyTypeDescription
emailstringThe e-mail address of the user.
preferredLocalestringThe preferred locale that should be used to interact with the user.
await wifiConnectService.connectToWifi(deviceId, {
  email: email,
  preferredLocale: preferredLocale,
});

getLatestLegalTerms(): Promise<LegalTerms>;

Gets the latest legal terms that must be accepted by the end-user to use the WiFi network. @returns A promise that resolves the legal terms or rejects if loading the legal terms failed.

Interfaces LegalTerms
PropertyTypeDescription
legalTermsstringLegal terms content
versionstringVersion of legal terms
minimumVersionstringMinimum legal terms version which must be accepted to access the API.
dateMinLegalTermsActivestringThe date at which the minimal version of legal terms will be enforced.
const terms: LegalTerms = await wifiConnectService.getLatestLegalTerms();

legalTermsAccepted(): Promise<boolean>;

Checks whether the specified user already accepted the legal terms or not. @returns true if the user already accepted the legal terms, otherwise false.

const result: boolean = await wifiConnectService.legalTermsAccepted();

legalTermsAcceptedVersion(): Promise<string>

Checks the version of legal terms accepted by the user. @returns version of the legal terms that was accepted by the user. If the user didn't accepted any legal terms yet - returns 'undefined'

const result: string = await wifiConnectService.legalTermsAcceptedVersion();

acceptLegalTerms(legalTermsVersion: string): Promise<void>;

Accept the specified version of legal terms. This method needs to be called before a user can register to connect to a WiFi network. @param legalTermsVersion The version of the legal terms.

await wifiConnectService.acceptLegalTerms(legalTermsVersion);

deleteWifiConfiguration(deviceId: string): Promise<void>;

Deletes the WiFi settings from the device and unregisters the device from abl servers. Basically, it just reverts the changes that were made by connectToWifi(). @param deviceId A string that uniquely identifies this device.

await wifiConnectService.deleteWifiConfiguration(deviceId);

isWifiConfigured(): Promise<boolean>;

Check if the device is configured to connect to abl's WiFi network. @returns true if the device is configured; otherwise false. In case of error promise will reject with error.

try {
  const result: boolean = await wifiConnectService.isWifiConfigured();
} catch (e) {
  // Do something with an error
}

isConnectedToWifi(): Promise<boolean>; (iOS only)

Check if device is connected to abl's WiFi network. Method should be invoked after connectToWifi() to check connection by received SSID, othervise resolves with false. @returns true if the device is connected; otherwise false. This function works only on iOS devices.

import { Platform } from 'react-native';
if (Platform.OS === 'ios') {
  setTimeout(async () => {
    const result: boolean = await wifiConnectService.isConnectedToWifi();
  }, 4000);
}

registerOnPermissionRejectedListener(callback: () => void): void;

Registers a callback that will be invoked if the required permissions are revoked after connectToWifi fullfilled. This callback can be used to handle the case if a user rejects the permission dialog after the confirmation time span. This callback should be unregistered (using unregisterOnPermissionRejectedListener) after usage to free internal resources. This callback will only be invoked on Android 10 devices. @param callback The callback to invoke.

import { Alert } from 'react-native';
wifiConnectService.registerOnPermissionRejectedListener(() => {
  Alert.alert('Permission rejected', 'Please accept...');
});

unregisterOnPermissionRejectedListener(): void;

Unregister the callback that was previously registered using registerOnPermissionRejectedListener

// return a clean up function to unregister the listener
return () => wifiConnectService?.unregisterOnPermissionRejectedListener();

Configure the WifiCampaignService

initCampaignService Options

PropertyrequiredTypeDescription
accessTokenstringAn access token that allows access to the Campaign API for the current user.
campaignApiEndpointstringOptionally set a different REST API endpoint that should be used by this library.
import type { CampaignService } from '@abl-solutions/wifi-connect';
import { initCampaignService } from '@abl-solutions/wifi-connect';

const createWifiCampaignService = (accessToken: string): CampaignService => {
  return initCampaignService({
    accessToken: accessToken,
    campaignApiEndpoint: process.env.CAMPAIGN_API_ENDPOINT,
  });
};

campaignService = createWifiCampaignService(auth.accessToken);

CampaignService API

getNextCampaign(deviceId: string): Promise<Campaign>;

Campaign

PropertyTypeDescription
campaignUrlstringA promise that resolves to a Campaign object if the campaign was fetched successfully. Rejects if fetching the next campaign failed for any reason. The Campaign object contains a flag Campaign.required that will be true if the user needs to watch a campaign. This will be the case if the timespan since watching the last campaign is greater than the configured timespan. If Campaign.required is false then it is not necessary to watch a campaign.
requiredbooleanThis flag indicating if watching campaign required or not to prolong an access to wifi.
notificationNotificationThat's an object that contain title and body that could be string or null
const campaign = await campaignService.getNextCampaign(deviceId);

shouldCloseCampaignView(campaignUrl: string): boolean;

Checking when to close campaign view - campaign at this step considered as watched.

const onNavigationStateChange = (navigationState: { url: string }) => {
  if (campaignService.shouldCloseCampaignView(navigationState?.url)) {
    setCampaign(undefined);
    console.log('campaign viewed - closing webview');
  }
};

Error handling

WifiConnect.connectToWifi(...) and WifiConnect.deleteWifiConfiguration() will reject if configuring the wifi failed for any reason. The error object contains at least the following properties:

{
  "code": "string",
  "message": "string"
}

Additionally, there can be any other properties depending on the error type and platform.

The error code specifies the type of error. The message provides an additional description of the error. Some of these error codes are only specific for a platform.

Error CodeDescriptionAndroidiOS
E_ACTIVITY_DOES_NOT_EXISTWill be thrown if the React Native context does not include a reference to the current activity.yesno
E_INVALID_WIFI_CONFIGURATIONWill be thrown if the WiFi configuration is invalid. This might be a invalid username, password or certificate. If this error occours, this should be reported to abl.yesyes
E_USER_REJECTEDThe user rejected to connect to the WiFi network.yesyes
E_PERMISSION_DENIEDThe app is not authorized to configure WiFi networks on the device.yesno (iOS will throw E_UNKNOWN_ERROR in this case)
E_FAILED_TO_ENABLE_NETWORKAndroid devices can store network configurations that are disabled. This error occours if enabling the network failed. Usually, this should not happen.yesno
E_RUNNING_ON_SIMULATORConnecting to a WiFi network on simulator is not supported. If you want to ignore this error and get a successful response anyway, set WifiConnectOptions.ignoreNetworkErrorOnSimulator to true.yesyes
E_API_ERROR_UNAUTHORIZEDThe request failed because the provided access token is invalid, expired or a required scope is missing.yesyes
E_API_ERROR_BAD_REQUESTThe request failed because one or more input arguments are missing or invalid.yesyes
E_API_ERROR_INTERNAL_SERVER_ERRORThe request failed due to an error on abl servers.yesyes
E_API_ERRORThe request failed for any unknown/unexpected reason.yesyes
E_UNKNOWN_ERRORAny other error case that is not described above.yesyes

The library provides an enum with all possible error codes.

import { ErrorCode } from '@abl-solutions/wifi-connect';

In all cases where the error message starts with E_API_, the thrown error contains an additional property apiError. This property contains additional information about the error. apiError can be of type string or an object that is JSON serializable.

Limitations

Android

The SDK has the following limitations on Android devices:

Running on Simulator

Simulators do not provide any possibility to simulate a real WiFi connection, because the real WiFi adapter of the host machine can not be used. Therefore, it is not possible to use WifiConnect.connectToWifi() and WifiConnect.deleteWifiConfiguration() in a simulator. Calling this function will raise a E_RUNNING_ON_SIMULATOR error. To overcome this issue in simulators, you can set WifiConnectOptions.ignoreNetworkErrorOnSimulator to true in the init() function. With this option, configuring the WiFi connection will be skipped. But in any case the device will be registered on abl servers. This is handy for testing other features like accepting legal terms or watching campaigns.

Keywords

FAQs

Last updated on 05 Dec 2023

Did you know?

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

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc