Skip to content

Commit 88bacdd

Browse files
authored
Merge pull request #4 from securenative/sn-1913-sdk-alignment
Sn 1913 sdk alignment
2 parents 4b7153c + 7d4f757 commit 88bacdd

21 files changed

Lines changed: 880 additions & 152 deletions

.github/workflows/ci.yml

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,9 +27,6 @@ jobs:
2727
- uses: nanasess/setup-php@master
2828
- uses: php-actions/phpunit@v9
2929

30-
- name: Run tests
31-
run: phpunit test/AgentTest.php && php test/SecureNativeTest.php
32-
3330
- name: Publish to codecov
3431
run: bash <(curl -s https://codecov.io/bash)
3532

.github/workflows/publish.yml

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,9 +24,6 @@ jobs:
2424
- uses: nanasess/setup-php@master
2525
- uses: php-actions/phpunit@v9
2626

27-
- name: Run tests
28-
run: phpunit test/AgentTest.php && php test/SecureNativeTest.php
29-
3027
- name: Publish to codecov
3128
run: bash <(curl -s https://codecov.io/bash)
3229

README.md

Lines changed: 73 additions & 79 deletions
Original file line numberDiff line numberDiff line change
@@ -34,35 +34,74 @@ When using Composer run the following command:
3434
$ composer require securenative/securenative-php
3535
```
3636

37-
## Initialize the SDK
38-
39-
To get your *API KEY*, login to your SecureNative account and go to project settings page:
40-
41-
### Option 1: Initialize via ConfigurationBuilder
37+
### Add required imports
4238
```php
4339
require_once __DIR__ . '/vendor/autoload.php';
4440

4541
use SecureNative\sdk\SecureNative;
4642
use SecureNative\sdk\SecureNativeOptions;
43+
use SecureNative\sdk\EventTypes;
44+
use SecureNative\sdk\SecureNativeContext;
45+
```
4746

48-
$options = new SecureNativeOptions();
47+
## Initialize the SDK
4948

50-
$options->setMaxEvents(10);
51-
$options->setLogLevel("error");
49+
To get your *API KEY*, login to your SecureNative account and go to project settings page:
5250

53-
SecureNative::init("YOUR_API_KEY", $options);
51+
### Option 1: Initialize via API_KEY and SecureNativeOptions
52+
```php
53+
$options = new SecureNativeOptions();
54+
$options->setTimeout(100)
55+
->setApiUrl("API URL")
56+
->setDisable(false)
57+
->setInterval(100)
58+
->setAutoSend(true)
59+
->setMaxEvents(10)
60+
->setLogLevel('fatal');
61+
62+
// Passing `$options` is optional, will use default params
63+
SecureNative::init("[API_KEY]", $options);
5464
```
55-
### Option 2: Initialize via API Key
56-
57-
Initialize using default options.
58-
65+
### Option 2: Initialize via configuration file
66+
67+
Attach `securenative.json` file to your root folder:
68+
69+
```json
70+
{
71+
"SECURENATIVE_API_KEY": "SOME_API_KEY",
72+
"SECURENATIVE_APP_NAME": "SOME_APP_NAME",
73+
"SECURENATIVE_API_URL": "SOME_API_URL",
74+
"SECURENATIVE_INTERVAL": 1000,
75+
"SECURENATIVE_MAX_EVENTS": 100,
76+
"SECURENATIVE_TIMEOUT": 1500,
77+
"SECURENATIVE_AUTO_SEND": true,
78+
"SECURENATIVE_DISABLE": false,
79+
"SECURENATIVE_LOG_LEVEL": "fatal"
80+
}
81+
```
82+
Then, call SDK's `init` function without props (sending props will override JSON configurations).
5983
```php
60-
require_once __DIR__ . '/vendor/autoload.php';
84+
SecureNative::init();
85+
```
6186

62-
use SecureNative\sdk\SecureNative;
87+
### Option 3: Initialize via environment variables
6388

89+
Pass desired environment variables (for example):
6490

65-
SecureNative::init("YOUR_API_KEY");
91+
```shell script
92+
SECURENATIVE_API_KEY=TEST_KEY
93+
SECURENATIVE_API_URL=http://url
94+
SECURENATIVE_INTERVAL=100
95+
SECURENATIVE_MAX_EVENTS=30
96+
SECURENATIVE_TIMEOUT=1500
97+
SECURENATIVE_AUTO_SEND=true
98+
SECURENATIVE_DISABLE=false
99+
SECURENATIVE_LOG_LEVEL=fatal
100+
```
101+
102+
Then, call SDK's `init` function without props (sending props will override JSON configurations).
103+
```php
104+
SecureNative::init();
66105
```
67106

68107
## Tracking events
@@ -71,20 +110,14 @@ Once the SDK has been initialized, tracking requests sent through the SDK
71110
instance.
72111

73112
```php
74-
require_once __DIR__ . '/vendor/autoload.php';
113+
$clientToken = "[SECURED_CLIENT_TOKEN]";
114+
$headers = (object)["user-agent" => "Mozilla/5.0 (iPad; U; CPU OS 3_2_1 like Mac OS X; en-us"];
115+
$ip = "79.179.88.157";
116+
$remoteIp = null;
117+
$url = null;
118+
$method = null;
119+
$body = null;
75120

76-
use SecureNative\sdk\SecureNative;
77-
use SecureNative\sdk\SecureNativeOptions;
78-
use SecureNative\sdk\EventTypes;
79-
use SecureNative\sdk\SecureNativeContext;
80-
81-
$clientToken = "SECURED_CLIENT_TOKEN"
82-
$headers = (object)["user-agent" => "Mozilla/5.0 (iPad; U; CPU OS 3_2_1 like Mac OS X; en-us"] // User-Agent header is important to get device information!
83-
$ip = "127.0.0.1"
84-
$remoteIp = "127.0.0.1"
85-
$url = null
86-
$method = null
87-
$body = null
88121
$ctx = new SecureNativeContext($clientToken, $ip, $remoteIp, $headers, $url, $method, $body);
89122

90123
SecureNative::track(array(
@@ -104,14 +137,8 @@ SecureNative::track(array(
104137
));
105138
```
106139

140+
You can also create request context from request:
107141
```php
108-
require_once __DIR__ . '/vendor/autoload.php';
109-
110-
use SecureNative\sdk\SecureNative;
111-
use SecureNative\sdk\EventTypes;
112-
use SecureNative\sdk\SecureNativeContext;
113-
114-
115142
SecureNative::track(array(
116143
'event' => EventTypes::LOG_IN,
117144
'context' => SecureNative::contextFromContext(),
@@ -129,64 +156,31 @@ SecureNative::track(array(
129156
));
130157
```
131158

132-
You can also create request context from request:
133-
134-
```php
135-
require_once __DIR__ . '/vendor/autoload.php';
136-
137-
use SecureNative\sdk\SecureNative;
138-
use SecureNative\sdk\EventTypes;
139-
use SecureNative\sdk\SecureNativeContext;
140-
141-
142-
SecureNative::track(array(
143-
'event' => EventTypes::LOG_IN,
144-
'context' => SecureNativeContext::fromRequest(),
145-
'userId' => '1234',
146-
'userTraits' => (object)[
147-
'name' => 'Your Name',
148-
'email' => 'name@gmail.com'
149-
],
150-
));
151-
```
152-
153159
## Verify events
154160

155161
**Example**
156162

157163
```php
158-
require_once __DIR__ . '/vendor/autoload.php';
159-
160-
use SecureNative\sdk\SecureNative;
161-
use SecureNative\sdk\EventTypes;
162-
use SecureNative\sdk\SecureNativeContext;
163-
164-
165164
$ver = SecureNative::verify(array(
166-
'event' => EventTypes::VERIFY,
167-
'userId' => '1234',
168-
'context' => SecureNativeContext::fromRequest(),
169-
'userTraits' => (object)[
170-
'name' => 'Your Name',
171-
'email' => 'name@gmail.com'
172-
]
165+
'event' => EventTypes::VERIFY,
166+
'userId' => '1234',
167+
'context' => SecureNativeContext::fromRequest(),
168+
'userTraits' => (object)[
169+
'name' => 'Your Name',
170+
'email' => 'name@gmail.com'
171+
]
173172
));
174173

175-
$ver.riskLevel // Low, Medium, High
176-
$ver.score // Risk score: 0 - 1 (0 - Very Low, 1 - Very High)
177-
$ver.triggers // ["TOR", "New IP", "New City"]
174+
print_r($ver->riskLevel); // (Low, Medium, High)
175+
print_r($ver->score); // (0 - Very Low, 1 - Very High)
176+
print_r($ver->triggers); // (Example: ["TOR", "New IP", "New City"])
178177
```
179178

180179
## Webhook signature verification
181180

182181
Apply our filter to verify the request is from us, for example:
183182

184183
```php
185-
require_once __DIR__ . '/vendor/autoload.php';
186-
187-
use SecureNative\sdk\SecureNative;
188-
189-
190184
$verified = SecureNative::getMiddleware()->verifySignature();
191185

192186
if ($verified) {

composer.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@
2727
"guzzlehttp/guzzle": "^6.0",
2828
"antecedent/patchwork": "~2.0",
2929
"monolog/monolog": "2.0.2",
30-
"phpunit/phpunit": "^8"
30+
"phpunit/phpunit": "^9"
3131
},
3232
"require-dev": {
3333
"php-coveralls/php-coveralls": "*"

src/ConfigurationManager.php

Lines changed: 124 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,124 @@
1+
<?php
2+
3+
namespace SecureNative\sdk;
4+
5+
function getConfigMap()
6+
{
7+
return (object)[
8+
'SECURENATIVE_API_KEY' => (object)['name' => 'apiKey', 'type' => 'string'],
9+
'SECURENATIVE_APP_NAME' => (object)['name' => 'appName', 'type' => 'string'],
10+
'SECURENATIVE_API_URL' => (object)['name' => 'apiUrl', 'type' => 'string'],
11+
'SECURENATIVE_INTERVAL' => (object)['name' => 'interval', 'type' => 'integer'],
12+
'SECURENATIVE_MAX_EVENTS' => (object)['name' => 'maxEvents', 'type' => 'integer'],
13+
'SECURENATIVE_TIMEOUT' => (object)['name' => 'timeout', 'type' => 'integer'],
14+
'SECURENATIVE_AUTO_SEND' => (object)['name' => 'autoSend', 'type' => 'boolean'],
15+
'SECURENATIVE_DISABLE' => (object)['name' => 'disable', 'type' => 'boolean'],
16+
'SECURENATIVE_LOG_LEVEL' => (object)['name' => 'logLevel', 'type' => 'string'],
17+
'SECURENATIVE_FAILOVER_STRATEGY' => (object)['name' => 'failoverStrategy', 'type' => 'string'],
18+
];
19+
}
20+
21+
function getConfigMapItem($key)
22+
{
23+
return getConfigMap()->{$key};
24+
}
25+
26+
class ConfigurationManager
27+
{
28+
const CONFIG_FILE = 'securenative.json';
29+
30+
public static ?SecureNativeOptions $config;
31+
32+
static function readConfigFile($configFilePath = null)
33+
{
34+
$configMap = getConfigMap();
35+
$validConfigValues = array();
36+
$path = isset($configFilePath) ? $configFilePath : join('/', array(getcwd(), self::CONFIG_FILE));
37+
38+
try {
39+
$file = @file_get_contents($path);
40+
if ($file === false) {
41+
Logger::error("Error loading configuration file");
42+
} else {
43+
$json = json_decode($file);
44+
45+
if (is_array($json) || is_object($json)) {
46+
foreach ($json as $key => $val) {
47+
// If config item exists
48+
if (property_exists($configMap, $key)) {
49+
$mapItem = $configMap->{$key};
50+
// Prop type matches desired type
51+
if ($mapItem->type == gettype($val)) {
52+
$validConfigValues[$mapItem->name] = $val;
53+
}
54+
}
55+
}
56+
}
57+
}
58+
} catch (\Exception $e) {
59+
Logger::error("Error loading configuration file");
60+
}
61+
62+
return $validConfigValues;
63+
}
64+
65+
static function setConfigKey($key, $val)
66+
{
67+
if (isset(self::$config)) {
68+
self::$config[$key] = $val;
69+
}
70+
}
71+
72+
static function getConfigKey($key)
73+
{
74+
return self::$config[$key];
75+
}
76+
77+
private static function loadConfig($configFilePath = null)
78+
{
79+
$fileConfig = self::readConfigFile($configFilePath);
80+
81+
// Returns config item value -> if not found returns env value -> if not found -> null
82+
$getConfigOrEnv = function ($configKey, $envKey) use ($fileConfig) {
83+
$type = getConfigMapItem($envKey)->type;
84+
$envVal = getenv($envKey) ? getenv($envKey) : null;
85+
86+
if (isset($envVal)) {
87+
if ($type == "integer") {
88+
$envVal = intval($envVal);
89+
} else if ($type == "boolean") {
90+
$envVal = boolval($envVal);
91+
}
92+
}
93+
94+
return isset($fileConfig[$configKey]) ? $fileConfig[$configKey] : $envVal;
95+
};
96+
97+
self::$config = new SecureNativeOptions(
98+
$getConfigOrEnv('apiKey', 'SECURENATIVE_API_KEY'),
99+
$getConfigOrEnv('apiUrl', 'SECURENATIVE_API_URL'),
100+
$getConfigOrEnv('interval', 'SECURENATIVE_INTERVAL'),
101+
$getConfigOrEnv('maxEvents', 'SECURENATIVE_MAX_EVENTS'),
102+
$getConfigOrEnv('timeout', 'SECURENATIVE_TIMEOUT'),
103+
$getConfigOrEnv('autoSend', 'SECURENATIVE_AUTO_SEND'),
104+
$getConfigOrEnv('disable', 'SECURENATIVE_DISABLE'),
105+
$getConfigOrEnv('logLevel', 'SECURENATIVE_LOG_LEVEL'),
106+
$getConfigOrEnv('failoverStrategy', 'SECURENATIVE_FAILOVER_STRATEGY'),
107+
);
108+
}
109+
110+
static function clearConfig()
111+
{
112+
self::$config = null;
113+
}
114+
115+
static function getConfig($configFilePath = null): SecureNativeOptions
116+
{
117+
if (!isset(self::$config) || self::$config == null) {
118+
self::loadConfig($configFilePath);
119+
}
120+
return self::$config;
121+
}
122+
123+
124+
}

0 commit comments

Comments
 (0)