def on_get(self, req, resp): """Recuperation de la liste des hopitaux disponible --- description: Recuperation de la liste des hopitaux responses: 200: description: Recuperation de la liste des hopitaux schema: ResponseSchema 401: description: Erreur de token schema: ResponseSchema """ rootLogger.info("Appel de la commande GET de l'api fh_hospitals") try: user = connect_from_header_connection(req, resp, self.db) except Exception as e: rootLogger.error(str(e)) send_resp(resp, falcon.HTTP_401, 401, "error", str(e)) return rootLogger.debug( "Récupération des hopitaux de l'utilisateur {!r}".format(user)) hospitals = self.db.list_hospitals(user['id']) hosp = {} hosp['hospitals'] = [] for hospital in hospitals: rootLogger.debug(hospital) hosp['hospitals'].append({"name": hospital[2], "id": hospital[0]}) send_resp(resp, falcon.HTTP_200, 200, 'hospitals', hosp)
def on_post(self, req, resp): rootLogger.info("Appel de la commande POST de l'api fh_login") # Demande de connexion à l'application rootLogger.debug("Req = {!r}".format(req)) try: data = json.load(req.stream) except Exception as e: send_resp(resp, falcon.HTTP_400, 400, "error", "Erreur lors de l'analyse du body envoyé") return rootLogger.debug("data = {!r}".format(data)) try: idinfo = valid_google_oauth_token(data['token']) if not self.db.check_user_exist(idinfo['email']): rootLogger.info( "L'utilisateur {!r} n'éxiste pas encore dans la base". format(idinfo['email'])) self.db.add_user(idinfo['email']) send_resp(resp, falcon.HTTP_200, 200, "info", "Token valide") return except Exception as e: rootLogger.error(str(e)) send_resp(resp, falcon.HTTP_401, 401, "error", str(e)) return
def list_hospitals(self, userId): rootLogger.debug( "Récupération des hopitaux de l'utilsateur {!r} ".format(userId)) curseur = self.cnx.cursor() curseur.execute( "SELECT * from FH_hospital where id_user={!r}".format(userId)) result = curseur.fetchall() return result
def get_user(self, email): rootLogger.debug("Récupération de l'utilisateur {!r}".format(email)) curseur = self.cnx.cursor() curseur.execute( "SELECT id from FH_user where email={!r}".format(email)) result = curseur.fetchall() # ligne 1, colone 1 return result[0][0]
def migration(self): rootLogger.debug("Lancement de la migration yoyo") backend = get_backend( 'mysql://{user}:{password}@{host}/{database}'.format(**BDD_INFO)) migrations = read_migrations('sql') with backend.lock(): backend.apply_migrations(backend.to_apply(migrations)) rootLogger.debug("migration terminée")
def valid_google_oauth_token(token): CLIENT_ID = GOOGLE_API_KEY google_token = token # validation du token google idinfo = id_token.verify_oauth2_token(google_token, requests.Request(), CLIENT_ID) rootLogger.debug("idinfo = {!r}".format(idinfo)) if idinfo['iss'] not in [ 'accounts.google.com', 'https://accounts.google.com' ]: raise ValueError('Wrong issuer.') rootLogger.info("Connexion google réussi pour {!r}".format( idinfo['email'])) return idinfo
def on_post(self, req, resp): """Creation d'un nouvel hopital --- description: Creation d'un nouvel hopital responses: 200: description: Recuperation de la liste des hopitaux schema: ResponseSchema 400: description: Erreur d'analyse du body schema: ResponseSchema 401: description: Erreur de token schema: ResponseSchema 409: description: La ressource existe deja schema: ResponseSchema """ rootLogger.info("Appel de la commande POST de l'api fh_hospitals") try: user = connect_from_header_connection(req, resp, self.db) except Exception as e: rootLogger.error(str(e)) send_resp(resp, falcon.HTTP_401, 401, "error", str(e)) return try: data = json.load(req.stream) except Exception as e: send_resp(resp, falcon.HTTP_400, 400, "error", "Erreur lors de l'analyse du body envoyé") return rootLogger.debug("data = {!r}".format(data)) try: self.db.add_hospital(user['id'], data['name']) send_resp(resp, falcon.HTTP_201, 201, "Info", "L'hopital {!s} à été créé".format(data['name'])) except mysql.connector.Error as e: if e.errno == errorcode.ER_DUP_ENTRY: send_resp(resp, falcon.HTTP_409, 409, "error", "L'hopital existe déjà") else: print(e) send_resp(resp, falcon.HTTP_500, 500, "error", "Erreur non géré") return
def connect_from_header_connection(req, resp, db): """ Take request Send email + base id """ user = {} token = req.get_header('Authorization') #rootLogger.debug("Token = {!r}".format(token)) # validation du token et récupération de l'id utilisateur idinfo = valid_google_oauth_token(token) user['email'] = idinfo['email'] if not db.check_user_exist(user['email']): send_resp(resp, falcon.HTTP_401, "401", "error", "Vous devez d'abord vous connecter pour créer un compte") user['id'] = db.get_user(user['email']) rootLogger.debug("user = {!r}".format(user)) return user
def on_get(self, req, resp): """Recuperation de la liste des salles --- description: Recuperation de la liste des salles responses: 200: description: Recuperation de la liste des salles schema: ResponseSchema 401: description: Erreur de token schema: ResponseSchema """ rootLogger.info( "Appel de la commande GET de l'api fh_salles sans paramètre") try: user = connect_from_header_connection(req, resp, self.db) except Exception as e: rootLogger.error(str(e)) send_resp(resp, falcon.HTTP_401, 401, "error", str(e)) return rootLogger.debug("Récupération des informations des salles en base") salles = self.db.list_salles() salle = {} salle['salles'] = {} rootLogger.debug(salles) for key, value in salles.items(): rootLogger.debug("{}=>{}".format(key, value)) salle['salles'][key] = {} salle['salles'][key]['levels'] = value send_resp(resp, falcon.HTTP_200, 200, 'salles', salle)
def check_user_exist(self, email): rootLogger.debug("Test de l'existance du mail {!r}".format(email)) curseur = self.cnx.cursor() curseur.execute( "SELECT id from FH_user where email={!r}".format(email)) result = curseur.fetchall() if len(result) == 0: rootLogger.debug("email non trouvé") return False else: rootLogger.debug("email trouvé") return True
def list_salles(self): rootLogger.debug("Récupération des informations des salles") curseur = self.cnx.cursor() curseur.execute("SELECT * from FH_Salles_Def") result = {} for room in curseur.fetchall(): rootLogger.debug( "Récupération des informations de la salle {!r}".format(room)) room_info = {} curseur.execute( "SELECT * from FH_Salles_Stats where `id_salles`={!r}".format(room[0])) for info_read in curseur.fetchall(): salle_lvl = info_read[2] salle_cmp = info_read[3] salle_tim = info_read[4] room_info[salle_lvl] = {} room_info[salle_lvl]['comp'] = salle_cmp room_info[salle_lvl]['tim'] = salle_tim rootLogger.debug(room_info) result[room[1]] = room_info rootLogger.debug("liste_salles={!r}".format(result)) return result
def __init__(self): rootLogger.debug("Initialisation de la classe fh_bdd") self.migration() try: rootLogger.debug("Connexion à la base...") self.cnx = mysql.connector.connect(**BDD_INFO) rootLogger.debug("Connecté à la base...") except mysql.connector.Error as err: if err.errno == errorcode.ER_ACCESS_DENIED_ERROR: rootLogger.error( "Something is wrong with your user name or password") elif err.errno == errorcode.ER_BAD_DB_ERROR: rootLogger.error("Database does not exist") else: rootLogger.error(err) self.cnx.autocommit = True
def __init__(self): rootLogger.debug("Initialisation de l'api fh_salles") self.db = fh_bdd()
def add_hospital(self, userid, name): rootLogger.debug( "Création de l'hopital {!r} pour l'utilisateur {!r}".format(name, userid)) curseur = self.cnx.cursor() curseur.execute( "INSERT INTO `FH_hospital` (`id`, `id_user`, `nom`) VALUES (NULL,{!r},%s)".format(userid), (name,))
def add_user(self, email): rootLogger.debug("Création de l'utilisateur {!r}".format(email)) curseur = self.cnx.cursor() curseur.execute( "INSERT INTO `FH_user` (`id`, `email`) VALUES (NULL, {!r})".format(email))