def find_by(token: str, email: str = None, offer_id: int = None) -> Booking:
    query = Booking.query.filter_by(token=token.upper())
    offer_is_educational = query.join(Stock).join(Offer).with_entities(
        Offer.isEducational).scalar()

    if email:
        # FIXME (dbaty, 2021-05-02): remove call to `func.lower()` once
        # all emails have been sanitized in the database.
        if not offer_is_educational:
            query = (query.join(IndividualBooking).join(
                IndividualBooking.user).filter(
                    func.lower(User.email) == sanitize_email(email)))
        elif offer_is_educational:
            query = (query.join(EducationalBooking).join(
                EducationalBooking.educationalRedactor).filter(
                    func.lower(EducationalBooking.educationalRedactor.email) ==
                    sanitize_email(email)))

    if offer_id:
        query = query.join(Stock).join(Offer).filter(Offer.id == offer_id)

    booking = query.one_or_none()

    if booking is None:
        errors = ResourceNotFoundError()
        errors.add_error("global", "Cette contremarque n'a pas été trouvée")
        raise errors

    return booking
Beispiel #2
0
def update_user_info(
    user,
    cultural_survey_filled_date=UNCHANGED,
    cultural_survey_id=UNCHANGED,
    email=UNCHANGED,
    first_name=UNCHANGED,
    has_seen_tutorials=UNCHANGED,
    last_name=UNCHANGED,
    needs_to_fill_cultural_survey=UNCHANGED,
    phone_number=UNCHANGED,
    public_name=UNCHANGED,
):
    if cultural_survey_filled_date is not UNCHANGED:
        user.culturalSurveyFilledDate = cultural_survey_filled_date
    if cultural_survey_id is not UNCHANGED:
        user.culturalSurveyId = cultural_survey_id
    if email is not UNCHANGED:
        user.email = sanitize_email(email)
    if first_name is not UNCHANGED:
        user.firstName = first_name
    if has_seen_tutorials is not UNCHANGED:
        user.hasSeenTutorials = has_seen_tutorials
    if last_name is not UNCHANGED:
        user.lastName = last_name
    if needs_to_fill_cultural_survey is not UNCHANGED:
        user.needsToFillCulturalSurvey = needs_to_fill_cultural_survey
    if phone_number is not UNCHANGED:
        user.phoneNumber = phone_number
    if public_name is not UNCHANGED:
        user.publicName = public_name
    repository.save(user)
Beispiel #3
0
def change_user_email(token: str) -> None:
    try:
        jwt_payload = decode_jwt_token(token)
    except (
        ExpiredSignatureError,
        InvalidSignatureError,
        DecodeError,
        InvalidTokenError,
    ) as error:
        raise InvalidTokenError() from error

    if not {"exp", "new_email", "current_email"} <= set(jwt_payload):
        raise InvalidTokenError()

    new_email = sanitize_email(jwt_payload["new_email"])
    if find_user_by_email(new_email):
        return

    current_user = find_user_by_email(jwt_payload["current_email"])
    if not current_user:
        return

    current_user.email = new_email
    sessions = UserSession.query.filter_by(userId=current_user.id)
    repository.delete(*sessions)
    repository.save(current_user)

    logger.info("User has changed their email", extra={"user": current_user.id})

    return
Beispiel #4
0
def signup_webapp():
    objects_to_save = []
    check_valid_signup_webapp(request)

    new_user = User(from_dict=request.json)
    new_user.email = sanitize_email(new_user.email)
    new_user.notificationSubscriptions = asdict(
        NotificationSubscriptions(marketing_email=bool(request.json.get("contact_ok")))
    )

    if settings.IS_INTEGRATION:
        objects_to_save.append(payments_api.create_deposit(new_user, "test"))
    else:
        authorized_emails, departement_codes = get_authorized_emails_and_dept_codes(ttl_hash=get_ttl_hash())
        departement_code = _get_departement_code_when_authorized_or_error(authorized_emails, departement_codes)
        new_user.departementCode = departement_code

    new_user.remove_admin_role()
    new_user.remove_beneficiary_role()
    new_user.isEmailValidated = True
    new_user.needsToFillCulturalSurvey = False
    new_user.hasSeenTutorials = True
    objects_to_save.append(new_user)

    repository.save(*objects_to_save)

    update_external_user(new_user)

    return jsonify(as_dict(new_user, includes=BENEFICIARY_INCLUDES)), 201
def create_beneficiary_from_application(
        application_detail: fraud_models.DMSContent,
        user: Optional[User] = None) -> User:
    if not user:
        beneficiary = User()
        beneficiary.password = random_hashed_password()
        beneficiary.email = sanitize_email(application_detail.email)
        beneficiary.dateOfBirth = application_detail.birth_date
    else:
        beneficiary = user

    beneficiary.lastName = application_detail.last_name
    beneficiary.firstName = application_detail.first_name
    beneficiary.publicName = "%s %s" % (application_detail.first_name,
                                        application_detail.last_name)
    beneficiary.departementCode = application_detail.department
    beneficiary.postalCode = application_detail.postal_code
    beneficiary.address = application_detail.address
    beneficiary.civility = application_detail.civility
    beneficiary.activity = application_detail.activity
    beneficiary.remove_admin_role()
    beneficiary.hasSeenTutorials = False
    beneficiary.idPieceNumber = application_detail.id_piece_number

    if not beneficiary.phoneNumber:
        beneficiary.phoneNumber = application_detail.phone

    return beneficiary
Beispiel #6
0
def create_or_update_users(rows: Iterable[dict]) -> list[User]:
    # The purpose of this function is to recreate test users on
    # staging after the staging database is reset. It's not meant to
    # be used anywhere else, and certainly not on production.
    if settings.IS_PROD:
        raise ValueError(
            "This function is not supposed to be run on production")

    users = []
    for row in rows:
        user = find_user_by_email(row["Mail"])
        birthdate = datetime.strptime(row["Date de naissance"], "%Y-%m-%d")
        if user:
            user.dateOfBirth = birthdate
            user.setPassword(settings.STAGING_TEST_USER_PASSWORD)
        else:
            user = users_api.create_account(
                email=sanitize_email(row["Mail"]),
                password=settings.STAGING_TEST_USER_PASSWORD,
                birthdate=birthdate,
                is_email_validated=True,
                send_activation_mail=False,
                remote_updates=False,
            )
            deposit = payments_api.create_deposit(user, "import_users (csv)")
            repository.save(deposit)

        user.add_beneficiary_role()
        user.lastName = row["Nom"]
        user.firstName = row["Prénom"]
        user.publicName = f"{user.firstName} {user.lastName}"
        user.phoneNumber = row["Téléphone"]
        user.departementCode = row["Département"]
        user.postalCode = row["Code postal"]
        repository.save(user)

        users.append(user)
        logger.info("Created or updated user=%s from CSV import", user.id)

    admin = find_user_by_email("*****@*****.**")
    if not admin:
        admin = users_api.create_account(
            email="*****@*****.**",
            password=settings.STAGING_TEST_USER_PASSWORD,
            birthdate=datetime(1946, 12, 24),
            is_email_validated=True,
            send_activation_mail=False,
            remote_updates=False,
        )
    admin.setPassword(settings.STAGING_TEST_USER_PASSWORD)
    admin.remove_beneficiary_role()
    admin.add_admin_role()
    admin.firstName = "Jeanne"
    admin.lastName = "Admin"
    admin.publicName = f"{user.firstName} {user.lastName}"
    repository.save(admin)
    logger.info("Created or updated admin user=%s", admin.id)
    return users
Beispiel #7
0
def fill_user_from(csv_row: list[str], user: User) -> User:
    user.lastName = csv_row[USER_LAST_NAME_COLUMN_INDEX]
    user.firstName = csv_row[USER_FIRST_NAME_COLUMN_INDEX].split(" ")[0]
    user.publicName = "%s %s" % (user.firstName, user.lastName)
    user.email = sanitize_email(csv_row[USER_EMAIL_COLUMN_INDEX])
    user.departementCode = csv_row[USER_DEPARTMENT_CODE_COLUMN_INDEX]
    user.remove_beneficiary_role()
    user.add_pro_role()

    fulfill_account_password(user)
    return user
def to_model(beneficiary_pre_subscription: BeneficiaryPreSubscription,
             user: Optional[User] = None) -> User:
    if user and beneficiary_pre_subscription.postal_code.strip() == "":
        dateOfBirth = beneficiary_pre_subscription.date_of_birth or user.dateOfBirth
        civility = beneficiary_pre_subscription.civility
        firstName = beneficiary_pre_subscription.first_name
        lastName = beneficiary_pre_subscription.last_name
        publicName = beneficiary_pre_subscription.public_name
        idPieceNumber = beneficiary_pre_subscription.id_piece_number
        User.query.filter(User.id == user.id).update({
            "civility": civility,
            "dateOfBirth": dateOfBirth,
            "firstName": firstName,
            "idPieceNumber": idPieceNumber,
            "lastName": lastName,
            "publicName": publicName,
        })
        return user

    if not user:
        beneficiary = User()
        beneficiary.email = sanitize_email(beneficiary_pre_subscription.email)
        fulfill_account_password(beneficiary)
    else:
        beneficiary = user

    beneficiary.dateOfBirth = beneficiary_pre_subscription.date_of_birth or beneficiary.dateOfBirth
    beneficiary.activity = beneficiary_pre_subscription.activity
    beneficiary.address = beneficiary_pre_subscription.address
    beneficiary.city = beneficiary_pre_subscription.city
    beneficiary.civility = beneficiary_pre_subscription.civility
    beneficiary.departementCode = beneficiary_pre_subscription.department_code
    beneficiary.firstName = beneficiary_pre_subscription.first_name
    beneficiary.hasSeenTutorials = False
    beneficiary.remove_admin_role()
    beneficiary.lastName = beneficiary_pre_subscription.last_name
    beneficiary.postalCode = beneficiary_pre_subscription.postal_code
    beneficiary.publicName = beneficiary_pre_subscription.public_name
    if FeatureToggle.ENABLE_IDCHECK_FRAUD_CONTROLS.is_active():
        beneficiary.idPieceNumber = beneficiary_pre_subscription.id_piece_number
    beneficiary.hasCompletedIdCheck = True

    if not beneficiary.phoneNumber:
        beneficiary.phoneNumber = beneficiary_pre_subscription.phone_number

    return beneficiary
Beispiel #9
0
def create_pro_user(pro_user: ProUserCreationBodyModel) -> User:
    new_pro_user = User(from_dict=pro_user.dict(by_alias=True))
    new_pro_user.email = sanitize_email(new_pro_user.email)
    new_pro_user.notificationSubscriptions = asdict(NotificationSubscriptions(marketing_email=pro_user.contact_ok))
    new_pro_user.remove_admin_role()
    new_pro_user.remove_beneficiary_role()
    new_pro_user.needsToFillCulturalSurvey = False
    new_pro_user.generate_validation_token()

    if pro_user.postal_code:
        new_pro_user.departementCode = PostalCode(pro_user.postal_code).get_departement_code()

    if settings.IS_INTEGRATION:
        new_pro_user.add_beneficiary_role()
        deposit = payment_api.create_deposit(new_pro_user, "integration_signup")
        new_pro_user.deposits = [deposit]

    return new_pro_user
Beispiel #10
0
def create_account(
    email: str,
    password: str,
    birthdate: date,
    marketing_email_subscription: bool = False,
    is_email_validated: bool = False,
    send_activation_mail: bool = True,
    remote_updates: bool = True,
    postal_code: str = None,
    phone_number: str = None,
    apps_flyer_user_id: str = None,
    apps_flyer_platform: str = None,
) -> User:
    email = sanitize_email(email)
    if find_user_by_email(email):
        raise exceptions.UserAlreadyExistsException()

    departement_code = PostalCode(postal_code).get_departement_code() if postal_code else None

    user = User(
        email=email,
        dateOfBirth=datetime.combine(birthdate, datetime.min.time()),
        isEmailValidated=is_email_validated,
        publicName=VOID_PUBLIC_NAME,  # Required because model validation requires 3+ chars
        hasSeenTutorials=False,
        notificationSubscriptions=asdict(NotificationSubscriptions(marketing_email=marketing_email_subscription)),
        postalCode=postal_code,
        departementCode=departement_code,
        phoneNumber=phone_number,
        lastConnectionDate=datetime.now(),
    )

    if not user.age or user.age < constants.ACCOUNT_CREATION_MINIMUM_AGE:
        raise exceptions.UnderAgeUserException()

    return initialize_account(
        user, password, apps_flyer_user_id, apps_flyer_platform, send_activation_mail, remote_updates
    )
Beispiel #11
0
def filter_email(value: Optional[str]) -> Optional[str]:
    if not value:
        return value
    return sanitize_email(value)
def find_user_by_email(email: str) -> User:
    # FIXME (dbaty, 2021-05-02): remove call to `func.lower()` once
    # all emails have been sanitized in the database.
    return User.query.filter(
        func.lower(User.email) == sanitize_email(email)).one_or_none()
def count_users_by_email(email: str) -> int:
    # FIXME (dbaty, 2021-05-02): remove call to `func.lower()` once
    # all emails have been sanitized in the database.
    return User.query.filter(
        func.lower(User.email) == sanitize_email(email)).count()