Elyos_FI_Back_Office/partners.py

404 lines
14 KiB
Python

'''
Ce fichier definit la gestion des partners - client.
exemple :
- creation et modification des compte client
- connexion pour l'obtention d'un token
- creation d'une api d'ajout/mise d'une formation
- creation d'une api de desactivation d'une formation
'''
from pymongo import MongoClient
import pymongo
import json
from flask import Flask, request, jsonify
#from flask_mongoengine import MongoEngine
import json
from bson import ObjectId
import re
import numpy as np
import ela_index_bdd_classes as ela_index
import email_mgt as mail
from datetime import datetime
import logging
import prj_common as mycommon
import secrets
class JSONEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, ObjectId):
return str(o)
return json.JSONEncoder.default(self, o)
CONNECTION_STRING = "mongodb://localhost/cherifdb"
client = MongoClient(CONNECTION_STRING)
dbname = client['cherifdb']
'''
Ajout d'un partenaire
'''
def add_partner_account(diction):
try:
# Dictionnaire des champs utilisables
'''
# Verification que les champs reçus dans l'API sont bien dans la liste des champs autorisés
# Cela evite le cas ou une entité tierce ajouter les valeurs inconnu dans l'API
# Ici on doit mettre tous les champs possible (obligatoire ou non) de la BDD dans la liste
# field_list.
'''
field_list = ['nom', 'adr_street', 'adr_city', 'adr_zip', 'adr_country',
'email','pwd', 'telephone','contact_nom','contact_prenom','contact_tel','contact_mail']
incom_keys = diction.keys()
for val in incom_keys:
if val not in field_list:
mycommon.myprint(" Creation partner account : Le champ '" + val + "' n'existe pas, Creation partenaire annulée")
return False, "Impossible de créer le partenaire"
'''
Une fois qu'on a controlé que toutes les clés mise dans l'API sont correcte. etape precedente,
On controle que les champs obligatoires sont presents dans la liste
'''
field_list_obligatoire = ['nom', 'email','pwd', 'telephone','contact_nom','contact_prenom','contact_tel','contact_mail']
for val in field_list_obligatoire :
if val not in diction:
mycommon.myprint( " : La valeur '"+val+"' n'est pas presente dans liste ")
return False, "Impossible de créer le partenaire"
# recuperation des paramettre
mydata = {}
if ("nom" in diction.keys()):
if diction['nom']:
mydata['nom'] = diction['nom']
if ("adr_street" in diction.keys()):
if diction['adr_street']:
mydata['adr_street'] = diction['adr_street']
if ("adr_city" in diction.keys()):
if diction['adr_city']:
mydata['adr_city'] = diction['adr_city']
if ("adr_zip" in diction.keys()):
if diction['adr_zip']:
mydata['adr_zip'] = diction['adr_zip']
if ("adr_country" in diction.keys()):
if diction['adr_country']:
mydata['adr_country'] = diction['adr_country']
if ("email" in diction.keys()):
if diction['email']:
mydata['email'] = diction['email']
if ("telephone" in diction.keys()):
if diction['telephone']:
mydata['telephone'] = diction['telephone']
if ("pwd" in diction.keys()):
if diction['pwd']:
mydata['pwd'] = diction['pwd']
if ("contact_nom" in diction.keys()):
if diction['contact_nom']:
mydata['contact_nom'] = diction['contact_nom']
if ("contact_prenom" in diction.keys()):
if diction['contact_prenom']:
mydata['contact_prenom'] = diction['contact_prenom']
if ("contact_tel" in diction.keys()):
if diction['contact_tel']:
mydata['contact_tel'] = diction['contact_tel']
if ("contact_mail" in diction.keys()):
if diction['contact_mail']:
mydata['contact_mail'] = diction['contact_mail']
# Creation du RecId du user
mydata['recid'] = mycommon.create_user_recid()
mydata['active'] = '0'
mydata['locked'] = '0'
print(str(datetime.now()) + " webservice : diction = "+str(mydata))
coll_name = dbname['partnair_account']
# Verification que cette adresse email n'existe pas
tmp = coll_name.find({'email': str(mydata['email']) }).count()
logging.info(" TMP = "+str(tmp))
if( tmp > 0 ):
mycommon.myprint("l'adresse email '"+str(mydata['email'])+"' existe deja, impossible de créer le compte partenaire ")
return False, "l'adresse email '"+str(mydata['email'])+"' existe deja, impossible de créer le compte partenaire "
ret_val = coll_name.insert_one(mydata)
mail.send_partner_account_mail(ret_val.inserted_id, str(mydata['email']))
return True, " Le partenaire a été créé"
except Exception as e:
mycommon.myprint(e)
return False, "Impossible de créer le partenaire"
'''
MAJ d'un partenaire.
la clé est l'adresse email principale
'''
def update_partner_account(diction):
try:
client = MongoClient(CONNECTION_STRING)
# Dictionnaire des champs utilisables
'''
# Verification que les champs reçus dans l'API sont bien dans la liste des champs autorisés
# Cela evite le cas ou une entité tierce ajouter les valeurs inconnu dans l'API
# Ici on doit mettre tous les champs possible (obligatoire ou non) de la BDD dans la liste
# field_list.
'''
field_list = ['nom', 'adr_street', 'adr_city', 'adr_zip', 'adr_country',
'email', 'pwd', 'telephone', 'contact_nom', 'contact_prenom', 'contact_tel',
'contact_mail', 'token']
incom_keys = diction.keys()
for val in incom_keys:
if val not in field_list:
mycommon.myprint(" Creation partner account : Le champ '" + val + "' n'existe pas, Creation partenaire annulée")
return False, " Creation partner account : Le champ '" + val + "' n'existe pas, Creation partenaire annulée"
'''
Une fois qu'on a controlé que toutes les clés mise dans l'API sont correcte. etape precedente,
On controle que les champs obligatoires sont presents dans la liste
'''
field_list_obligatoire = ['token']
for val in field_list_obligatoire:
if val not in diction:
mycommon.myprint(" La valeur '" + val + "' n'est pas presente dans liste ")
return False, " La valeur '" + val + "' n'est pas presente dans liste "
# recuperation des paramettre
my_email = ""
my_token = ""
if ("nom" in diction.keys()):
if diction['nom']:
my_token = diction['token']
# Verifier la validité du token
retval = mycommon.check_token_validity("", my_token)
if retval is False :
return False, " Le token n'est pas valide"
mydata = {}
if ("nom" in diction.keys()):
if diction['nom']:
mydata['nom'] = diction['nom']
if ("adr_street" in diction.keys()):
if diction['adr_street']:
mydata['adr_street'] = diction['adr_street']
if ("adr_city" in diction.keys()):
if diction['adr_city']:
mydata['adr_city'] = diction['adr_city']
if ("adr_zip" in diction.keys()):
if diction['adr_zip']:
mydata['adr_zip'] = diction['adr_zip']
if ("adr_country" in diction.keys()):
if diction['adr_country']:
mydata['adr_country'] = diction['adr_country']
if ("email" in diction.keys()):
if diction['email']:
my_email = diction['email']
if ("telephone" in diction.keys()):
if diction['telephone']:
mydata['telephone'] = diction['telephone']
if ("pwd" in diction.keys()):
if diction['pwd']:
mydata['pwd'] = diction['pwd']
if ("contact_nom" in diction.keys()):
if diction['contact_nom']:
mydata['contact_nom'] = diction['contact_nom']
if ("contact_prenom" in diction.keys()):
if diction['contact_prenom']:
mydata['contact_prenom'] = diction['contact_prenom']
if ("contact_tel" in diction.keys()):
if diction['contact_tel']:
mydata['contact_tel'] = diction['contact_tel']
if ("contact_mail" in diction.keys()):
if diction['contact_mail']:
mydata['contact_mail'] = diction['contact_mail']
mydata['date_update'] = str(datetime.now())
print(str(datetime.now()) + " webservice : diction = " + str(mydata))
dbname = client['cherifdb']
coll_name = dbname['partnair_account']
ret_val = coll_name.find_and_modify(query={'email': str(my_token), 'locked': '0'},
update={"$set": mydata}
)
if (ret_val and ret_val['_id']):
mycommon.myprint("Le partenaire a bien ete mise à jour =" + str(ret_val['_id']))
return True, "Le partenaire a bien ete mise à jour"
except Exception as e:
mycommon.myprint(e)
return False, "Impossible de mettre à jour le partenaire"
'''
cette fonction valide un compte partenaire
La modification ne s'effectue que si le compte n'est pas verrouillé.
'locked'=0
'''
def valide_partnair_account(value):
try:
client = MongoClient(CONNECTION_STRING)
dbname = client['cherifdb']
coll_name = dbname['partnair_account']
tmp = coll_name.find({'_id':ObjectId(str(value))})
print(" ########## Email = "+str(tmp[0]['email']))
print(" ########## recid = " + str(tmp[0]['recid']))
now = datetime.now()
ret_val = coll_name.find_and_modify(query={'_id':ObjectId(str(value)), 'locked':'0'},
update={"$set":
{'active': "1","date_update":str(now)}
}
)
if( ret_val and ret_val['_id']):
mycommon.myprint("La modif a bien ete faite ="+str(ret_val['_id']))
# A ce niveau le login et passe sont ok.
# il faut donc créer le token et renvoyer le token.
my_token = mycommon.create_token_urlsafe()
# Enregistrement du token
dbname2 = client['cherifdb']
token_collection = dbname2['user_token']
tokenfield = {}
tokenfield['token'] = my_token
tokenfield['email'] = str(tmp[0]['email'])
tokenfield['recid'] = str(tmp[0]['recid'])
tokenfield['date_update'] = str(datetime.now())
tokenfield['valide'] = '1'
ret_val = token_collection.insert_one(tokenfield)
if ret_val and ret_val.inserted_id:
mycommon.myprint("Ajout Token OK, _id = " + str(ret_val.inserted_id))
return 'True', my_token
else:
mycommon.myprint(" Impossible d'enregistrer le token " + my_token)
return False, "Impossible de valider le compte"
else:
mycommon.myprint(" Aucune modif n'a été faite")
return False, "Impossible de valider le compte"
except Exception as e:
mycommon.myprint( e)
return False, "Impossible de valider le compte"
'''
Recuperation d'un partenaire
'''
def get_partner_account(diction):
try:
# Dictionnaire des champs utilisables
field_list = ['token']
incom_keys = diction.keys()
for val in incom_keys:
if val not in field_list:
mycommon.myprint(" Le champ '" + val + "' n'existe pas, requete annulée")
return False, " Impossible de recuperer les informations"
'''
Une fois qu'on a controlé que toutes les clés mise dans l'API sont correcte. etape precedente,
On controle que les champs obligatoires sont presents dans la liste
'''
field_list_obligatoire = [ 'token']
for val in field_list_obligatoire:
if val not in diction:
mycommon.myprint(" : La valeur '" + val + "' n'est pas presente dans liste ")
return False, " Impossible de recuperer les informations"
# recuperation des paramettre
email_value = ""
token_value = ""
if diction['token']:
token_value = diction['token']
coll_name = dbname['partnair_account']
# Verification de la valididé du token
coll_token = dbname['user_token']
# Verification de la validité du token/mail dans le cas des user en mode connecté
retval = mycommon.check_token_validity(email_value, token_value )
if retval is False:
mycommon.myprint("Le token n'est pas valide")
return False, " Impossible de recuperer les informations"
'''tmp_count = coll_token.find({'email':email_value, 'token': token_value, 'valide': '1'}).count()
if (tmp_count <= 0):
mycommon.myprint("L'email ou le token ne sont pas valident")
return False
'''
coll_token = dbname['user_token']
tmp = coll_token.find({ 'token': str(token_value), 'valide': '1'})
partnere_recid = tmp[0]['recid']
print(" parters RECID = "+str(partnere_recid))
RetObject = []
for retVal in coll_name.find({'recid': str(partnere_recid)}):
mycommon.myprint (str(retVal))
user = retVal
RetObject.append(JSONEncoder().encode(user))
return True, RetObject
except Exception as e:
mycommon.myprint(e)
return False, " Impossible de recuperer les informations"