コード例 #1
0
def register_survey_routes(app):

    question_blueprint = base_routes.make_blueprint(Question, 'question')
    app.register_blueprint(question_blueprint)

    answer_blueprint = base_routes.make_blueprint(Answer, 'answer')
    app.register_blueprint(answer_blueprint)
コード例 #2
0
def register_conversation_routes(app):

    conversation_blueprint = base_routes.make_blueprint(Conversation, 'conversation')
    app.register_blueprint(conversation_blueprint)

    message_blueprint = base_routes.make_blueprint(Message, 'message')
    app.register_blueprint(message_blueprint)
コード例 #3
0
def register_survey_routes(app):

    question_blueprint = base_routes.make_blueprint(Question, 'question')
    app.register_blueprint(question_blueprint)

    answer_blueprint = base_routes.make_blueprint(Answer, 'answer')
    app.register_blueprint(answer_blueprint)
コード例 #4
0
def register_conversation_routes(app):

    conversation_blueprint = base_routes.make_blueprint(
        Conversation, 'conversation')
    app.register_blueprint(conversation_blueprint)

    message_blueprint = base_routes.make_blueprint(Message, 'message')
    app.register_blueprint(message_blueprint)
コード例 #5
0
def register_search_routes(app):

    search_blueprint = base_routes.make_blueprint(Search, 'search')
    app.register_blueprint(search_blueprint)

    @app.route('/api/labels')
    def get_labels():
        labels = store.session.query(Label).filter(Label.active == True).all()
        labelnames = [label.name for label in labels]
        response_data = {'data': labelnames}
        response = jsonify(response_data)
        return response

    @app.route(base_routes.API_PAGINATION_FORMAT.format('search') + '/results',
               methods=['GET'])
    def get_search_results(id, page):
        page = int(page)
        requester = get_requesting_user()
        if requester is None:
            response = base_routes.make_not_authorized_response()
        elif not is_integer(id):
            response = base_routes.make_bad_request_response()
        else:
            search = store.session.query(Search).filter_by(id=id).first()
            if search is None:
                response = base_routes.make_not_found_response()
            else:
                if search.has_admin_rights(requester):
                    matching_searches = search_utils.find_matching_searches(
                        search, page)

                    serialized = [
                        search.serialize(
                            requester,
                            exclude=[],
                        ) for search in matching_searches
                    ]
                    response_data = {'data': serialized}
                    response = jsonify(response_data)
                else:
                    response = base_routes.make_forbidden_response()
        return response
コード例 #6
0
def register_search_routes(app):

    search_blueprint = base_routes.make_blueprint(Search, 'search')
    app.register_blueprint(search_blueprint)

    @app.route('/api/labels')
    def get_labels():
        labels = store.session.query(Label).filter(Label.active == True).all()
        labelnames = [label.name for label in labels]
        response_data = {'data': labelnames}
        response = jsonify(response_data)
        return response

    @app.route(base_routes.API_PAGINATION_FORMAT.format('search') + '/results', methods=['GET'])
    def get_search_results(id, page):
        page = int(page)
        requester = get_requesting_user()
        if requester is None:
            response = base_routes.make_not_authorized_response()
        elif not is_integer(id):
            response = base_routes.make_bad_request_response()
        else:
            search = store.session.query(Search).filter_by(id=id).first()
            if search is None:
                response = base_routes.make_not_found_response()
            else:
                if search.has_admin_rights(requester):
                    matching_searches = search_utils.find_matching_searches(search, page)

                    serialized = [
                        search.serialize(
                            requester,
                            exclude=[],
                        ) for search in matching_searches
                    ]
                    response_data = {'data': serialized}
                    response = jsonify(response_data)
                else:
                    response = base_routes.make_forbidden_response()
        return response
コード例 #7
0
def register_search_routes(app):

    search_blueprint = base_routes.make_blueprint(Search, 'search')
    app.register_blueprint(search_blueprint)

    @app.route('/api/labels')
    def get_labels():
        labels = store.session.query(Label).filter(Label.active == True).all()
        labelnames = [label.name for label in labels]
        return {'data': labelnames}

    @app.route('/api/search/<id>/<page>/results', methods=['GET'])
    def get_search_results(id, page):
        page = int(page)
        requester = get_requesting_user()
        if requester is None:
            raise Unauthorized()
        elif not is_integer(id):
            raise BadRequest()
        else:
            search = store.session.query(Search).filter_by(id=id).first()
            if search is None:
                raise NotFound()
            else:
                if search.has_admin_rights(requester):
                    matching_searches = search_utils.find_matching_searches(search, page)

                    serialized = [
                        search.serialize(
                            requester,
                            exclude=[],
                        ) for search in matching_searches
                    ]
                    response = {'data': serialized}
                else:
                    raise Forbidden()
        return response
コード例 #8
0
ファイル: user_routes.py プロジェクト: TimmyTomTom/commshare
def register_user_routes(app):

    user_blueprint = base_routes.make_blueprint(User, 'user')
    app.register_blueprint(user_blueprint)

    user_review_blueprint = base_routes.make_blueprint(UserReview, 'user_review')
    app.register_blueprint(user_review_blueprint)

    institution_blueprint = base_routes.make_blueprint(Institution, 'institution')
    app.register_blueprint(institution_blueprint)

    @app.route('/api/usersignup', methods=['POST'])
    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

    @app.route('/api/userbyemail/<string:email>', methods=['GET'])
    def userbyemail(email):
        requester = get_requesting_user()
        if requester is None:
            response = base_routes.make_not_authorized_response()
        elif requester.email != email:
            response = base_routes.make_forbidden_response()
        else:
            users = store.session.query(User).filter(
                User.email==email, User.active==True).all()
            if len(users) > 1:
                logger.error('More than one active user with the same email - {}'.format(email))
                user = users[0]
            elif len(users) == 0:
                user = None
            else:
                user = users[0]
            if user is None:
                response = base_routes.make_not_found_response()
            else:
                response = base_routes.make_single_response(requester, user)
        return response

    @app.route('/api/requestresetpassword/<string:email>', methods=['GET'])
    def request_reset_password(email):
        user = store.session.query(User).filter_by(email=email).first()
        if user is None:
            response = base_routes.make_not_found_response()
        else:
            error_message = mail_actions.request_password_reset(user)
            if error_message:
                response = base_routes.make_server_error_response(error_message)
            else:
                response = base_routes.make_OK_response()
        return response

    @app.route('/api/requestapikey/', methods=['GET'])
    def request_api_key():
        requester = get_requesting_user()
        if requester is None:
            response = base_routes.make_not_authorized_response()
        else:
            secret = requester.make_api_key()
            response_data = {
                'apiKey': secret.key
            }
            response = jsonify(response_data)
        return response

    @app.route('/api/resetpassword', methods=['POST'])
    def reset_password():
        data = request.json
        key = data.get('key', '')
        password = data.get('password', '')
        if key == '':
            response = base_routes.make_bad_request_response(
                'Did not receive a key with password reset request.')
        elif password == '':
            response = base_routes.make_bad_request_response(
                'Received password to reset to was blank.')
        else:
            user, error_messages = mail_actions.process_password_reset(key, password)
            if error_messages:
                error_message = ', '.join(error_messages)
                response = base_routes.make_bad_request_response(error_message)
            elif user is None:
                response = base_routes.make_bad_request_response()
            else:
                response = base_routes.make_single_response(user, user)
        return response

    @app.route('/api/requestconfirmemail', methods=['GET'])
    def request_confirm_email():
        requester = get_requesting_user()
        if requester is None:
            response = base_routes.make_not_authorized_response()
        else:
            error_message = mail_actions.request_signup_email_confirmation(requester)
            if error_message:
                response = base_routes.make_server_error_response(error_message)
            else:
                response = base_routes.make_OK_response()
        return response

    @app.route('/api/confirmemail', methods=['POST'])
    def confirm_email():
        data = request.json
        key = data.get('key', '')
        if key == '':
            response = base_routes.make_bad_request_response(
                'Did not receive a key with email confirmation.')
        else:
            user, error_messages = mail_actions.process_confirm_email(key)
            if error_messages:
                error_message = ', '.join(error_messages)
                response = base_routes.make_bad_request_response(error_message)
            elif user is None:
                response = base_routes.make_bad_request_response()
            else:
                secret = user.make_api_key()
                serialized = user.serialize(user)
                response_data = {
                    'data': serialized,
                    'apiKey': secret.key,
                }
                response = jsonify(response_data)
        return response
        
        

    ALLOWED_EXTENSIONS = set(['.txt', '.pdf', '.png', '.jpg', '.jpeg', '.gif'])

    def process_filename(filename, user_id):
        base, extension = os.path.splitext(filename)
        if extension in ALLOWED_EXTENSIONS:
            # Maximum filename length = 100
            # Use 50 to be safe
            base = base[:50]
            processed = 'user_{0}_{1}{2}'.format(user_id, base, extension)
        else:
            processed = None
        return processed

    @app.route('/api/user/<int:user_id>/picture', methods=['PUT', 'POST', 'PATCH'])
    def post_picture(user_id):
        requester = get_requesting_user()
        if (user_id == requester.id):
            user = requester
            f = request.files['file']
            if f:
                filename = process_filename(f.filename, user_id)
                if filename is None:
                    response = base_routes.make_bad_request_response()
                else:
                    conn = tinys3.Connection(
                        config.S3_USERNAME, config.S3_KEY, tls=True)
                    # Upload it.  Set cache expiry time to 1 hr.
                    conn.upload(filename, f, config.S3_BUCKETNAME,
                                expires=3600)
                    user.picture_filename = filename
                    store.session.add(user)
                    store.session.commit()
                    response = base_routes.make_OK_response()
            else:
                response = base_routes.make_bad_request_response()
        else:
            response = base.routes.make_forbidden_response()
        return response
コード例 #9
0
def register_share_routes(app):

    share_blueprint = base_routes.make_blueprint(Share, 'share')
    event_blueprint = base_routes.make_blueprint(Event, 'event')
    app.register_blueprint(share_blueprint)
    app.register_blueprint(event_blueprint)
コード例 #10
0
def register_user_routes(app):

    user_blueprint = base_routes.make_blueprint(User, 'user')
    app.register_blueprint(user_blueprint)

    user_review_blueprint = base_routes.make_blueprint(UserReview, 'user_review')
    app.register_blueprint(user_review_blueprint)

    institution_blueprint = base_routes.make_blueprint(Institution, 'institution')
    app.register_blueprint(institution_blueprint)

    @app.route('/api/usersignup', methods=['POST'])
    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

    @app.route('/api/requestresetpassword/<string:email>', methods=['GET'])
    def request_reset_password(email):
        user = store.session.query(User).filter_by(email=email, active=True).first()
        if user is None:
            raise NotFound()
        else:
            error_message = mail_actions.request_password_reset(user)
            if error_message:
                raise InternalServerError(error_message)

        return make_OK_response()

    @app.route('/api/requestapikey', methods=['GET'])
    @needs_auth()
    def request_api_key(requester: User) -> Response:
        return {
            'apiKey': requester.make_api_key().key,
            'user': serialize(requester, requester),
        }

    @app.route('/api/resetpassword', methods=['POST'])
    def reset_password():
        data = request.json
        key = data.get('key', '')
        password = data.get('password', '')
        if key == '':
            raise BadRequest(
                'No key found. Please include a "key" property '
                'with the password reset token in the payload.',
            )
        elif password == '' or len(password) < 8:
            raise BadRequest(
                'New password was missing, blank, or too short. Please '
                'include a "password" property in the payload, and '
                'ensure that the password is at least 8 characters long.',
            )
        else:
            user, error_messages = mail_actions.process_password_reset(key, password)
            if error_messages:
                raise BadRequest(', '.join(error_messages))
            elif user is None:
                raise BadRequest()

        return make_single_response(user, user)

    @app.route('/api/requestconfirmemail', methods=['GET'])
    def request_confirm_email():
        requester = get_requesting_user()
        if requester is None:
            raise Unauthorized()
        else:
            error_message = mail_actions.request_signup_email_confirmation(requester)
            if error_message:
                raise InternalServerError(error_message)

        return make_OK_response()

    @app.route('/api/confirmemail', methods=['POST'])
    def confirm_email():
        data = request.json
        key = data.get('key', '')
        if key == '':
            raise BadRequest(
                'Key not found. Please include a "key" property in  the payload '
                'that contains the confirmation token that was provided via email.',
            )
        else:
            user, error_messages = mail_actions.process_confirm_email(key)
            if error_messages:
                raise BadRequest(', '.join(error_messages))
            elif user is None:
                raise BadRequest()
            else:
                secret = user.make_api_key()
                serialized = user.serialize(user)
                response_data = {
                    'data': serialized,
                    'apiKey': secret.key,
                }
                response = response_data
        return response

    @app.route('/api/usersearch', methods=['GET'])
    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)}

    @app.route('/api/user/<int:user_id>/picture', methods=['PUT', 'POST', 'PATCH'])
    @needs_auth()
    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()

    @app.route('/api/activate_email', methods=['POST'])
    def activate_email():
        User.activate_email()

    @app.route('/api/dump_csv', methods=['GET'])
    @needs_admin_auth()
    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
コード例 #11
0
def register_user_routes(app):

    user_blueprint = base_routes.make_blueprint(User, 'user')
    app.register_blueprint(user_blueprint)

    user_review_blueprint = base_routes.make_blueprint(UserReview, 'user_review')
    app.register_blueprint(user_review_blueprint)

    institution_blueprint = base_routes.make_blueprint(Institution, 'institution')
    app.register_blueprint(institution_blueprint)

    @app.route('/api/usersignup', methods=['POST'])
    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

    @app.route('/api/userbyemail/<string:email>', methods=['GET'])
    def userbyemail(email):
        requester = get_requesting_user()
        if requester is None:
            response = base_routes.make_not_authorized_response()
        elif requester.email != email:
            response = base_routes.make_forbidden_response()
        else:
            users = store.session.query(User).filter(User.email == email, User.active == True).all()
            if len(users) > 1:
                logger.error('More than one active user with the same email - {}'.format(email))
                user = users[0]
            elif len(users) == 0:
                user = None
            else:
                user = users[0]
            if user is None:
                response = base_routes.make_not_found_response()
            else:
                response = base_routes.make_single_response(requester, user)
        return response

    @app.route('/api/requestresetpassword/<string:email>', methods=['GET'])
    def request_reset_password(email):
        user = store.session.query(User).filter_by(email=email, active=True).first()
        if user is None:
            response = base_routes.make_not_found_response()
        else:
            error_message = mail_actions.request_password_reset(user)
            if error_message:
                response = base_routes.make_server_error_response(error_message)
            else:
                response = base_routes.make_OK_response()
        return response

    @app.route('/api/requestapikey', methods=['GET'])
    def request_api_key():
        requester = get_requesting_user()
        if requester is None:
            response = base_routes.make_not_authorized_response()
        else:
            secret = requester.make_api_key()
            response_data = {'apiKey': secret.key}
            response = jsonify(response_data)
        return response

    @app.route('/api/resetpassword', methods=['POST'])
    def reset_password():
        data = request.json
        key = data.get('key', '')
        password = data.get('password', '')
        if key == '':
            response = base_routes.make_bad_request_response(
                'Did not receive a key with password reset request.',
            )
        elif password == '':
            response = base_routes.make_bad_request_response(
                'Received password to reset to was blank.',
            )
        else:
            user, error_messages = mail_actions.process_password_reset(key, password)
            if error_messages:
                error_message = ', '.join(error_messages)
                response = base_routes.make_bad_request_response(error_message)
            elif user is None:
                response = base_routes.make_bad_request_response()
            else:
                response = base_routes.make_single_response(user, user)
        return response

    @app.route('/api/requestconfirmemail', methods=['GET'])
    def request_confirm_email():
        requester = get_requesting_user()
        if requester is None:
            response = base_routes.make_not_authorized_response()
        else:
            error_message = mail_actions.request_signup_email_confirmation(requester)
            if error_message:
                response = base_routes.make_server_error_response(error_message)
            else:
                response = base_routes.make_OK_response()
        return response

    @app.route('/api/confirmemail', methods=['POST'])
    def confirm_email():
        data = request.json
        key = data.get('key', '')
        if key == '':
            response = base_routes.make_bad_request_response(
                'Did not receive a key with email confirmation.',
            )
        else:
            user, error_messages = mail_actions.process_confirm_email(key)
            if error_messages:
                error_message = ', '.join(error_messages)
                response = base_routes.make_bad_request_response(error_message)
            elif user is None:
                response = base_routes.make_bad_request_response()
            else:
                secret = user.make_api_key()
                serialized = user.serialize(user)
                response_data = {
                    'data': serialized,
                    'apiKey': secret.key,
                }
                response = jsonify(response_data)
        return response

    @app.route('/api/usersearch', methods=['GET'])
    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

    @app.route('/api/user/<int:user_id>/picture', methods=['PUT', 'POST', 'PATCH'])
    def post_picture(user_id):
        user = get_requesting_user()

        if user_id != user.id:
            return base_routes.make_not_authorized_response()

        image_file = request.files['file']
        if not image_file:
            return base_routes.make_bad_request_response('missing image data')

        image_data = image_file.read()
        if not is_allowable_image(image_data):
            return base_routes.make_bad_request_response('unallowed image type')

        filename = image_to_user_filename(image_data, user_id)

        store_image(image_file, filename)

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

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

        return base_routes.make_OK_response()

    @app.route('/api/activate_email', methods=['POST'])
    def activate_email():
        User.activate_email()

    @app.route('/api/dump_csv', methods=['GET'])
    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
コード例 #12
0
def register_user_routes(app):

    user_blueprint = base_routes.make_blueprint(User, 'user')
    app.register_blueprint(user_blueprint)

    user_review_blueprint = base_routes.make_blueprint(UserReview,
                                                       'user_review')
    app.register_blueprint(user_review_blueprint)

    institution_blueprint = base_routes.make_blueprint(Institution,
                                                       'institution')
    app.register_blueprint(institution_blueprint)

    @app.route('/api/usersignup', methods=['POST'])
    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

    @app.route('/api/userbyemail/<string:email>', methods=['GET'])
    def userbyemail(email):
        requester = get_requesting_user()
        if requester is None:
            response = base_routes.make_not_authorized_response()
        elif requester.email != email:
            response = base_routes.make_forbidden_response()
        else:
            users = store.session.query(User).filter(
                User.email == email, User.active == True).all()
            if len(users) > 1:
                logger.error(
                    'More than one active user with the same email - {}'.
                    format(email))
                user = users[0]
            elif len(users) == 0:
                user = None
            else:
                user = users[0]
            if user is None:
                response = base_routes.make_not_found_response()
            else:
                response = base_routes.make_single_response(requester, user)
        return response

    @app.route('/api/requestresetpassword/<string:email>', methods=['GET'])
    def request_reset_password(email):
        user = store.session.query(User).filter_by(email=email,
                                                   active=True).first()
        if user is None:
            response = base_routes.make_not_found_response()
        else:
            error_message = mail_actions.request_password_reset(user)
            if error_message:
                response = base_routes.make_server_error_response(
                    error_message)
            else:
                response = base_routes.make_OK_response()
        return response

    @app.route('/api/requestapikey', methods=['GET'])
    def request_api_key():
        requester = get_requesting_user()
        if requester is None:
            response = base_routes.make_not_authorized_response()
        else:
            secret = requester.make_api_key()
            response_data = {'apiKey': secret.key}
            response = jsonify(response_data)
        return response

    @app.route('/api/resetpassword', methods=['POST'])
    def reset_password():
        data = request.json
        key = data.get('key', '')
        password = data.get('password', '')
        if key == '':
            response = base_routes.make_bad_request_response(
                'Did not receive a key with password reset request.', )
        elif password == '':
            response = base_routes.make_bad_request_response(
                'Received password to reset to was blank.', )
        else:
            user, error_messages = mail_actions.process_password_reset(
                key, password)
            if error_messages:
                error_message = ', '.join(error_messages)
                response = base_routes.make_bad_request_response(error_message)
            elif user is None:
                response = base_routes.make_bad_request_response()
            else:
                response = base_routes.make_single_response(user, user)
        return response

    @app.route('/api/requestconfirmemail', methods=['GET'])
    def request_confirm_email():
        requester = get_requesting_user()
        if requester is None:
            response = base_routes.make_not_authorized_response()
        else:
            error_message = mail_actions.request_signup_email_confirmation(
                requester)
            if error_message:
                response = base_routes.make_server_error_response(
                    error_message)
            else:
                response = base_routes.make_OK_response()
        return response

    @app.route('/api/confirmemail', methods=['POST'])
    def confirm_email():
        data = request.json
        key = data.get('key', '')
        if key == '':
            response = base_routes.make_bad_request_response(
                'Did not receive a key with email confirmation.', )
        else:
            user, error_messages = mail_actions.process_confirm_email(key)
            if error_messages:
                error_message = ', '.join(error_messages)
                response = base_routes.make_bad_request_response(error_message)
            elif user is None:
                response = base_routes.make_bad_request_response()
            else:
                secret = user.make_api_key()
                serialized = user.serialize(user)
                response_data = {
                    'data': serialized,
                    'apiKey': secret.key,
                }
                response = jsonify(response_data)
        return response

    @app.route('/api/usersearch', methods=['GET'])
    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

    @app.route('/api/user/<int:user_id>/picture',
               methods=['PUT', 'POST', 'PATCH'])
    def post_picture(user_id):
        user = get_requesting_user()

        if user_id != user.id:
            return base_routes.make_not_authorized_response()

        image_file = request.files['file']
        if not image_file:
            return base_routes.make_bad_request_response('missing image data')

        image_data = image_file.read()
        if not is_allowable_image(image_data):
            return base_routes.make_bad_request_response(
                'unallowed image type')

        filename = image_to_user_filename(image_data, user_id)

        store_image(image_file, filename)

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

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

        return base_routes.make_OK_response()

    @app.route('/api/activate_email', methods=['POST'])
    def activate_email():
        User.activate_email()

    @app.route('/api/dump_csv', methods=['GET'])
    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