示例#1
0
def test_deleted_user_no_message_permission():
    """Ensure nobody can message a deleted user."""
    deleted_user = User("Deleted_User", "password")
    deleted_user.is_deleted = True

    principals = principals_allowed_by_permission(deleted_user, "message")
    assert not principals
示例#2
0
def test_banned_user_no_message_permission():
    """Ensure nobody can message a banned user."""
    banned_user = User("Banned_User", "password")
    banned_user.is_banned = True

    principals = principals_allowed_by_permission(banned_user, "message")
    assert not principals
示例#3
0
def test_user_email_check():
    """Ensure checking a user's email address works correctly."""
    user = User("Some_User", "Some_Password")
    user.email_address = "*****@*****.**"

    assert user.is_correct_email_address("*****@*****.**")

    assert not user.is_correct_email_address("*****@*****.**")
示例#4
0
def test_duplicate_username(db):
    """Ensure two users with the same name can't be created."""
    original = User("Inimitable", "securepassword")
    db.add(original)
    duplicate = User("Inimitable", "adifferentpassword")
    db.add(duplicate)

    with raises(IntegrityError):
        db.commit()
示例#5
0
def post_register(
    request: Request,
    username: str,
    password: str,
    password_confirm: str,
    invite_code: str,
) -> HTTPFound:
    """Process a registration request."""
    if not request.params.get("accepted_terms"):
        raise HTTPUnprocessableEntity(
            "Terms of Use and Privacy Policy must be accepted.")

    if password != password_confirm:
        raise HTTPUnprocessableEntity(
            "Password and confirmation do not match.")

    code_row = _handle_invite_code(request, invite_code)

    # create the user and set inviter to the owner of the invite code
    user = User(username, password)
    if code_row:
        user.inviter_id = code_row.user_id

    # flush the user insert to db, will fail if username is already taken
    request.db_session.add(user)
    try:
        request.db_session.flush()
    except IntegrityError:
        raise HTTPUnprocessableEntity(
            "That username has already been registered.")

    # the flush above will generate the new user's ID, so use that to update the invite
    # code with info about the user that registered with it
    if code_row:
        code_row.invitee_id = user.user_id

    # subscribe the new user to all groups except ~test
    all_groups = request.query(Group).all()
    for group in all_groups:
        if group.path == "test":
            continue
        request.db_session.add(GroupSubscription(user, group))

    _send_welcome_message(user, request)

    incr_counter("registrations")

    # log the user in to the new account
    remember(request, user.user_id)

    # set request.user before logging so the user is associated with the event
    request.user = user
    request.db_session.add(Log(LogEventType.USER_REGISTER, request))

    # redirect to the front page
    raise HTTPFound(location="/")
示例#6
0
def test_duplicate_username_case_insensitive(db):
    """Ensure usernames only differing in casing can't be created."""
    test_username = "******"
    original = User(test_username.lower(), "hackproof")
    db.add(original)
    duplicate = User(test_username.upper(), "sosecure")
    db.add(duplicate)

    with raises(IntegrityError):
        db.commit()
示例#7
0
def test_creation_validates_schema(mocker):
    """Ensure that model creation goes through schema validation."""
    mocker.spy(UserSchema, 'validate')
    User('testing', 'testpassword')
    call_args = [call[0] for call in UserSchema.validate.call_args_list]
    expected_args = {'username': '******', 'password': '******'}
    assert any(expected_args in call for call in call_args)
示例#8
0
def test_creation_validates_schema(mocker):
    """Ensure that model creation goes through schema validation (via load())."""
    mocker.spy(UserSchema, "load")
    User("testing", "testpassword")
    call_args = [call[0] for call in UserSchema.load.call_args_list]
    expected_args = {"username": "******", "password": "******"}
    assert any(expected_args in call for call in call_args)
示例#9
0
def session_user(sdb):
    """Create a user named 'SessionUser' in the db for test session."""
    # note that some tests may depend on this username/password having these specific
    # values, so make sure to search for and update those tests if you change the
    # username or password for any reason
    user = User("SessionUser", "session user password")
    sdb.add(user)
    sdb.commit()

    yield user
示例#10
0
def insert_dev_data(config_path: str) -> None:
    """Load the app config and insert some "starter" data for a dev version."""
    session = get_session_from_config(config_path)

    user = User("TestUser", "password")
    group = Group("testing", "An automatically created group to use for testing")
    subscription = GroupSubscription(user, group)

    session.add_all([user, group, subscription])

    session.commit()
示例#11
0
def session_user2(sdb):
    """Create a second user named 'OtherUser' in the db for test session.

    This is useful for cases where two different users are needed, such as when testing
    private messages.
    """
    user = User("OtherUser", "other user password")
    sdb.add(user)
    sdb.commit()

    yield user
示例#12
0
def insert_dev_data(config_path: str) -> None:
    """Load the app config and insert some "starter" data for a dev version."""
    session = get_session_from_config(config_path)

    session.add_all([
        User('TestUser', 'password'),
        Group(
            'testing',
            'An automatically created group to use for testing purposes',
        ),
    ])

    session.commit()
示例#13
0
def user_list(db):
    """Create several users."""
    users = []
    for name in ["foo", "bar", "baz"]:
        user = User(name, "password")
        users.append(user)
        db.add(user)
    db.commit()

    yield users

    for user in users:
        db.delete(user)
    db.commit()
示例#14
0
def test_change_password():
    """Ensure changing a user password works as expected."""
    new_user = User("A_New_User", "lovesexsecretgod")

    new_user.change_password("lovesexsecretgod", "lovesexsecretgod1")

    # the old one shouldn't work
    assert not new_user.is_correct_password("lovesexsecretgod")

    # the new one should
    assert new_user.is_correct_password("lovesexsecretgod1")
示例#15
0
def test_ban_permission_manually_granted():
    """Ensure ban permissions must be granted manually."""
    user = User("Test_User", "password")

    principals = principals_allowed_by_permission(user, "ban")
    assert principals == {"*:user.ban"}
示例#16
0
def post_register(
    request: Request,
    username: str,
    password: str,
    password_confirm: str,
    invite_code: str,
) -> HTTPFound:
    """Process a registration request."""
    if not request.params.get("accepted_terms"):
        raise HTTPUnprocessableEntity(
            "Terms of Use and Privacy Policy must be accepted.")

    if password != password_confirm:
        raise HTTPUnprocessableEntity(
            "Password and confirmation do not match.")

    # attempt to fetch and lock the row for the specified invite code (lock prevents
    # concurrent requests from using the same invite code)
    lookup_code = UserInviteCode.prepare_code_for_lookup(invite_code)
    code_row = (
        request.query(UserInviteCode).filter(
            UserInviteCode.code == lookup_code,
            UserInviteCode.invitee_id == None,  # noqa
        ).with_for_update(skip_locked=True).one_or_none())

    if not code_row:
        incr_counter("invite_code_failures")
        raise HTTPUnprocessableEntity("Invalid invite code")

    # create the user and set inviter to the owner of the invite code
    user = User(username, password)
    user.inviter_id = code_row.user_id

    # flush the user insert to db, will fail if username is already taken
    request.db_session.add(user)
    try:
        request.db_session.flush()
    except IntegrityError:
        raise HTTPUnprocessableEntity(
            "That username has already been registered.")

    # the flush above will generate the new user's ID, so use that to update the invite
    # code with info about the user that registered with it
    code_row.invitee_id = user.user_id

    # subscribe the new user to all groups except ~test
    all_groups = request.query(Group).all()
    for group in all_groups:
        if group.path == "test":
            continue
        request.db_session.add(GroupSubscription(user, group))

    _send_welcome_message(user, request)

    incr_counter("registrations")

    # log the user in to the new account
    remember(request, user.user_id)

    # set request.user before logging so the user is associated with the event
    request.user = user
    request.db_session.add(Log(LogEventType.USER_REGISTER, request))

    # redirect to the front page
    raise HTTPFound(location="/")
示例#17
0
def test_password_contained_in_username():
    """Ensure a user can't be created with the password in the username."""
    with raises(ValidationError):
        User("PasswordIsVeryGood", "VeryGood")
示例#18
0
def test_user_password_check():
    """Ensure checking the password for a new user works correctly."""
    new_user = User("myusername", "mypassword")
    assert new_user.is_correct_password("mypassword")
示例#19
0
def test_username_contained_in_password():
    """Ensure a user can't be created with the username in the password."""
    with raises(ValidationError):
        User("MyUsername", "iputmyusernameinmypassword")
示例#20
0
def test_username_and_password_differ_in_casing():
    """Ensure a user can't be created with name/pass the same except case."""
    with raises(ValidationError):
        User("NobodyWillGuess", "nobodywillguess")
示例#21
0
def test_matching_password_and_username():
    """Ensure a new user can't be created with same username and password."""
    with raises(ValidationError):
        User("UnimaginativePassword", "UnimaginativePassword")
示例#22
0
def test_user_email_check_case_insensitive():
    """Ensure the user email address check isn't case-sensitive."""
    user = User("Some_User", "Some_Password")
    user.email_address = "*****@*****.**"

    assert user.is_correct_email_address("*****@*****.**")
示例#23
0
def test_conversation_other_user_invalid(conversation):
    """Ensure that "other user" method fails if the user isn't involved."""
    new_user = User("SomeOutsider", "super amazing password")

    with raises(ValueError):
        assert conversation.other_user(new_user)
示例#24
0
def test_too_short_password():
    """Ensure a new user can't be created with a too-short password."""
    password = "******" * (PASSWORD_MIN_LENGTH - 1)
    with raises(ValidationError):
        User("ShortPasswordGuy", password)
示例#25
0
def test_only_admin_has_ban_permission():
    """Ensure only admins have ban permissions."""
    user = User("Test_User", "password")

    principals = principals_allowed_by_permission(user, "ban")
    assert principals == {"admin"}