chg: [api] add£: register sensor endpoint

pull/24/head
Terrtia 2019-08-14 16:42:15 +02:00
parent d722390f89
commit 15bb67a086
No known key found for this signature in database
GPG Key ID: 1E1B1F50D84613D0
4 changed files with 146 additions and 6 deletions

View File

@ -86,8 +86,10 @@ sensor registrations, management of decoding protocols and dispatching to adequa
| --- | --- | --- |
| metadata_uuid:**uuid** | first_seen | **epoch** |
| | last_seen | **epoch** |
| | description | **description** |
| | Error | **error message** |
| | description | **description** | (optionnal)
| | Error | **error message** | (optionnal)
| | hmac_key | **hmac_key** | (optionnal)
| | user_id | **user_id** | (optionnal)
###### Last IP
| List Key | Value |

View File

@ -0,0 +1,84 @@
# API DOCUMENTATION
## General
### Automation key
The authentication of the automation is performed via a secure key available in the D4 UI interface. Make sure you keep that key secret. It gives access to the entire database! The API key is available in the ``Server Management`` menu under ``My Profile``.
The authorization is performed by using the following header:
~~~~
Authorization: YOUR_API_KEY
~~~~
### Accept and Content-Type headers
When submitting data in a POST, PUT or DELETE operation you need to specify in what content-type you encoded the payload. This is done by setting the below Content-Type headers:
~~~~
Content-Type: application/json
~~~~
Example:
~~~~
curl --header "Authorization: YOUR_API_KEY" --header "Content-Type: application/json" https://AIL_URL/
~~~~
## Item management
### Get item: `api/v1/get/item/default`<a name="get_item_default"></a>
#### Description
Get item default info.
**Method** : `POST`
#### Parameters
- `uuid`
- sensor uuid
- *uuid4*
- mandatory
- `hmac_key`
- sensor secret key
- *binary*
- mandatory
- `description`
- sensor description
- *str*
#### JSON response
- `uuid`
- sensor uuid
- *uuid4*
#### Example
```
curl https://127.0.0.1:7000/api/v1/add/sensor/register --header "Authorization: iHc1_ChZxj1aXmiFiF1mkxxQkzawwriEaZpPqyTQj " -H "Content-Type: application/json" --data @input.json -X POST
```
#### input.json Example
```json
{
"uuid": "",
"hmac_key": ""
}
```
#### Expected Success Response
**HTTP Status Code** : `200`
```json
{
"uuid": "",
}
```
#### Expected Fail Response
**HTTP Status Code** : `400`
```json
{"status": "error", "reason": "Mandatory parameter(s) not provided"}
```

45
server/lib/Sensor.py Executable file
View File

@ -0,0 +1,45 @@
#!/usr/bin/env python3
# -*-coding:UTF-8 -*
import os
import uuid
import redis
host_redis_metadata = os.getenv('D4_REDIS_METADATA_HOST', "localhost")
port_redis_metadata = int(os.getenv('D4_REDIS_METADATA_PORT', 6380))
r_serv_db = redis.StrictRedis(
host=host_redis_metadata,
port=port_redis_metadata,
db=0)
def is_valid_uuid_v4(UUID):
UUID = UUID.replace('-', '')
try:
uuid_test = uuid.UUID(hex=UUID, version=4)
return uuid_test.hex == UUID
except:
return False
## TODO: add user_id + description
def register_sensor(req_dict):
sensor_uuid = req_dict.get('uuid', None)
hmac_key = req_dict.get('hmac_key', None)
# verify uuid
if not is_valid_uuid_v4(sensor_uuid):
return ({"status": "error", "reason": "Invalid uuid"}, 400)
# sensor already exist
if r_serv_db.exists('metadata_uuid:{}'.format(sensor_uuid)):
return ({"status": "error", "reason": "Sensor already registred"}, 409)
res = _register_sensor(sensor_uuid, hmac_key, user_id=None, description=None)
return res
def _register_sensor(sensor_uuid, secret_key, user_id=None, description=None):
r_serv_db.hset('metadata_uuid:{}'.format(sensor_uuid), 'hmac_key', secret_key)
if user_id:
r_serv_db.hset('metadata_uuid:{}'.format(sensor_uuid), 'description', description)
if description:
r_serv_db.hset('metadata_uuid:{}'.format(sensor_uuid), 'description', description)
return ({'uuid': sensor_uuid}, 200)

View File

@ -18,6 +18,9 @@ from flask_login import login_required
from functools import wraps
sys.path.append(os.path.join(os.environ['D4_HOME'], 'lib'))
import Sensor
# ============ BLUEPRINT ============
restApi = Blueprint('restApi', __name__, template_folder='templates')
@ -27,6 +30,12 @@ restApi = Blueprint('restApi', __name__, template_folder='templates')
host_redis_metadata = os.getenv('D4_REDIS_METADATA_HOST', "localhost")
port_redis_metadata = int(os.getenv('D4_REDIS_METADATA_PORT', 6380))
r_serv_metadata = redis.StrictRedis(
host=host_redis_metadata,
port=port_redis_metadata,
db=0,
decode_responses=True)
r_serv_db = redis.StrictRedis(
host=host_redis_metadata,
port=port_redis_metadata,
@ -143,9 +152,9 @@ def one():
# ============= ROUTES ==============
@restApi.route("/api/v1/get/item", methods=['GET'])
@token_required('user')
def get_item_id():
@restApi.route("/api/v1/add/sensor/register", methods=['POST'])
@token_required('sensor_register')
def add_sensor_register():
data = request.get_json()
res = ({'test': 2}, 200)
res = Sensor.register_sensor(data)
return Response(json.dumps(res[0], indent=2, sort_keys=True), mimetype='application/json'), res[1]