def generate_token(user_id): ''' Returns a JWT token based on the users id and a secret message. if a user is already logged in, it does not add the token to curr_users ''' curr_users = get_valid_tokens() token = encode({'id': user_id}, SECRET, algorithm='HS256').decode('utf-8') if token not in curr_users: curr_users.append(token) return token
def invalidate_token(token): ''' Invalidates token by removing it from curr_users. raises AccessError if token is not in curr_users. Returns true if token is successfully invalidated. ''' curr_users = get_valid_tokens() try: curr_users.remove(token) except ValueError: raise AccessError(description="Token is already invalid") return True
def test_application_clean(): ''' Tests that all global variables have been emptied by the reset ''' for new_user in range(100): user = auth_register("z55555" + str(new_user) + "@unsw.edu.au", "f for hayden rip", "hydaen", "smith") channels_create(user['token'], "test channel" + str(new_user), True) workspace_reset() assert len(get_channels().keys()) == 0 assert len(get_users().keys()) == 0 assert len(get_users()) == 0 assert len(get_slackr_owners()) == 0 assert len(get_valid_tokens()) == 0 original_image_folder = os.path.join(os.getcwd(), 'images/original') assert len(os.listdir(original_image_folder)) == 1 cropped_image_folder = os.path.join(os.getcwd(), 'images/cropped') assert len(os.listdir(cropped_image_folder)) == 1
def check_token(token): '''Checks if a jwt token corresponds to a currently logged in user. If the user's account has been deleted, invalidates that users token. :param token: jwt token :type token: str :raises AccessError: If the token does not correspond to a logged in user :raises AccessError: If the token corresponds to a deleted user :return: User id corresponding to the the valid token :rtype: int ''' curr_users = get_valid_tokens() if not token in curr_users: raise AccessError(description="You do not have a valid token") u_id = decode(token.encode('utf-8'), SECRET, algorithms=['HS256'])['id'] if is_user_disabled(u_id): invalidate_token(token) raise AccessError(description="Your account has been deleted") return u_id