def update_visit(visit_id): try: current_user = get_user_if_exists() update_data = dict(request.get_json()) visit = VisitModel.query.filter_by(id_visit=visit_id).first() if current_user.id_user != visit.id_role: return ("unauthorized"), 403 try: # Delete selected existing media id_media_to_delete = json.loads(update_data.get("delete_media")) if len(id_media_to_delete): db.session.query(MediaOnVisitModel).filter( MediaOnVisitModel.id_media.in_(tuple(id_media_to_delete)), MediaOnVisitModel.id_data_source == visit_id, ).delete(synchronize_session="fetch") db.session.query(MediaModel).filter( MediaModel.id_media.in_(tuple(id_media_to_delete)) ).delete(synchronize_session="fetch") except Exception as e: current_app.logger.warning("[update_visit] delete media ", e) raise GeonatureApiError(e) visit.date = update_data.get("date") visit.json_data = update_data.get("data") db.session.commit() return ("Visit updated successfully"), 200 except Exception as e: current_app.logger.critical("[update_visit] Error: %s", str(e)) return {"message": str(e)}, 400
def delete_visit(visit_id): current_user = get_user_if_exists() # try: visit = ( db.session.query(VisitModel) .filter(VisitModel.id_visit == visit_id) .first() ) if current_user.id_user == visit.id_role: VisitModel.query.filter_by(id_visit=visit_id).delete() db.session.commit() return ("Site deleted successfully"), 200 else: return ("delete unauthorized"), 403
def delete_site(site_id): current_user = get_user_if_exists() try: site = (db.session.query( SiteModel, UserModel).filter(SiteModel.id_site == site_id).join( UserModel, SiteModel.id_role == UserModel.id_user, full=True).first()) if current_user.id_user == site.id_role: SiteModel.query.filter_by(id_site=site_id).delete() db.session.commit() return ("Site deleted successfully"), 200 else: return ("delete unauthorized"), 403 except Exception as e: return {"message": str(e)}, 500
def delete_observation(id_obs): current_user = get_user_if_exists() try: if current_user: ObservationModel.query.filter( ObservationModel.id_observation == id_obs, ObservationModel.id_role == current_user.id_user, ).delete() db.session.commit() return ("observation deleted successfully"), 200 else: return ("delete unauthorized"), 403 except Exception as e: return {"message": str(e)}, 500
def delete_user(): """list all logged users --- tags: - Authentication summary: Delete current logged user consumes: - application/json produces: - application/json responses: 200: description: Delete current logged user """ # Get logged user current_app.logger.debug("[delete_user] Delete current user") current_user = get_user_if_exists() if current_user: username = current_user.username current_app.logger.debug( "[delete_user] current user is {}".format(username)) try: db.session.query(UserModel).filter( UserModel.id_user == current_user.id_user).delete() db.session.commit() current_app.logger.debug( "[delete_user] user {} succesfully deleted".format(username)) except Exception as e: db.session.rollback() raise GeonatureApiError(e) return {"message": str(e)}, 400 return ( { "message": """Account "{}" have been successfully deleted""".format( username) }, 200, )
def update_site(): try: current_user = get_user_if_exists() update_data = dict(request.get_json()) update_site = {} for prop in ["name", "id_type"]: update_site[prop] = update_data[prop] try: shape = asShape(update_data["geometry"]) update_site["geom"] = from_shape(Point(shape), srid=4326) except Exception as e: current_app.logger.warning("[update_site] coords ", e) raise GeonatureApiError(e) site = SiteModel.query.filter_by(id_site=update_data.get("id_site")) if current_user.id_user != site.first().id_role: return ("unauthorized"), 403 site.update(update_site, synchronize_session="fetch") db.session.commit() return ("site updated successfully"), 200 except Exception as e: current_app.logger.critical("[update_site] Error: %s", str(e)) return {"message": str(e)}, 400
def logged_user(): """current user model --- tags: - Authentication summary: current registered user produces: - application/json responses: 200: description: current user model """ try: user = get_user_if_exists() if flask.request.method == "GET": # base stats, to enhance as we go result = user.as_secured_dict(True) result["stats"] = { "platform_attendance": db.session.query(func.count(ObservationModel.id_role)).filter( ObservationModel.id_role == user.id_user).one()[0] } return ( { "message": "Vos données personelles", "features": result }, 200, ) if flask.request.method == "PATCH": is_admin = user.admin or False current_app.logger.debug( "[logged_user] Update current user personnal data") request_data = dict(request.get_json()) if "extention" in request_data and "avatar" in request_data: extention = request_data["extention"] imgdata = base64.b64decode(request_data["avatar"].replace( "data:image/" + extention + ";base64,", "")) filename = "avatar_" + user.username + "." + extention request_data["avatar"] = filename if os.path.exists( os.path.join( str(MEDIA_DIR), str(user.as_secured_dict(True)["avatar"]), )): os.remove( os.path.join( str(MEDIA_DIR), str(user.as_secured_dict(True)["avatar"]), )) try: handler = open(os.path.join(str(MEDIA_DIR), str(filename)), "wb+") handler.write(imgdata) handler.close() except Exception as e: return ( { "message": e }, 500, ) for data in request_data: if hasattr(UserModel, data) and data not in { "id_user", "username", "admin", }: setattr(user, data, request_data[data]) if "newPassword" in request_data: user.password = UserModel.generate_hash( request_data["newPassword"]) user.admin = is_admin user.update() return ( { "message": "Informations personnelles mises à jour. Merci.", "features": user.as_secured_dict(True), }, 200, ) except Exception as e: # raise GeonatureApiError(e) current_app.logger.error("AUTH ERROR:", str(e)) return ( { "message": str(e) }, 400, )
def export_sites_xls(user_id): current_user = get_user_if_exists() try: if current_user.id_user != user_id: return ("unauthorized"), 403 title_style = xlwt.easyxf("font: bold on") date_style = xlwt.easyxf(num_format_str="D/M/YY") wb = xlwt.Workbook() # SITES SHEET ws = wb.add_sheet("mes sites") sites = _get_user_sites(user_id) fields = ( { "col_name": "id_site", "getter": lambda s: s.id_site }, { "col_name": "Programme", "getter": lambda s: s.program.title }, { "col_name": "Type", "getter": lambda s: s.site_type.type }, { "col_name": "Nom", "getter": lambda s: s.name }, { "col_name": "Coord. x", "getter": lambda s: s.coordinates[0] }, { "col_name": "Coord. y", "getter": lambda s: s.coordinates[1] }, { "col_name": "Date création", "getter": lambda s: s.timestamp_create, "style": date_style, }, ) row = 0 for col, field in enumerate(fields): ws.write(row, col, field["col_name"], title_style) row += 1 for site in sites: site.coordinates = get_geojson_feature( site.geom)["geometry"]["coordinates"] for col, field in enumerate(fields): args = [] if field.get("style"): args.append(field.get("style")) ws.write(row, col, field["getter"](site), *args) row += 1 # VISITS SHEET ws = wb.add_sheet("mes visites") visits = VisitModel.query.filter_by(id_role=user_id) basic_fields = ( { "col_name": "id_visit", "getter": lambda s: s.id_visit }, { "col_name": "Site", "getter": lambda s: s.site.name }, { "col_name": "Date", "getter": lambda s: s.date, "style": date_style, }, ) json_keys = list( set([key for v in visits for key in v.json_data.keys()])) row, col = 0, 0 for field in basic_fields: ws.write(row, col, field["col_name"], title_style) col += 1 for key in json_keys: ws.write(row, col, key, title_style) col += 1 row, col = 1, 0 for visit in visits: for field in basic_fields: args = [] if field.get("style"): args.append(field.get("style")) ws.write(row, col, field["getter"](visit), *args) col += 1 for key in json_keys: ws.write(row, col, visit.json_data.get(key)) col += 1 row += 1 col = 0 # In memory save and return xls file xls_file = io.BytesIO() wb.save(xls_file) output = make_response(xls_file.getvalue()) output.headers["Content-Disposition"] = ("attachment; filename=" + "export_sites.xls") output.headers["Content-type"] = "application/xls" return output except Exception as e: current_app.logger.warning("Error: %s", str(e)) return {"error_message": str(e)}, 400