def init_database(): db.create_all() country1 = Country(name="TestCountry") db.session.add(country1) db.session.commit() interest1 = Interest( activity="testInterest1", interest_class="General", interest_type="Outdoors" ) db.session.add(interest1) interest2 = Interest( activity="testInterest2", interest_class="Collection", interest_type="Indoors" ) db.session.add(interest2) db.session.commit() user = User( username="******", birthdate="1990-03-13", gender="Male", about_me="Test Test text", email="*****@*****.**", country_id="1", ) user.set_password("testPassword") db.session.add(user) db.session.commit() yield db db.drop_all()
def init_database(): db.create_all() country1 = Country(name="TestCountry") db.session.add(country1) db.session.commit() language1 = Language(name="testLanguage1") db.session.add(language1) language2 = Language(name="testLanguage2") db.session.add(language2) db.session.commit() user = User( username="******", birthdate="1990-03-13", gender="Male", about_me="Test Test text", email="*****@*****.**", country_id="1", ) user.set_password("testPassword") db.session.add(user) db.session.commit() yield db db.drop_all()
def add(cls, user: User, new_script): """ Adds a new script to the given user. :param user: User object :param new_script: The new script to be added to the user :return: A brand new script """ script = cls(**new_script) user.scripts.append(script) user.update_mongo() return new_script
def add(cls, user: User, new_campaign): """ Adds a new campaign to the given user. :param user: User object :param new_campaign: The new campaign to be added to the user :return: A brand new campaign """ campaign = cls(**new_campaign) user.campaigns.append(campaign) user.update_mongo() return new_campaign
def delete(user: User, _id): """ Removes from the user's array of scripts the script with the given id. :param user: User object :param _id: The ID of the script to be deleted :return: The remaining scripts of the user """ for script in user.scripts: if script.json()["_id"] == _id: user.scripts.remove(script) user.update_mongo() return user.scripts raise ScriptNotFoundException("El Script con el ID dado no existe")
def init_database(): db.create_all() country1 = Country(name="TestCountry1") db.session.add(country1) country2 = Country(name="TestCountry2") db.session.add(country2) db.session.commit() user1 = User( username="******", email="*****@*****.**", birthdate="1901-01-01", country_id="1", ) user1.set_password("testPassword") db.session.add(user1) user2 = User( username="******", email="*****@*****.**", birthdate="1912-12-12", country_id="2", ) user2.set_password("authTester2Password") db.session.add(user2) db.session.commit() yield db db.drop_all()
def delete(user: User, _id): """ Removes from the user's array of campaigns the campaign with the given id. :param user: User object :param _id: The ID of the campaign to be deleted :return: The remaining campaigns of the user """ for campaign in user.campaigns: if campaign.json()["_id"] == _id: user.campaigns.remove(campaign) user.update_mongo() return user.campaigns raise CampaignNotFoundException("La campaña con el ID dado no existe")
def delete(user: User, _id): """ Removes from the user's array of cards the card with the given id. :param user: User object :param _id: The ID of the card to be deleted :return: The remaining cards of the user """ for card in user.cards: if card.json()["_id"] == _id: user.cards.remove(card) user.update_mongo() return user.cards raise CardNotFoundException("La tarjeta con el ID dado no existe")
def update(user: User, _id, data): """ Updates the information (name and/or body message) from the script with the given id. :param user: User object :param _id: The ID of the script to be updated :param data: Dictionary containing the information of the name and body message to be updated :return: All the scripts of the current user, with updated data """ for script in user.scripts: if script.json()["_id"] == _id: user.scripts[user.scripts.index(script)].name = data["name"] user.scripts[user.scripts.index(script)].body = data["body"] user.update_mongo() return user.scripts raise ScriptNotFoundException("El Script con el ID dado no existe")
def put(self): """ Changes the type of the user from Prepago to Pospago and viceversa :return: Confirmation message """ try: user_id = get_jwt_identity() user = UserModel.get_by_id(user_id) updated_user = UserModel.change_user_type(user) return Response( success=True, message="Tipo de pago exitosamente actualizado".format( updated_user.user_type)).json(), 200 except UserException as e: return Response(message=e.message).json(), 400
def put(self): """ Changes the status of the user's account (Active / Not Active) :return: Confirmation message """ try: user_id = get_jwt_identity() user = UserModel.get_by_id(user_id) updated_user = UserModel.change_user_status(user) return Response( success=True, message="Status del usuario exitosamente actualizado".format( updated_user.status)).json(), 200 except UserException as e: return Response(message=e.message).json(), 400
def post(self): """ Registers a new user manually given its body parameters :return: JSON object with the tokens """ parser = reqparse.RequestParser() parser.add_argument('email', type=str, required=True, help="This field cannot be blank.") parser.add_argument('password', type=str, required=True, help="This field cannot be blank.") parser.add_argument('name', type=str, required=True, help="This field cannot be blank.") parser.add_argument('user_type', type=str, required=True, help="This field cannot be blank.") parser.add_argument('sms_cost', type=str, required=True, help="This field cannot be blank.") data = parser.parse_args() try: new_user = UserModel.register(data) return Response(success=True, message="Registro de usuario {} exitoso".format( new_user.email)).json(), 200 except UserException as e: return Response(message=e.message).json(), 400
def get(self): """ Retrieves the information of all the Cards of the current user. :return: JSON object with all the Cards """ user_id = get_jwt_identity() user = UserModel.get_by_id(user_id) return [card.json() for card in CardModel.get_user_cards(user)], 200
def get(self): """ Retrieves the information of all the payments of the current user. :return: JSON object with all the payments """ user_id = get_jwt_identity() user = UserModel.get_by_id(user_id) return [campaign.json() for campaign in PaymentModel.get_user_payments(user)], 200
def get(self, param): """ Gets the information of a specific user, given its email or its ID :return: User object """ if Utils.email_is_valid(param): try: user = UserModel.get_by_email(param) return user.json(), 200 except UserException as e: return Response(message=e.message).json(), 400 else: try: user = UserModel.get_by_id(param) return user.json(), 200 except UserException as e: return Response(message=e.message).json(), 400
def put(self): """ Recovers the password of the user by creating a new password :return: Confirmation message """ try: user_id = get_jwt_identity() user = UserModel.get_by_id(user_id) # Falta implementar para recibir los datos correctos updated_user = UserModel.recover_password(user, user.email, user.password) return Response( success=True, message="Status del usuario exitosamente actualizado".format( updated_user.status)).json(), 200 except UserException as e: return Response(message=e.message).json(), 400
def update(user: User, _id, data): """ Updates the information (name and/or numbers) from the campaign with the given id. :param user: User object :param _id: The ID of the campaign to be updated :param data: Dictionary containing the information of the name and numbers to be updated :return: All the campaigns of the current user, with updated data """ for campaign in user.campaigns: if campaign.json()["_id"] == _id: user.campaigns[user.campaigns.index( campaign)].numbers = data["numbers"] user.campaigns[user.campaigns.index( campaign)].name = data["name"] user.update_mongo() return user.campaigns raise CampaignNotFoundException("La campaña con el ID dado no existe")
def put(self): """ Updates the balance to the user given a new balance :return: Confirmation message """ try: data = ChangeUserBalance.parser.parse_args() balance_to_change = data['balance'] user_id = get_jwt_identity() user = UserModel.get_by_id(user_id) updated_user = UserModel.change_user_balance( user, balance_to_change) return Response( success=True, message="Balance del usuario exitosamente actualizado".format( updated_user.balance)).json(), 200 except UserException as e: return Response(message=e.message).json(), 400
def add(cls, user: User, new_card): """ Adds a new card to the given user, and uses Etomin API to tokenise it. :param user: User object :param new_card: The new card to be added to the user :return: A brand new card """ card_info = { "card": { "cardholder": new_card.get("name"), "number": new_card.get("number"), "cvv": new_card.get("cvv"), "expirationDate": new_card.get("month") + "/" + new_card.get("year") } } auth = requests.get(URL) if auth.status_code == 200: token = requests.post(URL_TOKEN, params={}, data=json.dumps(card_info), headers=HEADERS) obj_token = json.loads(token.text) if cls.is_card_repeated(user, obj_token["token"]): raise RepeatedCardException( "Esta tarjeta ya ha sido añadida previamente.") new_card["number"] = obj_token["card"] new_card["token"] = obj_token["token"] new_card.pop("cvv") card = cls(**new_card) user.cards.append(card) user.update_mongo() return new_card raise TokenizationFailedException( "No fue posible tokenizar la tarjeta. Contacte al administrador.")
def send_messages(self): user_id = get_jwt_identity() user = User.get_by_id(user_id) messages_to_send = self.prepare_messages() total_cost = len(messages_to_send)* user.sms_cost if total_cost < user.balance and user.user_type == "pre": raise NotEnoughBalanceToSendPackageError(f"El usuario cuenta con {user.balance} y se necesita {total_cost}") [message.send() for message in messages_to_send] user.balance -= (messages_to_send * user.sms_cost) user.update_mongo() return messages_to_send
def get(self): """ Retrieves the information of all the scripts of the current user. :return: JSON object with all the scripts """ user_id = get_jwt_identity() user = UserModel.get_by_id(user_id) return [ script.json() for script in ScriptModel.get_user_scripts(user) ], 200
def get(self): """ Retrieves the information of all the messages of a certain package. :return: JSON object with all the messages """ user_id = get_jwt_identity() user = UserModel.get_by_id(user_id) return [ message.json() for message in MessageModel.get_package_messages(user) ], 200
def update(user: User, _id, data): """ Updates the information (number, name, type, and/or token) from the card with the given id. :param user: User object :param _id: The ID of the card to be updated :param data: Dictionary containing the information of the number, name, type, and token to be updated :return: All the cards of the current user, with updated data """ for card in user.cards: if card.json()["_id"] == _id: user.cards[user.cards.index(card)].number = data["number"] user.cards[user.cards.index(card)].name = data["name"] user.cards[user.cards.index(card)].type = data["type"] user.cards[user.cards.index(card)].token = data["token"] user.cards[user.cards.index(card)].month = data["month"] user.cards[user.cards.index(card)].year = data["year"] user.update_mongo() return user.cards raise CardNotFoundException("La tarjeta con el ID dado no existe")
def add(cls, user: User, new_payment): """ Adds a new payment to the given user. :param user: User object :param new_payment: The new payment to be added to the user :return: A brand new payment """ new_payment["status"] = "PENDIENTE" etomin_number = "" for card in user.cards: if card.json()["_id"] == new_payment["id_card"]: etomin_number = user.cards[user.cards.index(card)].token payment = cls(**new_payment) params = { "public_key": os.environ.get("ETOMIN_PB_KEY"), "transaction": { "payer": { "email": user.email }, "order": { "external_reference": payment._id }, "payment": { "amount": new_payment.get("amount"), "payment_method": new_payment.get("payment_method"), "currency": CURRENCY, "payment_country": PAYMENT_COUNTRY, "token": etomin_number }, "payment_pending": False, "device_session_id": "" }, "test": True } auth = requests.get(URL) if auth.status_code == 200: obj = json.loads(auth.text) params["transaction"]["device_session_id"] = obj["session_id"] charge = requests.post(URL_CHARGE, params={}, data=json.dumps(params), headers=HEADERS) obj_charge = json.loads(charge.text) if obj_charge.get("error") == '0': payment.status = "APROBADO" payment.id_reference = obj_charge.get("authorization_code") payment.etomin_number = obj_charge.get("card_token") new_payment["status"] = "APROBADO" user.change_user_balance(-new_payment.get("amount")) user.payments.append(payment) user.update_mongo() return new_payment else: payment.status = "RECHAZADO" payment.etomin_number = etomin_number user.payments.append(payment) user.update_mongo() raise PaymentFailedException(obj_charge.get("message"))
def add_users(count): click.echo(f"Seeding user table with {count} new users.") count_users = 0 while count_users < int(count): try: user = User( username=fake.name(), email=fake.email(), birthdate=fake.date(), gender="Female", about_me=fake.text(max_nb_chars=500), country_id=Country.query.order_by(func.random()).first().id, ) user.set_password(fake.text(max_nb_chars=20)) languages = Language.query.order_by(func.random()).limit( randrange(1, 4)) interests = Interest.query.order_by(func.random()).limit( randrange(4, 10)) # Remove duplicates user.languages = list(dict.fromkeys(languages)) user.interests = list(dict.fromkeys(interests)) db.session.add(user) count_users += 1 except AssertionError: pass # Skips that user e.g. faker randomized user with same name db.session.commit() click.echo("Done.")
def post(self): """ Inserts a new script to the current user. :return: JSON object with the newly created script """ try: data = PARSER.parse_args() user_id = get_jwt_identity() user = UserModel.get_by_id(user_id) return ScriptModel.add(user, data), 200 except UserException as e: return Response(message=e.message).json(), 401
def create_user(): body = request.get_json() user = User() user.from_dict(body) user.set_password(body["password"]) db.session.add(user) db.session.commit() return user
def init_database(): db.create_all() country1 = Country(name="Chad") db.session.add(country1) country2 = Country(name="Sweden") db.session.add(country2) db.session.commit() user1 = User( username="******", email="*****@*****.**", country_id="1" ) user1.set_password("testPassword") db.session.add(user1) user2 = User( username="******", email="*****@*****.**", country_id="2" ) user2.set_password("testPass2") db.session.add(user2) db.session.commit() penpal1 = PenPal(created_date=time.time()) db.session.add(penpal1) db.session.commit() letter1 = Letter( text="Hi I'm letterTester", sent_date=time.time(), penpal_id=penpal1.id, penpal=penpal1, user_id=user1.id, user=user1, ) db.session.add(letter1) letter2 = Letter( text="Hi I'm letterTester2", sent_date=time.time(), penpal_id=penpal1.id, penpal=penpal1, user_id=user2.id, user=user2, ) db.session.add(letter2) db.session.commit() yield db db.drop_all()
def delete(self, card_id): """ Deletes the card with the given id in the parameters. :param card_id: The id of the card to be deleted from the user :return: JSON object with the remaining cards """ try: user_id = get_jwt_identity() user = UserModel.get_by_id(user_id) return [card.json() for card in CardModel.delete(user, card_id)], 200 except CardNotFoundException as e: return Response(message=e.message).json(), 400
def get(self, card_id): """ Retrieves the information of the card with the given id in the parameters. :param card_id: The id of the card to be read from the user :return: JSON object with the requested card information """ try: user_id = get_jwt_identity() user = UserModel.get_by_id(user_id) return CardModel.get(user, card_id).json(), 200 except CardNotFoundException as e: return Response(message=e.message).json(), 400 except UserException as e: return Response(message=e.message).json(), 401