def __init__(self, namespace, config, sio): super().__init__(namespace) self.chat_service = ChatService(config) self.chat_room_service = ChatRoomService(config) self.linkedin_login = LinkedInLogin(config) self.user_service = UserService(config) self.offer_service = OfferService(config) self.config = config
def _create_generic_user(role_id: int = 3, name_on_page: str = "customer"): """ This method contains the logic to create a new user with a different role :param role_id: role id on database this mean that is possible :param name_on_page: name to customize the page inside the template :return: response template """ form = UserForm() current_app.logger.debug("Create a {} with method {}".format( name_on_page, request.method)) if request.method == "POST": if form.validate_on_submit(): current_app.logger.debug("Form validate") q_user_email = UserService.user_is_present(email=form.email.data) q_user_phone = UserService.user_is_present(phone=form.phone.data) current_app.logger.debug( "user with email is null? {}".format(q_user_email is None)) current_app.logger.debug( "user with phone is null? {}".format(q_user_phone is None)) if (q_user_email is not None) or (q_user_phone is not None): return render_template( "create_user.html", form=form, message="Email {} and/or number {} already registered". format(form.email.data, form.phone.data), _test="error_create_user_test", type=name_on_page, ) user = UserService.create_user(form, role_id) if user is False: current_app.logger.error( "An error occured while creating the user") return render_template( "create_user.html", form=form, message="An error occured while creating the user", _test="error_create_user_test", type=name_on_page, ) SendEmailService.confirm_registration(form.email.data, form.firstname.data) # if user is operator, do the login and redirect to the home # in this way the home will show create restaurant page if role_id == 2: # we need to take the user from email current_app.logger.debug( "Requesting user with email {}".format(form.email.data)) user = UserService.get_user_by_email(form.email.data) # set the session session["current_user"] = user.serialize() login_user(user) session["ROLE"] = "OPERATOR" return redirect("/") else: return redirect("/login") return render_template("create_user.html", form=form, type=name_on_page)
def user_delete(): operation = UserService.delete_user(current_user.id) if operation: return redirect("/logout") else: return render_template( "generic_error.html", message= "An error occurred while deleting user.Please try again later.")
def search_contacts(): form = SearchUserForm() if request.method == "POST": if form.validate_on_submit(): email = form.email.data phone = form.phone.data if len(email) == 0 and len(phone) == 0: return render_template( "search_contacts.html", _test="search_contacts_no_data", form=form, message="Insert an email or a phone number", ) user_email = UserService.user_is_present(email) user_phone = UserService.user_is_present(phone=phone) if user_email is None and user_phone is None: return render_template( "/search_contacts.html", form=form, message="User not exist inside the sistem", _test="search_contact_not_registered", ) contacts = HealthyServices.search_contacts(email, phone) if isinstance(contacts, list): return render_template("list_contacts.html", _test="list_page", contacts=contacts) elif isinstance(contacts, str): return render_template( "search_contacts.html", _test="search_contacts_no_positive", form=form, message=contacts, ) else: return render_template( "search_contacts.html", _test="search_contacts_no_positive", form=form, message="Error", ) return render_template("/search_contacts.html", form=form)
def wrapper(*args, **kwargs): user_id = None auth_headers = request.headers.get("Authorization", "").split() try: if len(auth_headers) != 2: raise errors.HTTPTokenRequired token = auth_headers[1] data = jwt.decode(token, verify=False) cognito_id = data["sub"] email = data["email"] groups = data.get("cognito:groups") or [] if SystemGroupName.USER_GROUP_NAME in groups or SystemGroupName.ADMIN_GROUP_NAME in groups: user_svc = UserService(ProductionFactory()) user = user_svc.get_user_by_cognito_id(cognito_id) if not user: raise errors.HTTPInvalidTokenError else: user_id = user["id"] else: raise errors.HTTPPermissionDenied auth_data = { "email": email, "user_id": user_id, "cognito_id": cognito_id, "groups": groups, "permissions": user["permissions"] } return func(auth_data, *args, **kwargs) except jwt.ExpiredSignatureError as e: raise errors.HTTPExpiredSignatureError except jwt.InvalidTokenError as e: raise errors.HTTPInvalidTokenError except HTTPException as e: traceback.print_exc() raise e except ValidationError as e: traceback.print_exc() raise errors.HTTPBadRequest(custom_message=json.dumps(str(e))) except Exception as e: traceback.print_exc() raise errors.HTTPServerError
def mark_positive(user_email: str = None, user_phone: str = None) -> str: if user_email is None and user_phone is None: return "Insert an email or a phone number" response = UserService.mark_positive(user_email, user_phone) if response is not None: contacts = HealthyServices.search_contacts_for_email( user_email, user_phone) SendEmailService.send_possible_contact( contacts) ## We assume that is true return "" else: return "An error occurs, please try again"
def login(): form = LoginForm() if request.method == "POST": if form.validate_on_submit(): email, password = form.data["email"], form.data["password"] url = "{}/login".format(USER_MICROSERVICE_URL) current_app.logger.debug("URL to user microservice: {}".format(url)) # Look at https://urllib3.readthedocs.io/en/latest/user-guide.html#certificate-verification user, status_code = UserService.login_user(email, password) # TODO improve the error code inside the User API if user is None and status_code != 404: return render_template( "login.html", form=form, _test="error_login", message="Connection refused", ) if user is None and status_code == 404: return render_template( "login.html", form=form, _test="error_login", message="User not exist", ) if UserService.log_in_user(user): return redirect("/") else: current_app.logger.error("log in failed") return render_template( "login.html", form=form, _test="error_login", message="An error occurred during log in. Please try later", ) return render_template("login.html", _test="first_visit_login", form=form)
def delete_reservation(reservation_id): deleted = BookingServices.delete_book(reservation_id, current_user.id) reservations_as_list = UserService.get_customer_reservation( None, None, current_user.id) form = ReservationForm() return render_template( "user_reservations.html", reservations_as_list=reservations_as_list, my_date_formatter_iso=my_date_formatter_iso, deleted=deleted, _test="del_rest_test", form=form, )
def myreservation(): # filter params fromDate = request.args.get("fromDate", type=str) toDate = request.args.get("toDate", type=str) reservations_as_list = UserService.get_customer_reservation( fromDate, toDate, current_user.id) form = ReservationForm() return render_template( "user_reservations.html", reservations_as_list=reservations_as_list, my_date_formatter_iso=my_date_formatter_iso, form=form, _test="customer_reservations_test", )
def unmark_positive(user_email: str = None, user_phone: str = None) -> str: """ This method perform the request to unmark th user as positive. """ response = UserService.unmark_positive(user_email, user_phone) if response[0] is None: return "An error occurs" if response[1] == 400: return "An error occurs, please try again" if response[1] == 404: # Logic error make the check of the user inside the UI # If the user don't exist we don't need to perform the request return "The customer not registered or not positive" if response[1] == 200: return "" return "Error on Server please try again."
def user_data(): if request.method == "POST": form = UserEditForm() if form.validate_on_submit(): user = UserService.modify_user(form) if user is not None: session["current_user"] = user.serialize() return render_template("user_data.html", form=form, message="Modified") else: return render_template("user_data.html", form=form, error="Error during the operation") current_app.logger.debug(form.errors.items()) return render_template("user_data.html", form=form, message="Error in the data") user = current_user if user is not None: form = UserEditForm(obj=user) return render_template("user_data.html", form=form)
from unittest.mock import patch from src.config import APP_CONFIG from src.database import User, UserRequest, session_scope from src.services import UserService from tests.fixtures import create_user from tests.utils import assert_dict_in user_service = UserService(config=APP_CONFIG) def test_create__is_buy(): user_params = { "email": "*****@*****.**", "full_name": "Ben", "provider_user_id": "testing", "display_image_url": "http://blah", "is_buy": True, "auth_token": None, } committee_email = create_user(is_committee=True)["email"] with patch("src.services.EmailService.send_email") as mock: user_service.create_if_not_exists(**user_params) mock.assert_any_call(emails=[user_params["email"]], template="register_buyer") mock.assert_any_call(emails=[committee_email], template="new_user_review") with session_scope() as session:
def search_contacts(user_email: str, user_phone: str): if user_email == "" and user_phone == "": return "Insert an email or a phone number" response = UserService.search_possible_contacts(user_email, user_phone) if response is None: return "The customer not registered or not positive" contact_users_GUI = [] # now we have the information about the positivity of the user in response date_marking = response["from_date"] user_id = response["user_id"] # start to check contacts # API: get all reservation of the customer between date_marking and date_marking -14 date_marking = datetime.strptime(date_marking, "%Y-%m-%d") to_date = date_marking - timedelta(days=14) reservations_customer = BookingServices.get_reservation_by_constraint( user_id, from_data=to_date, to_data=date_marking) i = 1 if reservations_customer is not None: all_reservations = BookingServices.get_reservation_by_constraint( from_data=to_date, to_data=date_marking) if all_reservations is None: return None for reservation in reservations_customer: restaurant_id = reservation["table"]["restaurant"]["id"] start = datetime.strptime(reservation["reservation_date"], "%Y-%m-%dT%H:%M:%SZ") end = datetime.strptime(reservation["reservation_end"], "%Y-%m-%dT%H:%M:%SZ") current_app.logger.debug( "I'm working with reserv from {} to {}".format(start, end)) for one_reservation in all_reservations: restaurant_id_contact = one_reservation["table"][ "restaurant"]["id"] if restaurant_id_contact != restaurant_id: continue start_contact = datetime.strptime( one_reservation["reservation_date"], "%Y-%m-%dT%H:%M:%SZ") end_contact = datetime.strptime( one_reservation["reservation_end"], "%Y-%m-%dT%H:%M:%SZ") # if people are in the same restaurant in the same day if start.date() == start_contact.date(): openings = RestaurantServices.get_opening_hours_restaurant( restaurant_id) dayNumber = start.weekday() restaurant_hours = [] current_app.logger.debug( "I got openings. Start is {}".format(dayNumber)) for opening in openings: if opening["week_day"] == dayNumber: restaurant_hours.append( datetime.strptime(opening["open_lunch"], "%H:%M")) restaurant_hours.append( datetime.strptime(opening["close_lunch"], "%H:%M")) restaurant_hours.append( datetime.strptime(opening["open_dinner"], "%H:%M")) restaurant_hours.append( datetime.strptime(opening["close_dinner"], "%H:%M")) # if people are in the restaurant at lunch or dinner if (restaurant_hours[0].time() <= start.time() and restaurant_hours[1].time() >= end.time() ) or (restaurant_hours[2].time() <= start.time() and restaurant_hours[3].time() >= end.time()): # people are in the same restaurant at lunch # if they are in the same time if (end_contact < start or start_contact > end) is False: # they are contacts! # API: get user email and name of the contact user = UserService.get_user_by_id( one_reservation["customer_id"]) if user is not None: contact_users_GUI.append([ i, user.firstname + " " + user.lastname, user.dateofbirth, user.email, user.phone, ]) i += 1 return contact_users_GUI
def report_positive(): """ This method call the user service to get all the positive """ return UserService.get_list_of_positive_user()
def index(): restaurants = RestaurantServices.get_all_restaurants() if current_user is None: _test = "anonymous_test" else: _test = "logged_test" if "ROLE" in session: if session["ROLE"] == "HEALTH": positives = UserService.get_count_of_positive_user() return render_template("index_health.html", _test=_test, n_positive=positives) elif session["ROLE"] == "OPERATOR": if "RESTAURANT_ID" in session: restaurant_id = session["RESTAURANT_ID"] model = RestaurantServices.get_all_restaurants_info( restaurant_id) if model is None: abort(501) weekDaysLabel = [ "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday", ] return render_template( "restaurantsheet.html", id=restaurant_id, name=model.name, lat=model.lat, lon=model.lon, phone=model.phone, covid_measures=model.covid_measures, hours=model.opening_hours, cuisine=model.cusine, weekDaysLabel=weekDaysLabel, photos=model.photos, reviews=RestaurantServices.get_three_reviews( restaurant_id), dishes=model.dishes, _test=_test, ) else: return render_template("norestaurant.html", _test=_test) elif session["ROLE"] == "CUSTOMER": form = ReservationForm() is_positive = UserService.is_positive(current_user.id) return render_template( "index_customer.html", _test=_test, restaurants=restaurants, form=form, is_positive=is_positive, ) return render_template("index.html", _test=_test, restaurants=restaurants)
import jwt from flask_pymongo import PyMongo from googlesearch import search from flask_expects_json import expects_json from src.services import UserService, TextService app = Flask(__name__, static_folder='static') JWT_SECRET = os.getenv('JWT_SECRET') assert JWT_SECRET ADMIN_EMAIL = os.getenv('ADMIN_EMAIL') assert ADMIN_EMAIL ADMIN_PASS = os.getenv('ADMIN_PASS') assert ADMIN_PASS app.config["MONGO_URI"] = os.getenv('MONGO_URI') mongo = PyMongo(app) # TODO: may be some issues in multiple threads user_service = UserService(mongo.db.users) text_service = TextService(mongo.db.texts) @app.before_first_request def ensure_admin(): user_service.ensure_admin_user(ADMIN_EMAIL, ADMIN_PASS) def allow_without_auth(func): func._allow_without_auth = True return func def allow_for_roles(roles): def _allow_for_roles(func): def __allow_for_roles(*args, **kwargs): if g.decoded is None or g.decoded['role'] not in roles: abort(403)
def search_contacts_for_email(user_email: str, user_phone: str): if user_email == "" and user_phone == "": return "Insert an email or a phone number" friends = [] contacts = [] past_restaurants = [] future_restaurants = [] if user_email != "": URL = USER_MICROSERVICE_URL + "/positiveinfo/email/" + str( user_email) else: URL = USER_MICROSERVICE_URL + "/positiveinfo/phone/" + str( user_phone) # check if the user exists # check if the user is positive (get also date of marking) (API) response = HttpUtils.make_get_request(URL) if response is None: return "Error, please try again" # now we have the information about the positivity of the user in response date_marking = response["from_date"] user_id = response["user_id"] # start to check contacts # API: get all reservation of the customer between date_marking and date_marking -14 date_marking = datetime.strptime(date_marking, "%Y-%m-%d") to_date = date_marking - timedelta(days=14) reservations_customer = BookingServices.get_reservation_by_constraint( user_id, from_data=to_date, to_data=date_marking) if reservations_customer is not None: # API: get all reservations between date_marking and date_m -14 all_reservations = BookingServices.get_reservation_by_constraint( from_data=to_date, to_data=date_marking) for reservation in reservations_customer: restaurant_id = reservation["table"]["restaurant"]["id"] restaurant = RestaurantServices.get_rest_by_id(restaurant_id) if restaurant is None: continue friends = friends + reservation["people"] start = datetime.strptime(reservation["reservation_date"], "%Y-%m-%dT%H:%M:%SZ") end = datetime.strptime(reservation["reservation_end"], "%Y-%m-%dT%H:%M:%SZ") past_restaurants.append({ "email": restaurant.owner_email, "name": restaurant.name, "date": start.strftime("%Y-%m-%dT%H:%M:%SZ"), }) for one_reservation in all_reservations: restaurant_id_contact = one_reservation["table"][ "restaurant"]["id"] if restaurant_id_contact != restaurant_id: continue start_contact = datetime.strptime( one_reservation["reservation_date"], "%Y-%m-%dT%H:%M:%SZ") end_contact = datetime.strptime( one_reservation["reservation_end"], "%Y-%m-%dT%H:%M:%SZ") # if people are in the same restaurant in the same day if start.date() != start_contact.date(): continue openings = RestaurantServices.get_opening_hours_restaurant( restaurant_id) dayNumber = start.weekday() restaurant_hours = [] for opening in openings: if opening["week_day"] == dayNumber: restaurant_hours.append( datetime.strptime(opening["open_lunch"], "%H:%M")) restaurant_hours.append( datetime.strptime(opening["close_lunch"], "%H:%M")) restaurant_hours.append( datetime.strptime(opening["open_dinner"], "%H:%M")) restaurant_hours.append( datetime.strptime(opening["close_dinner"], "%H:%M")) # if people are in the restaurant at lunch or dinner if (restaurant_hours[0].time() <= start.time() and restaurant_hours[1].time() >= end.time()) or ( restaurant_hours[2].time() <= start.time() and restaurant_hours[3].time() >= end.time()): # people are in the same restaurant at lunch # if they are in the same time if not ((end_contact < start) or (start_contact > end)): # they are contacts! # API: get user email and name of the contact user = UserService.get_user_by_id( one_reservation["customer_id"]) if user is not None: contacts.append({ "email": user.email, "name": user.firstname, "restaurant_name": restaurant.name, "date": start.strftime("%Y-%m-%dT%H:%M:%SZ"), }) friends = friends + one_reservation["people"] if user_email != "": customer_email = user_email else: URL = USER_MICROSERVICE_URL + "/" + str(user_id) user = HttpUtils.make_get_request(URL) customer_email = user["email"] # API booking: get all future booking of the customer future_reservations = BookingServices.get_reservation_by_constraint( user_id, from_data=to_date, to_data=date_marking) for future_reservation in future_reservations: date = datetime.strptime(reservation["reservation_date"], "%Y-%m-%dT%H:%M:%SZ") restaurant_id = future_reservation["table"]["restaurant"]["id"] restaurant = RestaurantServices.get_rest_by_id(restaurant_id) if restaurant is not None: future_restaurants.append({ "email": restaurant.owner_email, "name": restaurant.name, "date": date.strftime("%Y-%m-%dT%H:%M:%SZ"), "customer_email": customer_email, }) return { "friends": friends, "contacts": contacts, "past_restaurants": past_restaurants, "reservation_restaurants": future_restaurants, }
sentry_sdk.init( dsn="https://[email protected]/1800796", integrations=[SanicIntegration(), SqlalchemyIntegration()], before_send=sentry_before_send, ) app = Sanic(load_env=False) app.config.update(APP_CONFIG) sio = socketio.AsyncServer( async_mode="sanic", cors_allowed_origins=[], json=AcquityJson ) sio.attach(app) sio.register_namespace(ChatSocketService("/v1/chat", app.config)) app.user_service = UserService(app.config) app.sell_order_service = SellOrderService(app.config) app.buy_order_service = BuyOrderService(app.config) app.security_service = SecurityService(app.config) app.round_service = RoundService(app.config) app.match_service = MatchService(app.config) app.banned_pair_service = BannedPairService(app.config) app.chat_room_service = ChatRoomService(app.config) app.chat_service = ChatService(app.config) app.linkedin_login = LinkedInLogin(app.config) app.user_request_service = UserRequestService(app.config) initialize_cors(app) app.blueprint(blueprint)
class ChatSocketService(socketio.AsyncNamespace): def __init__(self, namespace, config, sio): super().__init__(namespace) self.chat_service = ChatService(config) self.chat_room_service = ChatRoomService(config) self.linkedin_login = LinkedInLogin(config) self.user_service = UserService(config) self.offer_service = OfferService(config) self.config = config async def _authenticate(self, token): linkedin_user = self.linkedin_login._get_user_profile(token=token) user = self.user_service.get_user_by_linkedin_id( user_id=linkedin_user.get("user_id")) return user.get("id") async def _get_chat_rooms(self, sid, user_id, user_type): rooms = self.chat_room_service.get_chat_rooms(user_id=user_id, user_type=user_type) for room in rooms: self.enter_room(sid, room.get("chat_room_id")) self.enter_room(sid, user_id) return rooms async def on_connect(self, sid, environ): return {"data": "success"} async def on_disconnect(self, sid): return {"data": "success"} async def on_req_chat_rooms(self, sid, data): user_id = await self._authenticate(token=data.get("token")) rooms = await self._get_chat_rooms(sid=sid, user_id=user_id, user_type=data.get("user_type")) await self.emit("res_chat_rooms", rooms, room=user_id) async def on_req_conversation(self, sid, data): user_id = await self._authenticate(token=data.get("token")) conversation = self.chat_service.get_conversation( user_id=user_id, chat_room_id=data.get("chat_room_id"), user_type=data.get("user_type"), ) await self.emit("res_conversation", conversation, room=user_id) async def on_req_new_message(self, sid, data): user_id = await self._authenticate(token=data.get("token")) room_id = data.get("chat_room_id") chat = self.chat_service.create_new_message( chat_room_id=data.get("chat_room_id"), message=data.get("message"), author_id=user_id, user_type=data.get("user_type"), ) await self.emit("res_new_message", chat, room=room_id) async def on_req_new_offer(self, sid, data): user_id = await self._authenticate(token=data.get("token")) room_id = data.get("chat_room_id") offer = self.offer_service.create_new_offer( author_id=user_id, chat_room_id=data.get("chat_room_id"), price=data.get("price"), number_of_shares=data.get("number_of_shares"), user_type=data.get("user_type"), ) await self.emit("res_new_offer", offer, room=room_id) async def on_req_accept_offer(self, sid, data): user_id = await self._authenticate(token=data.get("token")) room_id = data.get("chat_room_id") offer = self.offer_service.accept_offer( chat_room_id=room_id, offer_id=data.get("offer_id"), user_id=user_id, user_type=data.get("user_type"), ) await self.emit("res_accept_offer", offer, room=room_id) async def on_req_decline_offer(self, sid, data): user_id = await self._authenticate(token=data.get("token")) room_id = data.get("chat_room_id") offer = self.offer_service.reject_offer( chat_room_id=room_id, offer_id=data.get("offer_id"), user_id=user_id, user_type=data.get("user_type"), ) await self.emit("res_decline_offer", offer, room=room_id) async def on_req_other_party_details(self, sid, data): user_id = await self._authenticate(token=data.get("token")) room_id = data.get("chat_room_id") other_party_details = self.chat_room_service.get_other_party_details( chat_room_id=room_id, user_id=user_id) await self.emit("res_other_party_details", other_party_details, room=room_id)