Example #1
0
def test_auth_register_multiple_users():
    """
    - u_id is unique when multiple users are entered
    creates a large  number of u_id's and make sure none of them conflict
    tested it up to 10,000 array_size but takes a while, can go higher for sure
    """

    clear()

    array_size = 100
    array = [0] * array_size

    i = 0
    while i < array_size:
        array[i] = (auth.auth_register('test' + str(i)
        + '@example.com', 'password', 'Test', 'Personmanperson')['u_id'])
        i += 1

    assert len(array) == len(set(array))

    # a unique handle is produced
    new_list = []
    for user in data.return_users():
        new_list.append(user['handle_str'])
    assert len(new_list) == len(set(new_list))
Example #2
0
def test_register(url):
    '''
    Test whether requests sent to auth_http for auth_register come back
    '''
    # clear out the databases
    requests.delete(url + 'other/clear', json={})

    resp = requests.post(url + 'auth/register',
                         json={
                             'email': '*****@*****.**',
                             'password': '******',
                             'name_first': 'Emily',
                             'name_last': 'Luo?'
                         })

    text = json.loads(resp.text)

    focus_user = None

    for user in data.return_users():
        if user['u_id'] == text.get('u_id'):
            focus_user = user
            break

    assert focus_user is not None
    assert focus_user.get('email') == '*****@*****.**'
Example #3
0
def user_profile(token, u_id):
    """For a valid user, returns information about their user_id, email, first name, last name, and handle.

    Raises:
        1. InputError
            - User with u_id is not a valid user
    """
    person = decode_token(token)
    if person is None:
        return {'is_success': False}
    # Avoid someone put a string
    try:
        u_id = int(u_id)
    except Exception as e:
        raise InputError('terrible uid') from e
    user = None

    for i in data.return_users():
        if i['u_id'] == u_id:
            user = i

    if user is None:
        raise InputError('not user')

    return {
        'user': {
            'u_id': u_id,
            'email': user['email'],
            'name_first': user['name_first'],
            'name_last': user['name_last'],
            'handle_str': user['handle_str'],
            'profile_img_url': '',
        },
    }
Example #4
0
def auth_login(email, password):
    """Used to log user into program."""

    # check if email is valid.
    regex_email_check(email)

    # Check if email is used by user.
    focus_user = check_in_users('email', data.return_users(), email)

    # If not stored, raise an error.
    if focus_user is None:
        raise InputError('Email is not for a registered user')

    # Check password is correct
    if focus_user['password'] != hash_(password):
        raise InputError('Incorrect Password')

    # Creates a token
    u_id = focus_user['u_id']
    session_secret = create_secret(50)
    token = create_token(u_id, session_secret)

    # update the session_secret in stored users
    data.update_user(u_id, 'session_secret', session_secret)

    token_object = {
        'u_id': u_id,
        'token': token,
    }

    return token_object
Example #5
0
def passwordreset_request(email):
    """Password reseting request."""

    # find the user in question
    focus_user = None
    for user in data.return_users():
        if user['email'] == email:
            focus_user = user
            break
    if focus_user is None:
        raise InputError('This is an incorrect email')

    # create the secret code
    code = create_secret(10, whitespace=False)

    # store the code
    u_id = focus_user['u_id']
    data.update_user(u_id, 'password_reset', {
        'origin': datetime.datetime.utcnow(),
        'code': code
    })

    # get the html formatted
    html = data.return_password_reset_email().format(
        PREVIEWTEXT='This is your password reset code',
        FIRSTNAME=focus_user.get('name_first'),
        CODE=code)

    # send the email
    send_email(email, html)
    return {}
Example #6
0
def auth_register(email, password, name_first, name_last):
    """Function to register a new user to the program."""

    # check for errors in input
    auth_register_error_check(email, password, name_first, name_last)

    # Create variables for new user
    u_id = create_u_id(data.return_users())
    session_secret = create_secret(50)
    token = create_token(u_id, session_secret)
    handle = handle_generator(name_first, name_last, u_id)
    password = hash_(password)
    permission_id = determine_permission_id()
    # Create and store a user object.
    user = {
        'u_id': u_id,
        'email': email,
        'name_first': name_first,
        'name_last': name_last,
        'handle_str': handle,
        'password': password,
        'permission_id': permission_id,
        'session_secret': session_secret,
        'profile_img_url': '',
    }
    data.append_users(user)

    # Creates an object with u_id and token.
    token_object = {
        'u_id': u_id,
        'token': token,
    }
    return token_object
Example #7
0
def decode_token(token):
    """Return user dict from given token.
    If incorrect token or user is inputted, it returns None.
    """

    # firstly get public u_id from header
    try:
        u_id = jwt.get_unverified_header(token).get('u_id')
    except DecodeError:
        return None

    # next, get the hidden session_secret
    try:
        stored_secret = jwt.decode(token, JWT_SECRET,
                                   algorithms=['HS256']).get('session_secret')
    except DecodeError:
        # if it fails to decode token, return none
        return None
    # find user with session secret
    focus_user = None
    for user in data.return_users():
        if (user.get('session_secret') == stored_secret
                and user.get('u_id') == u_id):
            # if user is correct and matches the session
            focus_user = user
            break

    # if u_id and session_secret match, return user
    # if no user is found, it also returns None
    return focus_user
Example #8
0
def user_profile_setname(token, name_first, name_last):
    """Update the authorised user's first and last name.

    Raises:
        1. InputError
            - name_first is not between 1 and 50 characters inclusively in length
            - name_last is not between 1 and 50 characters inclusively in length
    """
    # decode the token
    person = decode_token(token)
    if person is None:
        return {'is_success': False}
    email = person.get('email')

    # Check first name matches requirements.
    if len(name_first) < 1 or len(name_first) > 50:
        raise InputError('invalid first name')

    # Check Last Name matches requirements.
    if len(name_last) < 1 or len(name_last) > 50:
        raise InputError('invalid last name')
    user=check_in_users("email",data.return_users(),email)
    user['name_first']=name_first
    user['name_last']=name_last
    data.updateByEmail(user,email)
    return {}
Example #9
0
def test_passwordreset_reset_valid_code():
    ''' test passwordreset with a valid code '''
    clear()

    # register a user
    u_id = auth.auth_register('*****@*****.**', 'password', 'Mate', 'Old').get('u_id')

    # send the password reset
    auth.passwordreset_request('*****@*****.**')
    code = get_reset_code(u_id).get('code')
    now = datetime.datetime.utcnow()

    # reset the password
    assert auth.passwordreset_reset(code, 'passwordTime') is not None

    new_hash = auth.hash_('passwordTime')

    # check the password
    valid = False
    for user in data.return_users():
        if (user.get('password') == new_hash
        and abs((now - user.get('password_reset').get('origin')).total_seconds()) < 500):
            valid = True
            break
    # if new password wasn't stored, assert
    assert valid
Example #10
0
def check_permission(user_id):
    """check if given u_id person is permission one"""
    permission_check = 1
    for i in data.return_users():
        if i['u_id'] == user_id:
            permission_check = i['permission_id']

    return permission_check
Example #11
0
def find_user(user_id):
    """Find user's info by search one's id."""
    u_id = -1
    for i in data.return_users():
        if i['u_id'] == user_id:
            u_id = i
            break
    return u_id
Example #12
0
def user_from_u_id(u_id):
    ''' return user from given u_id'''

    focus_user = None
    for user in data.return_users():
        if user['u_id'] == u_id:
            focus_user = user
            break
    return focus_user
Example #13
0
def determine_permission_id():
    """Check first user to add permission id."""
    id = 2
    # check if user list is empty
    if not data.return_users():
        id = 1
    else:
        id = 2

    return id
Example #14
0
def user_profile_setemail(token, email):
    """Update the authorised user's email address.

    Raises:
        1. InputError
            - Email entered is not a valid email using the method provided
            - Email address is already being used by another user
    """
    person = decode_token(token)
    if person is None:
        return {'is_success': False}
    email_now = person.get('email')

    regex_email_check(email)

    user = check_in_users('email', data.return_users(), email)
    if user is not None:
        raise InputError('Cannot use this email repeating :(')

    user = check_in_users('email', data.return_users(), email_now)

    user['email']=email
    data.updateByEmail(user,email_now)
    return {}
Example #15
0
def users_all(token):
    """Return all of the users list."""
    # check that token exists
    owner_from_token(token)
    users = data.return_users()
    list_users = []

    for i in users:
        user = {
            'u_id': i['u_id'],
            'email': i['email'],
            'name_first': i['name_first'],
            'name_last': i['name_last'],
            'handle_str': i['handle_str'],
            'profile_img_url': '',
        }
        list_users.append(user)

    return {'users': list_users}
Example #16
0
def user_profile_sethandle(token, handle_str):
    """Update the authorised user's handle (i.e. display name).

    Raises:
        1. InputError
            - handle_str must be between 3 and 20 characters
            - handle is already used by another user
    """
    person = decode_token(token)
    if person is None:
        return {'is_success': False}
    email = person.get('email')
    # handle_str must be between 3 and 20 characters
    if len(handle_str) < 3 or len(handle_str) > 20:
        raise InputError('1')
    user=check_in_users("email",data.return_users(),email)
    user['handle_str']=handle_str
    data.updateByEmail(user,email)
    return {}
Example #17
0
def test_userpermission_change(url):
    send_request('DELETE', url, 'clear', {})

    user1 = register_user(url, '*****@*****.**', 'emilyisshort', 'Emily',
                          'Luo')
    user2 = register_user(url, '*****@*****.**', 'emilyisshort2', 'Emily2',
                          'Luo2')

    send_request('POST', url, 'admin/permission/change', {
        'token': user1.get('token'),
        'u_id': user2.get('u_id'),
        'permission_id': 1
    })
    #i = other.users/all(u1_token)

    i = data.return_users()
    i_user1 = i[0]
    i_user2 = i[1]
    assert i_user1['permission_id'] == 1
    assert i_user2['permission_id'] == 2
Example #18
0
def handle_generator(name_first, name_last, u_id):
    """
    Generates a unique handle.
    Much simpler than the thing I had before.
    """

    # Create base concatenation.
    raw_concatenation = name_first + name_last
    raw_concatenation = raw_concatenation[:20]
    if check_in_users('handle_str', data.return_users(),
                      raw_concatenation) is None:
        return raw_concatenation

    # add u_id if handle is not already unique
    u_id_len = len(str(u_id))
    cut_concatenation = raw_concatenation[0:20 - u_id_len]
    # u_id is already verified to be unique
    u_id_concatenation = cut_concatenation + str(u_id)

    return u_id_concatenation
Example #19
0
def auth_register_error_check(email, password, name_first, name_last):
    """Handles error checking for auth_register."""

    # Check for valid input.
    regex_email_check(email)

    # Check if email is already used.
    if check_in_users('email', data.return_users(), email) is not None:
        raise InputError('Email Already in Use')

    # check len(password) >= 6.
    if len(password) < 6:
        raise InputError('Password Too Short')

    # Check first name matches requirements.
    if len(name_first) < 1 or len(name_first) > 50:
        raise InputError('First Name Incorrect Length')

    # Check Last Name matches requirements.
    if len(name_last) < 1 or len(name_last) > 50:
        raise InputError('Last Name Incorrect Length')
Example #20
0
def test_admin_userpermission_change_permission_id():
    '''check the initial permission_id of the users is true'''
    other.clear()
    #initialise the users list
    #create the first user
    auth.auth_register('*****@*****.**', 'password', 'FirstN', 'LastN')
    auth.auth_login('*****@*****.**', 'password')

    #create another 2 users
    auth.auth_register('*****@*****.**', 'password', 'FirstN2', 'LastN2')
    auth.auth_login('*****@*****.**', 'password')
    auth.auth_register('*****@*****.**', 'password', 'FirstN3', 'LastN3')
    auth.auth_login('*****@*****.**', 'password')

    #check the default value
    i = data.return_users()
    i_user1 = i[0]
    i_user2 = i[1]
    i_user3 = i[2]
    assert i_user1['permission_id'] == 1
    assert i_user2['permission_id'] == 2
    assert i_user3['permission_id'] == 2
Example #21
0
def test_passwordreset_real_user():
    '''
    This will test what happens when user is real
    '''
    clear()

    # register a user
    u_id = auth.auth_register('*****@*****.**', 'password', 'Mate', 'Old').get('u_id')
    
    auth.passwordreset_request('*****@*****.**')
    code = get_reset_code(u_id).get('code')
    now = datetime.datetime.utcnow()

    # check that the code stored was the same as given code
    valid = False
    for user in data.return_users():
        if (user.get('password_reset').get('code') == code
        and abs((now - user.get('password_reset').get('origin')).total_seconds()) < 500):
            valid = True
            break
    # if code wasn't stored, or it was an incorrect code, it's not valid
    # if password_reset doesn't have an acceptable time delta, it is not valid
    assert valid
Example #22
0
def admin_userpermission_change(token, u_id, permission_id):
    """Change the permission if the admin is a owner."""
    i = owner_from_token(token)  # check that token exists

    users = data.return_users()
    found = 0
    for user in users:  # Check that u_id is valid.
        if user['u_id'] == u_id:
            found = 1
            break

    if found != 1:
        raise InputError(description='The u_id is invalid.')

    if permission_id not in range(1, 3):  # Check the permission_id.
        raise InputError(description='The permission_id is invalid.')

    if i['permission_id'] != 1:  # The admin is not a owner_num.
        raise AccessError(description='The admin is not a owner.')

    data.update_user(u_id, 'permission_id', permission_id)

    return {}
Example #23
0
def test_admin_userpermission_change():
    '''functions test'''
    other.clear()
    #initialise the users list
    #create a user
    user1 = auth.auth_register('*****@*****.**', 'password', 'FirstN', 'LastN')
    user1 = auth.auth_login('*****@*****.**', 'password')
    u1_token = user1['token']

    #create another user
    user2 = auth.auth_register('*****@*****.**', 'password', 'FirstN2',
                               'LastN2')
    user2 = auth.auth_login('*****@*****.**', 'password')
    u2_id = user2['u_id']

    #run the function and test
    other.admin_userpermission_change(u1_token, u2_id, 1)

    i = data.return_users()
    i_user1 = i[0]
    i_user2 = i[1]
    assert i_user1['permission_id'] == 1
    assert i_user2['permission_id'] == 1
Example #24
0
def passwordreset_reset(reset_code, new_password):
    """Check if reset_code is correct."""

    # check that password is valid length
    if len(new_password) < 6:
        raise InputError('Password Too Short')
    now = datetime.datetime.utcnow()

    # check that the code stored was the same as given code
    focus_user = None
    for user in data.return_users():
        if (user.get('password_reset').get('code') == reset_code and abs(
            (now - user.get('password_reset').get('origin')).total_seconds()) <
                500):
            focus_user = user
            break
    # raise input error if person is faulty
    if focus_user is None:
        raise InputError('Invalid Reset Code')

    # store the new password
    data.update_user(focus_user['u_id'], 'password', hash_(new_password))

    return {}
Example #25
0
def get_reset_code(u_id):
    ''' helper function to get the password code '''
    
    for user in data.return_users():
        if user['u_id'] == u_id:
            return user.get('password_reset')