Esempio n. 1
0
def make_random_user():
    # Make the user
    first_name, last_name = gen_new_name(user_names_used, first_names, last_names)

    if first_name is None:
        return

    user_names_used.add((first_name, last_name))

    password = Secret.make_key(20)
    password_hash = User.pwd_context.encrypt(password)

    if random.randint(0, 1):
        searcher_role = 'educator'
        searching_for_role = 'partner'
        bio = generate_educator_bio()
        associations = [gen_random_institution(schools, educator_roles)]
    else:
        searcher_role = 'partner'
        searching_for_role = 'educator'
        bio = generate_expert_bio()
        associations = [
            gen_random_institution(companies, partner_roles) for _ in range(random.randint(1, 2))
        ]

    new_user = User(
        name='{0} {1}'.format(first_name, last_name),
        email=gen_email(first_name, last_name),
        password_hash=password_hash,
        picture_filename=random.choice(profile_picture_filenames),
        bio=bio,
        institution_associations=associations,
        is_administrator=False,
        email_confirmed=True
    )

    store.session.add(new_user)
    store.session.commit()

    # Make the search
    latitude, longitude = make_random_location()
    search = Search(
        searcher_user_id=new_user.id,
        searcher_role=searcher_role,
        searching_for_role=searching_for_role,
        latitude=latitude,
        longitude=longitude,
    )
    search.labels = Label.name_list_to_object_list(gen_labels())

    store.session.add(search)
    store.session.commit()

    if search.searcher_role == 'educator':
        new_user.educator_profile_search = search
    else:
        new_user.community_partner_profile_search = search

    store.session.add(new_user)
    store.session.commit()
Esempio n. 2
0
def make_random_user():
    # Make the user
    finished = False
    while not finished:
        first_name = random_item_from_list(first_names)
        last_name = random_item_from_list(last_names)
        combined = (first_name, last_name)
        if combined not in user_names_used:
            finished = True
            user_names_used.add(combined)
    password = Secret.make_key(20)
    email = make_email(first_name, last_name)
    password_hash = User.pwd_context.encrypt(password)
    name = '{0} {1}'.format(first_name, last_name)
    picture_filename = random_item_from_list(profile_picture_filenames)
    randombinary = random.randint(0, 1)
    if randombinary:
        searcher_role = 'educator'
        searching_for_role = 'partner'
        bio = generate_educator_bio()
        institution_associations = [
            InstitutionAssociation(
                institution=random_item_from_list(schools),
                role=random_item_from_list(educator_roles)
            )]
    else:
        searcher_role = 'partner'
        searching_for_role = 'educator'
        bio = generate_expert_bio()
        n_institutions = random.randint(1, 2)
        institution_associations = [
            InstitutionAssociation(
                institution=random_item_from_list(companies),
                role=random_item_from_list(partner_roles))
            for x in range(n_institutions)]
    new_user = User(name=name, email=email, password_hash=password_hash,
                    picture_filename=picture_filename, bio=bio,
                    institution_associations=institution_associations,
                    is_administrator=False, email_confirmed=True)
    store.session.add(new_user)
    store.session.commit()
    # Make the search
    location = make_random_location()
    search = Search(
        searcher_user_id=new_user.id,
        searcher_role=searcher_role,
        searching_for_role=searching_for_role,
        latitude=location[0],
        longitude=location[1],
    )
    search.labels = Label.name_list_to_object_list(get_labels())
    store.session.add(search)
    store.session.commit()
    if search.searcher_role == 'educator':
        new_user.educator_profile_search = search
    else:
        new_user.community_partner_profile_search = search
    store.session.add(new_user)
    store.session.commit()
Esempio n. 3
0
def make_random_user(password_hash):
    # Make the user
    first_name, last_name = gen_new_name(user_names_used, first_names, last_names)

    if first_name is None:
        return

    user_names_used.add((first_name, last_name))

    if random.randint(0, 1):
        searcher_role = 'educator'
        searching_for_role = 'partner'
        bio = generate_educator_bio()
        associations = [gen_random_institution(schools, educator_roles)]
    else:
        searcher_role = 'partner'
        searching_for_role = 'educator'
        bio = generate_expert_bio()
        associations = [
            gen_random_institution(companies, partner_roles) for _ in range(random.randint(1, 2))
        ]

    new_user = User(
        name='{0} {1}'.format(first_name, last_name),
        email=gen_email(first_name, last_name),
        password_hash=password_hash,
        picture_filename=random.choice(profile_picture_filenames),
        bio=bio,
        institution_associations=associations,
        is_administrator=False,
        email_confirmed=True
    )

    store.session.add(new_user)
    store.session.commit()

    # Make the search
    latitude, longitude = make_random_location()
    search = Search(
        searcher_user_id=new_user.id,
        searcher_role=searcher_role,
        searching_for_role=searching_for_role,
        latitude=latitude,
        longitude=longitude,
    )
    search.labels = Label.name_list_to_object_list(gen_labels())

    store.session.add(search)
    store.session.commit()

    if search.searcher_role == 'educator':
        new_user.educator_profile_search = search
    else:
        new_user.community_partner_profile_search = search

    store.session.add(new_user)
    store.session.commit()
 def search():
     requester = get_requesting_user()
     search_text = request.args.get('search_text', None)
     date_created_greaterthan = request.args.get('date_created.greaterthan', None)
     date_created_lessthan = request.args.get('date_created.lessthan', None)
     users = User.search(search_text, date_created_greaterthan, date_created_lessthan)
     return {'data': serialize_many(requester, users)}
Esempio n. 5
0
 def dump_csv():
     csv_obj = User.dump_csv()
     response = make_response(csv_obj.getvalue())
     response.headers["Content-Type"] = "text/csv"
     response.headers[
         "Content-Disposition"] = "attachment; filename=communityshare.csv"
     return response
Esempio n. 6
0
 def usersignup():
     data = request.json
     user = data.get('user', None)
     email = user.get('email', '')
     password = data.get('password', None)
     # Check that the email isn't in use.
     existing_user = store.session.query(User).filter(
         User.email==email, User.active==True).first()
     if existing_user is not None:
         response = base_routes.make_bad_request_response(
             'That email address is already associated with an account.')
     elif password is None:
         response = base_routes.make_bad_request_response(
             'A password was not specified.');
     else:
         user = User.admin_deserialize_add(user)
         error_messages = user.set_password(password)
         if error_messages:
             error_message = ', '.join(error_messages)
             response = base_routes.make_bad_request_response(error_message)
         else:
             store.session.add(user)
             store.session.commit()
             error_message = mail_actions.request_signup_email_confirmation(user)
             secret = user.make_api_key()
             serialized = user.serialize(user)
             response_data = {
                 'data': serialized,
                 'apiKey': secret.key,
                 'warningMessage': 'Failed to send email confirmation: {0}'.format(error_message)
             }
             response = jsonify(response_data)
     return response
 def usersignup():
     data = request.json
     user = data.get('user', None)
     email = user.get('email', '')
     password = data.get('password', None)
     # Check that the email isn't in use.
     existing_user = store.session.query(User)
     existing_user = existing_user.filter(User.email == email, User.active == True)
     existing_user = existing_user.first()
     if existing_user is not None:
         raise BadRequest('That email address is already associated with an account.')
     elif password is None:
         raise BadRequest('No password was found. Please include a "password" property in the payload.')
     else:
         try:
             user = User.admin_deserialize_add(user)
             error_messages = user.set_password(password)
             if error_messages:
                 raise BadRequest(', '.join(error_messages))
             else:
                 store.session.add(user)
                 store.session.commit()
                 error_message = mail_actions.request_signup_email_confirmation(user)
                 secret = user.make_api_key()
                 serialized = user.serialize(user)
                 warning_message = 'Failed to send email confirmation: {0}'.format(error_message)
                 response_data = {
                     'data': serialized,
                     'apiKey': secret.key,
                     'warningMessage': warning_message,
                 }
             response = response_data
         except ValidationException as e:
             raise BadRequest(str(e))
     return response
 def search():
     requester = get_requesting_user()
     search_text = request.args.get('search_text', None)
     date_created_greaterthan = request.args.get('date_created.greaterthan', None)
     date_created_lessthan = request.args.get('date_created.lessthan', None)
     users = User.search(search_text, date_created_greaterthan, date_created_lessthan)
     response = base_routes.make_many_response(requester, users)
     return response
Esempio n. 9
0
 def search():
     requester = get_requesting_user()
     search_text = request.args.get('search_text', None)
     date_created_greaterthan = request.args.get('date_created.greaterthan',
                                                 None)
     date_created_lessthan = request.args.get('date_created.lessthan', None)
     users = User.search(search_text, date_created_greaterthan,
                         date_created_lessthan)
     response = base_routes.make_many_response(requester, users)
     return response
Esempio n. 10
0
def make_admin_user(name, email, password):
    password_hash = User.pwd_context.encrypt(password)
    new_user = User(
        name=name,
        email=email,
        password_hash=password_hash,
        is_administrator=True,
        email_confirmed=True,
    )
    store.session.add(new_user)
    try:
        store.session.commit()
    except (IntegrityError, InvalidRequestError):
        store.session.rollback()
        new_user = None
    return new_user
Esempio n. 11
0
 def usersignup():
     data = request.json
     user = data.get('user', None)
     email = user.get('email', '')
     password = data.get('password', None)
     # Check that the email isn't in use.
     existing_user = store.session.query(User)
     existing_user = existing_user.filter(User.email == email,
                                          User.active == True)
     existing_user = existing_user.first()
     if existing_user is not None:
         response = base_routes.make_bad_request_response(
             'That email address is already associated with an account.', )
     elif password is None:
         response = base_routes.make_bad_request_response(
             'A password was not specified.')
     else:
         try:
             user = User.admin_deserialize_add(user)
             error_messages = user.set_password(password)
             if error_messages:
                 error_message = ', '.join(error_messages)
                 response = base_routes.make_bad_request_response(
                     error_message)
             else:
                 store.session.add(user)
                 store.session.commit()
                 error_message = mail_actions.request_signup_email_confirmation(
                     user)
                 secret = user.make_api_key()
                 serialized = user.serialize(user)
                 warning_message = 'Failed to send email confirmation: {0}'.format(
                     error_message)
                 response_data = {
                     'data': serialized,
                     'apiKey': secret.key,
                     'warningMessage': warning_message,
                 }
             response = jsonify(response_data)
         except ValidationException as e:
             response = base_routes.make_bad_request_response(str(e))
     return response
Esempio n. 12
0
def get_requesting_user():
    authorization = request.headers.get('Authorization', None)
    authorized_user = None
    if authorization is not None:
        bits = authorization.split(':')
        if len(bits) == 3 and bits[0] == 'Basic':
            email = bits[1]
            password = bits[2]
            logger.debug('Authorizing with email={0}'.format(email))
            if email == 'api':
                authorized_user = User.from_api_key(password)
            else:
                user = store.session.query(User).filter_by(email=email, active=True).first()
                if user is not None:
                    if user.is_password_correct(password):
                        authorized_user = user
    if authorized_user is not None:
        if not authorized_user.active:
            authorized_user = None
    return authorized_user
Esempio n. 13
0
    def post_picture(user_id: int, requester: User) -> Response:
        if user_id != requester.id and not requester.is_administrator:
            raise Unauthorized()

        image_file = request.files['file']
        if not image_file:
            raise FileTypeNotImplemented(
                'Missing image data. Request needs to provide binary\n'
                'image data as the request parameter named "file".'
            )

        image_data = image_file.read()
        if not is_allowable_image(image_data):
            image_type = get_image_type(image_data)

            if image_type is None:
                reason = 'Could not infer type of image.'
            else:
                reason = 'Inferred image type {} is not allowed.'
                reason = reason.format(image_type)

            raise FileTypeNotPermitted(
                '{reason}\n\n'
                'Allowable types are {types}.'
                .format(
                    reason=reason,
                    types=', '.join(picture_types),
                )
            )

        filename = image_to_user_filename(image_data, user_id)

        store_image(image_file, filename)

        requester.picture_filename = filename
        store.session.add(requester)
        store.session.commit()

        logger.info('Saving image {!r}'.format(filename))

        return make_OK_response()
Esempio n. 14
0
def get_requesting_user():
    authorization = request.headers.get('Authorization', None)
    authorized_user = None
    if authorization is not None:
        bits = authorization.split(':')
        if len(bits) == 3 and bits[0] == 'Basic':
            email = bits[1]
            password = bits[2]
            logger.debug('Authorizing with email={0}'.format(email))
            if email == 'api':
                authorized_user = User.from_api_key(password)
            else:
                user = store.session.query(User).filter_by(
                    email=email, active=True).first()
                if user is not None:
                    if user.is_password_correct(password):
                        authorized_user = user
    if authorized_user is not None:
        if not authorized_user.active:
            authorized_user = None
    return authorized_user
Esempio n. 15
0
def get_users(
        requesting_user,
        search_text=None,
        created_after=None,
        created_before=None,
        number=10,
        offset=0,
):
    users = User.search(
        search_text,
        created_after,
        created_before,
        number=number,
        offset=offset,
    )
    count = users.count()

    users = [user.serialize(requesting_user) for user in users]
    users = [user for user in users if user is not None]

    return users, count
Esempio n. 16
0
def process_password_reset(secret_key, new_password):
    user = None
    error_messages = User.is_password_valid(new_password)
    if not error_messages:
        secret = Secret.lookup_secret(secret_key)
        error_message = ''
        if secret is not None:
            secret_info = secret.get_info()
            userId = secret_info.get('userId', None)
            action = secret_info.get('action', None)
            if action == 'password_reset' and userId is not None:
                user = store.session.query(User).filter_by(id=userId).first()
                if user is not None:
                    error_messages += user.set_password(new_password)
                    if not error_messages:
                        secret.used = True
                        store.session.add(user)
                        store.session.add(secret)
                        store.session.commit()
        else:
            error_messages.append('Authorization for this action is invalid or expired.')
    return (user, error_messages)
Esempio n. 17
0
def process_password_reset(secret_key, new_password):
    user = None
    error_messages = User.is_password_valid(new_password)
    if not error_messages:
        secret = Secret.lookup_secret(secret_key)
        error_message = ''
        if secret is not None:
            secret_info = secret.get_info()
            userId = secret_info.get('userId', None)
            action = secret_info.get('action', None)
            if action == 'password_reset' and userId is not None:
                user = store.session.query(User).filter_by(id=userId).first()
                if user is not None:
                    error_messages += user.set_password(new_password)
                    if not error_messages:
                        secret.used = True
                        store.session.add(user)
                        store.session.add(secret)
                        store.session.commit()
        else:
            error_messages.append(
                'Authorization for this action is invalid or expired.')
    return (user, error_messages)
Esempio n. 18
0
 def test_is_administrator_not_writeable_on_add(self):
     potential_admin_user = dict(user)
     potential_admin_user['is_administrator'] = True
     created_user = User.admin_deserialize_add(potential_admin_user)
     self.assertFalse(created_user.is_administrator)
Esempio n. 19
0
 def activate_email():
     User.activate_email()
Esempio n. 20
0
 def request_api_key(requester: User) -> Response:
     return {
         'apiKey': requester.make_api_key().key,
         'user': serialize(requester, requester),
     }
Esempio n. 21
0
 def activate_email():
     User.activate_email()
Esempio n. 22
0
 def dump_csv(requester: User) -> Response:
     csv_obj = User.dump_csv()
     response = make_response(csv_obj.getvalue())
     response.headers["Content-Type"] = "text/csv"
     response.headers["Content-Disposition"] = "attachment; filename=communityshare.csv"
     return response