Пример #1
0
def log_in_route(request):
  """
  Log in user.
  """

  db_conn = request['db_conn']
  name = request['params'].get('name') or ''
  name = name.lower().strip()
  user = get_user(db_conn, {'name': name})
  if not user:
    user = get_user(db_conn, {'email': name})
  if not user:
    return 404, {
      'errors': [{
        'name': 'name',
        'message': c('no_user'),
        'ref': 'dfhMHDFbT42CmRRmN14gdA',
      }],
    }
  real_encrypted_password = user['password']
  given_password = request['params'].get('password')
  if not is_password_valid(real_encrypted_password, given_password):
    return 400, {
      'errors': [{
        'name': 'password',
        'message': c('no_match'),
        'ref': 'DTarUzzsSLKarq-uIsXkFQ',
      }],
    }
  return _log_in(user)
Пример #2
0
def log_in_route(request):
    """
    Log in user.
    """

    db_conn = request['db_conn']
    name = request['params'].get('name') or ''
    name = name.lower().strip()

    user = get_user({'name': name}, db_conn)
    if not user:
        user = get_user({'email': request['params'].get('name')}, db_conn)
    if not user:
        return 404, {
            'errors': [{
                'name': 'name',
                'message': c('no_user'),
            }],
            'ref': 'FYIPOI8g2nzrIEcJYSDAfmti'
        }
    real_encrypted_password = user['password']
    given_password = request['params'].get('password')
    if not is_password_valid(real_encrypted_password, given_password):
        return 400, {
            'errors': [{
                'name': 'password',
                'message': c('no_match'),
            }],
            'ref': 'UwCRydZ7Agi7LYKv9c1y07ft'
        }
    return _log_in(user)
Пример #3
0
def process_article():
    # generate a random file name and a current datetime

    lookup_id = str(uuid.uuid4())
    current_dt = datetime.datetime.now()
    filename = lookup_id + str(current_dt) + ".txt"
    content = request.form['page']
    user_id = request.form['user_id']

    # push page text through nlp pipeline
    processor = nlp.NaturalLanguageProcessor()
    keywords = processor.get_keywords(content)

    # Add results as a record to database.
    api_results = article_a.get_articles(keywords)
    webpage_lookup = web_page_lookup.create_webpage_lookup(
        user_id, content, lookup_id, filename, keywords, current_dt,
        api_results)

    # Get the User Object and find the top 10 keywords
    user = user_collection.get_user(user_id)
    user_keywords = web_page_lookup.count_keywords(user)[:10]

    return_dict = {
        "lookup_id": lookup_id,
        "user_id": user_id,
        "datetime": str(current_dt),
        "keywords": keywords,
        "user_keywords": user_keywords
    }

    for result in api_results.keys():
        return_dict[result] = api_results[result]

    return jsonify(return_dict)
Пример #4
0
def test_set_learning_context(db_conn, users_table):
    """
    Expect to set the learning context.
    """

    users_table.insert({"id": "abcd1234", "name": "Dalton", "email": "*****@*****.**", "password": "******"}).run(
        db_conn
    )

    user = get_user({"id": "abcd1234"}, db_conn)

    set_learning_context(user, card={"entity_id": "A"})
    assert get_learning_context(user) == {"card": {"entity_id": "A"}}

    set_learning_context(
        user, unit={"entity_id": "B", "name": "Banana", "body": "Banana"}, set={"entity_id": "C", "name": "Coconut"}
    )
    assert get_learning_context(user) == {
        "card": {"entity_id": "A"},
        "unit": {"entity_id": "B", "name": "Banana", "body": "Banana"},
        "set": {"entity_id": "C", "name": "Coconut"},
    }

    set_learning_context(user, set=None)
    assert get_learning_context(user) == {
        "card": {"entity_id": "A"},
        "unit": {"entity_id": "B", "name": "Banana", "body": "Banana"},
    }

    set_learning_context(user, card=None, unit=None)
    assert get_learning_context(user) == {}
Пример #5
0
def get_user_route(request, user_id):
    """
    Get the user by their ID.
    """

    db_conn = request["db_conn"]
    user = get_user({"id": user_id}, db_conn)
    current_user = get_current_user(request)
    # Posts if in request params
    # Sets if in request params and allowed
    # Follows if in request params and allowed
    if not user:
        return abort(404)

    data = {}
    data["user"] = deliver_user(user, access="private" if current_user and user["id"] == current_user["id"] else None)

    # TODO-2 SPLITUP create new endpoints for these instead
    if "posts" in request["params"]:
        data["posts"] = [post.deliver() for post in get_posts_facade(db_conn, user_id=user["id"])]
    if "sets" in request["params"] and user["settings"]["view_sets"] == "public":
        u_sets = UserSets.get(db_conn, user_id=user["id"])
        data["sets"] = [set_.deliver() for set_ in u_sets.list_sets(db_conn)]
    if "follows" in request["params"] and user["settings"]["view_follows"] == "public":
        data["follows"] = [follow.deliver() for follow in Follow.list(db_conn, user_id=user["id"])]
    if "avatar" in request["params"]:
        size = int(request["params"]["avatar"])
        data["avatar"] = get_avatar(user["email"], size if size else None)

    return 200, data
Пример #6
0
    def save(self, db_conn):
        """
        Overwrite save method to add to Elasticsearch.
        """

        # TODO-2 should we validate the save worked before going to ES?

        from database.topic import get_topic, deliver_topic
        from database.user import get_user, deliver_user

        data = json_prep(self.deliver())
        topic = get_topic({'id': self['topic_id']}, db_conn)
        if topic:
            data['topic'] = json_prep(deliver_topic(topic))
        user = get_user({'id': self['user_id']}, db_conn)
        if user:
            data['user'] = json_prep(deliver_user(user))

        es.index(
            index='entity',
            doc_type='post',
            body=data,
            id=self['id'],
        )
        return super().save(db_conn)
Пример #7
0
def get_follows_route(request):
    """
  Get a list of the users follows.
  """

    db_conn = request['db_conn']
    current_user = get_current_user(request)
    user_id = request['params'].get('user_id')
    if user_id:
        user = get_user(db_conn, {'id': user_id})
        if not user:
            return abort(404, 'sYkDuhNmReOrKyR0xsBmHg')
        if (user != current_user
                and user['settings']['view_follows'] != 'public'):
            return abort(403, 'FnH15Y3MRma6bU2gXqzjQQ')
    else:
        user = current_user
        if not user:
            return abort(401, 'YMC5rhI1TOCgUQu6jJeoQg')
    params = dict(**request['params'])
    params['user_id'] = user['id']
    follows = list_follows_by_user(db_conn, params)
    return 200, {
        'follows':
        [deliver_follow(follow, access='private') for follow in follows]
    }
def test_judge_diagnose(db_conn, users_table, units_table, responses_table):
    """
    Expect to add no known ability to "diagnose".
    """

    add_test_set(db_conn, users_table, units_table, responses_table)
    unit = Unit.get(db_conn, entity_id="divide")
    user = get_user({"id": "user"}, db_conn)
    assert judge(db_conn, unit, user) == "diagnose"
def test_judge_done(db_conn, units_table, users_table, responses_table):
    """
    Expect to show "done".
    """

    add_test_set(db_conn, users_table, units_table, responses_table)
    unit = Unit.get(db_conn, entity_id="add")
    user = get_user({"id": "user"}, db_conn)
    assert judge(db_conn, unit, user) == "done"
def test_judge_learn(db_conn, units_table, users_table, responses_table):
    """
    Expect to add known low ability to "learn".
    """

    add_test_set(db_conn, users_table, units_table, responses_table)
    unit = Unit.get(db_conn, entity_id="multiply")
    user = get_user({"id": "user"}, db_conn)
    assert judge(db_conn, unit, user) == "learn"
def test_judge_done(db_conn, units_table, users_table, responses_table):
    """
    Expect to show "done".
    """

    add_test_set(db_conn, users_table, units_table, responses_table)
    unit = Unit.get(db_conn, entity_id='add')
    user = get_user({'id': 'user'}, db_conn)
    assert judge(db_conn, unit, user) == "done"
def test_judge_learn(db_conn, session):
    """
  Expect to add known low ability to "learn".
  """

    add_test_subject(db_conn)
    unit = get_latest_accepted_unit(db_conn, entity_id=unit_multiply_uuid)
    user = get_user(db_conn, {'id': user_id})
    assert judge(db_conn, unit, user) == "learn"
def test_judge_done(db_conn, session):
    """
  Expect to show "done".
  """

    add_test_subject(db_conn)
    unit = get_latest_accepted_unit(db_conn, entity_id=unit_add_uuid)
    user = get_user(db_conn, {'id': user_id})
    assert judge(db_conn, unit, user) == "done"
def test_judge_diagnose(db_conn, session):
    """
  Expect to add no known ability to "diagnose".
  """

    add_test_subject(db_conn)
    unit = get_latest_accepted_unit(db_conn, entity_id=unit_divide_uuid)
    user = get_user(db_conn, {'id': user_id})
    assert judge(db_conn, unit, user) == "diagnose"
def test_judge_review(db_conn, session):
    """
  Expect to add older, high ability to "review".
  """

    add_test_subject(db_conn)
    unit = get_latest_accepted_unit(db_conn, entity_id=unit_subtract_uuid)
    user = get_user(db_conn, {'id': user_id})
    assert judge(db_conn, unit, user) == "review"
def test_judge_diagnose(db_conn, users_table, units_table, responses_table):
    """
    Expect to add no known ability to "diagnose".
    """

    add_test_set(db_conn, users_table, units_table, responses_table)
    unit = Unit.get(db_conn, entity_id='divide')
    user = get_user({'id': 'user'}, db_conn)
    assert judge(db_conn, unit, user) == "diagnose"
def test_judge_review(db_conn, users_table, units_table, responses_table):
    """
    Expect to add older, high ability to "review".
    """

    add_test_set(db_conn, users_table, units_table, responses_table)
    unit = Unit.get(db_conn, entity_id='subtract')
    user = get_user({'id': 'user'}, db_conn)
    assert judge(db_conn, unit, user) == "review"
def test_judge_learn(db_conn, units_table, users_table, responses_table):
    """
    Expect to add known low ability to "learn".
    """

    add_test_set(db_conn, users_table, units_table, responses_table)
    unit = Unit.get(db_conn, entity_id='multiply')
    user = get_user({'id': 'user'}, db_conn)
    assert judge(db_conn, unit, user) == "learn"
def test_judge_review(db_conn, users_table, units_table, responses_table):
    """
    Expect to add older, high ability to "review".
    """

    add_test_set(db_conn, users_table, units_table, responses_table)
    unit = Unit.get(db_conn, entity_id="subtract")
    user = get_user({"id": "user"}, db_conn)
    assert judge(db_conn, unit, user) == "review"
Пример #20
0
def get_current_user(request):
  """
  Get the current user if available, else None.
  """

  user_id = get_current_user_id(request)
  if user_id:
    db_conn = request['db_conn']
    return get_user(db_conn, {'id': user_id})
Пример #21
0
def test_set_learning_context(db_conn, users_table):
    """
    Expect to set the learning context.
    """

    users_table.insert({
        'id': 'abcd1234',
        'name': 'Dalton',
        'email': '*****@*****.**',
        'password': '******',
    }).run(db_conn)

    user = get_user({'id': 'abcd1234'}, db_conn)

    set_learning_context(user, card={'entity_id': 'A'})
    assert get_learning_context(user) == {'card': {'entity_id': 'A'}}

    set_learning_context(user,
                         unit={
                             'entity_id': 'B',
                             'name': 'Banana',
                             'body': "Banana",
                         },
                         set={
                             'entity_id': 'C',
                             'name': 'Coconut',
                         })
    assert get_learning_context(user) == {
        'card': {
            'entity_id': 'A',
        },
        'unit': {
            'entity_id': 'B',
            'name': 'Banana',
            'body': "Banana",
        },
        'set': {
            'entity_id': 'C',
            'name': 'Coconut',
        }
    }

    set_learning_context(user, set=None)
    assert get_learning_context(user) == {
        'card': {
            'entity_id': 'A',
        },
        'unit': {
            'entity_id': 'B',
            'name': 'Banana',
            'body': "Banana",
        },
    }

    set_learning_context(user, card=None, unit=None)
    assert get_learning_context(user) == {}
Пример #22
0
def test_log_in_user(users_table, db_conn):
    """
    Expect to log in as a user.
    """

    create_user_in_db(users_table, db_conn)
    user = get_user({'id': 'abcd1234'}, db_conn)
    token = log_in_user(user)
    assert token
    assert redis.get(token).decode() == 'abcd1234'
Пример #23
0
def test_log_in_user(db_conn):
    """
  Expect to log in as a user.
  """

    create_user_in_db(db_conn)
    user = get_user(db_conn, {'id': user_id})
    token = log_in_user(user)
    assert token
    assert red.get(token).decode() == convert_uuid_to_slug(user_id)
Пример #24
0
def log_in_route(request):
    """
    Log in user.
    """

    db_conn = request["db_conn"]
    name = request["params"].get("name") or ""
    name = name.lower().strip()

    user = get_user({"name": name}, db_conn)
    if not user:
        user = get_user({"email": request["params"].get("name")}, db_conn)
    if not user:
        return 404, {"errors": [{"name": "name", "message": c("no_user")}], "ref": "FYIPOI8g2nzrIEcJYSDAfmti"}
    real_encrypted_password = user["password"]
    given_password = request["params"].get("password")
    if not is_password_valid(real_encrypted_password, given_password):
        return 400, {"errors": [{"name": "password", "message": c("no_match")}], "ref": "UwCRydZ7Agi7LYKv9c1y07ft"}
    return _log_in(user)
Пример #25
0
def test_log_in_user(users_table, db_conn):
    """
    Expect to log in as a user.
    """

    create_user_in_db(users_table, db_conn)
    user = get_user({'id': 'abcd1234'}, db_conn)
    token = log_in_user(user)
    assert token
    assert redis.get(token).decode() == 'abcd1234'
Пример #26
0
def create_token_route(request):
  """
  Create an email token for the user.
  """

  db_conn = request['db_conn']
  user = get_user(db_conn, {'email': request['params'].get('email')})
  if not user:
    return abort(404, 'AyuDktXTTJqNOp6TV5A3yA')
  get_email_token(user)
  return 200, {}  # NB do not output token
Пример #27
0
def get_current_user(request):
    """
    Get the current user if available, else None.
    """

    cookies = request.get('cookies', {})
    session_id = cookies.get('session_id')
    user_id = redis.get(session_id)
    if user_id:
        user_id = user_id.decode()
        return get_user({'id': user_id}, request['db_conn'])
Пример #28
0
def create_token_route(request):
    """
    Create an email token for the user.
    """

    db_conn = request["db_conn"]
    user = get_user({"email": request["params"].get("email")}, db_conn)
    if not user:
        return abort(404)
    get_email_token(user)
    return 200, {}
Пример #29
0
def create_token_route(request):
    """
    Create an email token for the user.
    """

    db_conn = request['db_conn']
    user = get_user({'email': request['params'].get('email')}, db_conn)
    if not user:
        return abort(404)
    get_email_token(user)
    return 200, {}
Пример #30
0
def get_current_user(request):
    """
    Get the current user if available, else None.
    """

    cookies = request.get("cookies", {})
    session_id = cookies.get("session_id")
    user_id = redis.get(session_id)
    if user_id:
        user_id = user_id.decode()
        return get_user({"id": user_id}, request["db_conn"])
Пример #31
0
def test_get_email_token(db_conn, users_table):
    """
    Expect an email token created so a user can reset their password.
    """

    users_table.insert({"id": "abcd1234", "name": "Dalton", "email": "*****@*****.**", "password": "******"}).run(
        db_conn
    )
    user = get_user({"id": "abcd1234"}, db_conn)
    token = get_email_token(user, send_email=False)
    assert redis.get("user_password_token_abcd1234")
    assert token
Пример #32
0
def test_user_create_password_ok(db_conn):
    """
  Expect a user to be able to reset their password.
  """

    create_user_in_db(db_conn)
    user = get_user(db_conn, {'id': user_id})
    pw1 = user['password']
    token = get_email_token(user)

    request = {
        'params': {
            'token': token,
            'password': '******'
        },
        'db_conn': db_conn
    }
    code, _ = routes.user.create_password_route(request, user_id)
    assert code == 200
    user = get_user(db_conn, {'id': user_id})
    assert user['password'] != pw1
Пример #33
0
def test_user_create_password_ok(db_conn, users_table):
    """
    Expect a user to be able to reset their password.
    """

    create_user_in_db(users_table, db_conn)
    user = get_user({'id': 'abcd1234'}, db_conn)
    pw1 = user['password']
    token = get_email_token(user, send_email=False)

    request = {
        'params': {
            'token': token,
            'password': '******'
        },
        'db_conn': db_conn
    }
    code, response = routes.user.create_password_route(request, 'abcd1234')
    assert code == 200
    user = get_user({'id': 'abcd1234'}, db_conn)
    assert user['password'] != pw1
Пример #34
0
def test_user_create_password_ok(db_conn, users_table):
    """
    Expect a user to be able to reset their password.
    """

    create_user_in_db(users_table, db_conn)
    user = get_user({'id': 'abcd1234'}, db_conn)
    pw1 = user['password']
    token = get_email_token(user, send_email=False)

    request = {
        'params': {
            'token': token,
            'password': '******'
        },
        'db_conn': db_conn
    }
    code, response = routes.user.create_password_route(request, 'abcd1234')
    assert code == 200
    user = get_user({'id': 'abcd1234'}, db_conn)
    assert user['password'] != pw1
Пример #35
0
def test_is_valid_token(db_conn, users_table):
    """
    Expect a valid token to be approved.
    Expect an invalid token to not be approved.
    """

    users_table.insert({"id": "abcd1234", "name": "Dalton", "email": "*****@*****.**", "password": "******"}).run(
        db_conn
    )
    user = get_user({"id": "abcd1234"}, db_conn)
    token = get_email_token(user, send_email=False)
    assert is_valid_token(user, token)
    assert not is_valid_token(user, "abcd1234")
def test_traverse(db_conn, units_table, users_table, responses_table, sets_table):
    """
    Expect to take a list of units and traverse them correctly.
    Basic test.
    """

    add_test_set(db_conn, users_table, units_table, responses_table, sets_table)

    set_ = Set.get(db_conn, entity_id="set")
    user = get_user({"id": "user"}, db_conn)
    buckets = traverse(db_conn, user, set_)
    assert buckets["diagnose"][0]["entity_id"] == "divide"
    assert buckets["learn"][0]["entity_id"] == "multiply"
    assert buckets["review"][0]["entity_id"] == "subtract"
Пример #37
0
def test_log_out_user(users_table, db_conn):
    """
    Expect to log out as a user.
    """

    create_user_in_db(users_table, db_conn)
    user = get_user({'id': 'abcd1234'}, db_conn)
    token = log_in_user(user)
    assert redis.get(token).decode() == 'abcd1234'
    log_out_user({
        'cookies': {'session_id': token},
        'db_conn': db_conn,
    })
    assert redis.get(token) is None
Пример #38
0
def test_get_email_token(db_conn, users_table):
    """
    Expect an email token created so a user can reset their password.
    """

    users_table.insert({
        'id': 'abcd1234',
        'name': 'Dalton',
        'email': '*****@*****.**',
        'password': '******',
    }).run(db_conn)
    user = get_user({'id': 'abcd1234'}, db_conn)
    token = get_email_token(user, send_email=False)
    assert redis.get('user_password_token_abcd1234')
    assert token
Пример #39
0
def create_password_route(request, user_id):
    """
    Update a user's password if the token is valid.
    """

    db_conn = request['db_conn']
    user = get_user({'id': user_id}, db_conn)
    if not user:
        return abort(404)
    token = request['params'].get('token')
    valid = is_valid_token(user, token)
    if not valid:
        return abort(403)
    given_password = request['params'].get('password')
    update_user_password(user, {'password': given_password}, db_conn)
    return _log_in(user)
Пример #40
0
def test_is_valid_token(db_conn, users_table):
    """
    Expect a valid token to be approved.
    Expect an invalid token to not be approved.
    """

    users_table.insert({
        'id': 'abcd1234',
        'name': 'Dalton',
        'email': '*****@*****.**',
        'password': '******',
    }).run(db_conn)
    user = get_user({'id': 'abcd1234'}, db_conn)
    token = get_email_token(user, send_email=False)
    assert is_valid_token(user, token)
    assert not is_valid_token(user, 'abcd1234')
Пример #41
0
def create_password_route(request, user_id):
  """
  Update a user's password if the token is valid.
  """

  db_conn = request['db_conn']
  user = get_user(db_conn, {'id': user_id})
  if not user:
    return abort(404, 'FstipA94SDa0qZ3IwRtcMQ')
  token = request['params'].get('token')
  valid = is_valid_token(user, token)
  if not valid:
    return abort(403, 'qe27rSkpQbi49-pbqEl7Kw')
  given_password = request['params'].get('password')
  update_user_password(db_conn, user, {'password': given_password})
  return _log_in(user)
Пример #42
0
def test_log_out_user(users_table, db_conn):
    """
    Expect to log out as a user.
    """

    create_user_in_db(users_table, db_conn)
    user = get_user({'id': 'abcd1234'}, db_conn)
    token = log_in_user(user)
    assert redis.get(token).decode() == 'abcd1234'
    log_out_user({
        'cookies': {
            'session_id': token
        },
        'db_conn': db_conn,
    })
    assert redis.get(token) is None
Пример #43
0
def test_log_out_user(db_conn):
    """
  Expect to log out as a user.
  """

    create_user_in_db(db_conn)
    user = get_user(db_conn, {'id': user_id})
    token = log_in_user(user)
    assert red.get(token).decode() == convert_uuid_to_slug(user_id)
    log_out_user({
        'cookies': {
            'session_id': token
        },
        'db_conn': db_conn,
    })
    assert red.get(token) is None
def test_traverse(db_conn, units_table, users_table, responses_table,
                  sets_table):
    """
    Expect to take a list of units and traverse them correctly.
    Basic test.
    """

    add_test_set(db_conn, users_table, units_table, responses_table,
                 sets_table)

    set_ = Set.get(db_conn, entity_id='set')
    user = get_user({'id': 'user'}, db_conn)
    buckets = traverse(db_conn, user, set_)
    assert buckets['diagnose'][0]['entity_id'] == 'divide'
    assert buckets['learn'][0]['entity_id'] == 'multiply'
    assert buckets['review'][0]['entity_id'] == 'subtract'
Пример #45
0
def create_password_route(request, user_id):
    """
    Update a user's password if the token is valid.
    """

    db_conn = request["db_conn"]
    user = get_user({"id": user_id}, db_conn)
    if not user:
        return abort(404)
    token = request["params"].get("token")
    valid = is_valid_token(user, token)
    if not valid:
        return abort(403)
    given_password = request["params"].get("password")
    update_user_password(user, {"password": given_password}, db_conn)
    return _log_in(user)
Пример #46
0
def update_user_route(request, user_id):
    """
    Update the user. Must be the current user.
    """

    db_conn = request["db_conn"]
    user = get_user({"id": user_id}, db_conn)
    current_user = get_current_user(request)
    if not user:
        return abort(404)
    if not user["id"] == current_user["id"]:
        return abort(401)
    user, errors = update_user(user, request["params"], db_conn)
    if len(errors):
        return 400, {"errors": errors, "ref": "AS7LCAWiOOyeEbNOrbsegVY9"}
    return 200, {"user": deliver_user(user, access="private")}
Пример #47
0
def get_user_route(request, user_id):
  """
  Get the user by their ID.
  """

  db_conn = request['db_conn']
  user = get_user(db_conn, {'id': user_id})
  if not user:
    return abort(404, 'Tp5JnWO1SWms2lTdhw3bJQ')
  current_user = get_current_user(request)
  access = 'private' if (current_user and
                         user['id'] == current_user['id']) else None
  data = {'user': deliver_user(user, access)}
  if 'avatar' in request['params']:
    size = int(request['params']['avatar']) or None
    data['avatar'] = get_avatar(user['email'], size)
  return 200, data
Пример #48
0
def test_seq_next(db_conn, session):
    """
    Expect sequencer route to say where to go next.
    """

    request = {
        'cookies': {'session_id': session},
        'db_conn': db_conn,
    }
    user = get_user({'id': 'abcd1234'}, db_conn)
    set_learning_context(user, next={
        'method': 'DANCE',
        'path': '/s/unicorns'
    })
    code, response = routes.next.next_route(request)
    assert code == 200
    assert response['next']['method'] == 'DANCE'
    set_learning_context(user, next=None)
Пример #49
0
def test_get_learning_context(db_conn, users_table):
    """
    Expect to get the learning context.
    """

    users_table.insert({"id": "abcd1234", "name": "Dalton", "email": "*****@*****.**", "password": "******"}).run(
        db_conn
    )

    user = get_user({"id": "abcd1234"}, db_conn)

    redis.set(
        "learning_context_abcd1234",
        json.dumps({"card": {"entity_id": "A"}, "unit": {"entity_id": "B"}, "set": {"entity_id": "C"}}),
    )
    assert get_learning_context(user) == {
        "card": {"entity_id": "A"},
        "unit": {"entity_id": "B"},
        "set": {"entity_id": "C"},
    }

    redis.delete("learning_context_abcd1234")
    assert get_learning_context(user) == {}
Пример #50
0
def get_posts_route(request, topic_id):
    """
    Get a reverse chronological listing of posts for given topic.
    Includes topic meta data and posts (or proposals or votes).
    Paginates.
    """

    db_conn = request['db_conn']

    # Is the topic valid?
    topic = Topic.get(db_conn, id=topic_id)
    if not topic:
        return 404, {
            'errors': [{
                'name': 'topic_id',
                'message': c('no_topic'),
            }],
            'ref': 'pgnNbqSP1VUWkOYq8MVGPrSS',
        }

    # Pull the entity
    entity_kind = topic['entity']['kind']
    entity = get_latest_accepted(db_conn,
                                 entity_kind,
                                 topic['entity']['id'])

    # Pull all kinds of posts
    posts = get_posts_facade(
        db_conn,
        limit=request['params'].get('limit') or 10,
        skip=request['params'].get('skip') or 0,
        topic_id=topic_id
    )

    # For proposals, pull up the proposal entity version
    # ...then pull up the previous version
    # ...make a diff between the previous and the proposal entity version
    diffs = {}
    entity_versions = {}
    for post_ in posts:
        if post_['kind'] == 'proposal':
            entity_version = entity_versions[post_['id']] = get_version(
                db_conn,
                post_['entity_version']['kind'],
                post_['entity_version']['id']
            )
            previous_version = get_version(
                db_conn,
                post_['entity_version']['kind'],
                entity_version['previous_id']
            )
            if previous_version:
                diffs[post_['id']] = object_diff(previous_version.deliver(),
                                                 entity_version.deliver())

    # TODO-2 SPLITUP create new endpoint for this instead
    users = {}
    for post_ in posts:
        user_id = post_['user_id']
        if user_id not in users:
            user = get_user({'id': user_id}, db_conn)
            if user:
                users[user_id] = {
                    'name': user['name'],
                    'avatar': get_avatar(user['email'], 48),
                }

    # TODO-2 SPLITUP create new endpoints for these instead
    output = {
        'topic': topic.deliver(),
        'posts': [p.deliver() for p in posts],
        'entity_versions': {
            p: ev.deliver('view')
            for p, ev in entity_versions.items()
        },
        # 'diffs': diffs,  TODO-2 this causes a circular dependency
        'users': users,
    }
    if entity:
        output[entity_kind] = entity.deliver()
    return 200, output