ajout des routes pour le parametrage

This commit is contained in:
Vincent BENOIT committed 2022-10-10 17:36:08 +02:00
1 parent 3fee231309
commit 02ab9aa099
5 files changed
+264 -2

No files matched your search

+2 -1
View File
@@ -20,6 +20,7 @@ import jwt
from src.config import DefaultConfig
from src.auth import auth
from src.account import account
from src.params import params
from src.log import log as logs
#########################################################
@@ -131,5 +132,5 @@ def configure_blueprints(app=None):
:return None:
'''
for bp in [auth, logs, account]:
for bp in [auth, logs, account, params]:
app.register_blueprint(bp)
+6
View File
@@ -0,0 +1,6 @@
# -*- encoding: utf-8 -*-
# @author : vincent.benoit@benserv.fr
# @brief : params views and models
from .views import params
+110
View File
@@ -0,0 +1,110 @@
# -*- encoding: utf-8 -*-
# @author : vincent.benoit@benserv.fr
# @brief : Params routes
#########################################################
# Importation de modules externes #
import sys, re, os
import logging as log
from datetime import datetime, timezone
from flask import Flask, Blueprint, request, abort, jsonify, current_app
from flask_api import status
from flask_jwt_extended import create_access_token
from flask_jwt_extended import get_jwt
from flask_jwt_extended import set_access_cookies
from flask_jwt_extended import unset_jwt_cookies
from flask_jwt_extended import get_jwt_identity
from flask_jwt_extended import jwt_required
import json
import shutil
import hashlib
from werkzeug.exceptions import HTTPException
#########################################################
# Class et Methods #
params = Blueprint('params', __name__, url_prefix='/api/configurateur')
@params.errorhandler(HTTPException)
def handle_exception(e):
''' return JSON instead of HTML for HTTP errors '''
response = e.get_response()
# replace the body with JSON
response.data = json.dumps({
'code': e.code,
'name': e.name,
'description': e.description,
})
response.content_type = "application/json"
return response
@params.after_request
def refresh_expiring_tokens(response):
''' Using an 'after_request' callback, we refresh any token that is within
30 minutes of expiring.'''
try:
exp_timestamp = get_jwt()['exp']
now = datetime.now(timezone.utc)
target_timestamp = datetime.timestamp(now + current_app.config['DELTA'])
if target_timestamp > exp_timestamp:
current_app.logger.warning("On doit recréer un token JWT ....")
access_token = create_access_token(identity=get_jwt_identity())
# refresh token in storage place
if os.path.exists(os.path.join("/tmp", current_app.config['PROJECT'])):
with open(os.path.join("/tmp", current_app.config['PROJECT'], get_jwt_identity()['id']), 'w') as f:
f.write(access_token)
# Modifiy a Flask Response to set a cookie containing the access JWT.
set_access_cookies(response, access_token)
return response
except (RuntimeError, KeyError):
return response
@params.route('/params', methods=['GET'])
@jwt_required()
def retreive_params():
''' Récupération des paramètres de l'intercom
'''
current_app.logger.info("Récupération des paramètres de l'intercom")
current_user = get_jwt_identity()
# load data from JSON database
with open(current_app.config['DB_PATH'], 'r') as f:
data = json.load(f)
if 'PIN_ACTIF' and 'CODE_PIN' and 'NUM_AUTORISE' and 'TONE_DURATION' and 'DTMF_CODE' and 'DTMF_DURATION' in data:
content = {'pin_actif': data['PIN_ACTIF'], 'code_pin': data['CODE_PIN'], 'num_autorized': data['NUM_AUTORISE'], 'tone_duration': data['TONE_DURATION'], 'dtmf_code': data['DTMF_CODE'], 'dtmf_duration': data['DTMF_DURATION']}
else:
abort(status.HTTP_406_NOT_ACCEPTABLE, description="paramètres manquant en base de données")
return content, status.HTTP_200_OK
@params.route('/update_params', methods=['POST'])
@jwt_required()
def update_params():
''' Mise à jour des paramètres de l'intercom
'''
current_app.logger.info("Mise à jour des paramètres de l'intercom")
current_user = get_jwt_identity()
# recuperation des attributs JSON de la requete
data_req = request.get_json()
current_app.logger.debug("request: {}".format(data_req))
# load data from JSON database
with open(current_app.config['DB_PATH'], 'r') as f:
data = json.load(f)
if 'old' in data_req:
if data_req['old'] != data['utilisateur']['password']:
abort(status.HTTP_406_NOT_ACCEPTABLE, description="Mauvais ancien mot de passe")
else:
abort(status.HTTP_406_NOT_ACCEPTABLE, description="Ancien mot de passe invalide")
if 'new' in data_req:
data['utilisateur']['password'] = data_req['new']
with open(current_app.config['DB_PATH'], 'w') as f:
json.dump(data, f)
else:
abort(status.HTTP_406_NOT_ACCEPTABLE, description="Nouveau mot de passe invalide")
content = {'message':'maj password successful!'}
return content, status.HTTP_200_OK