def change_user_permission(token, u_id, permission_id):
    """
    Given a User by their user ID, set their permissions
    to new permissions described by permission_id
    """
    # Store u_id of person running command
    user_from_token = database.get_current_user(token)

    if permission_id not in VALID_PERMISSION_IDS.values():
        raise error.InputError(description="permission_id does not refer to a value permission")
    if (database.get_permission_dict(user_from_token).get("permission_id")
            != VALID_PERMISSION_IDS['owner']):
        # User is not a global owner.
        raise error.AccessError(description="The authorised user is not an owner")

    number_of_owners = 0
    for member in database.get_permissions_list():
        if member.get('permission_id') == VALID_PERMISSION_IDS['owner']:
            number_of_owners += 1

    if (u_id == user_from_token and number_of_owners == 1):
        # i.e. Owner calling this function is only owner.
        raise error.AccessError(description="Owner cannot remove" +
                                " permissions when he is the only owner")


    # Now, having checked for all errors, run function:
    database.set_permissions(u_id, permission_id)
示例#2
0
def channel_removeowner(token, channel_id, u_id):
    # Check that token is valied
    caller = check_token(token)

    # Check that user is part of flockr
    removed_person = find_with_uid(u_id)

    # Find the channel
    target_channel = find_channel(channel_id)

    # Check person to remove is part of channel
    is_member = is_member_check(caller['u_id'], target_channel)
    if not is_member:
        raise error.InputError('User to be removed is not in the channel')

    # Check to see if caller is an owner
    is_owner = is_owner_check(caller['u_id'], target_channel)
    # Access Error if the person calling is not an owner
    if not is_owner:
        raise error.AccessError(
            'You are not an owner of the channel and cannot add owners')

    # Check to see if caller is a flockr owner
    if caller['permission_id'] == 1:
        is_owner = True

    # Check to see if the admin is removing a flockr owner
    if removed_person['permission_id'] == 1:
        raise error.AccessError('You cannot remove rights from Flockr Owner')

    # Access Error if the caller is not an owner
    if not is_owner:
        raise error.AccessError(
            'You are not an owner of the channel and cannot remove owners')

    # Check to see if removed person is an owner
    is_owner = is_owner_check(removed_person['u_id'], target_channel)
    # Input Error if the person to be removed is not owner
    if not is_owner:
        raise error.InputError('Person to be demoted is not an owner')

    # Check to see if we are removing ourselves as owner
    if caller['u_id'] == removed_person['u_id']:
        # If we are the only person left in the channel then raise error
        if len(target_channel['all_members']) == 1:
            raise error.InputError(
                'You are the only person in the channel, you cannot remove yourself as owner, please add another member'
            )
        # If we are the only owner in the channel raise error to indicate a new owner must be assigned
        elif len(target_channel['owner_members']) == 1:
            raise error.InputError(
                'You are the only owner in the channel, please make someone else owner before removing yourself'
            )
        # Otherwise, we can remove self as owner
        else:
            remove_helper_func(channel_id, removed_person)
            return {}
    # We can remove the person as owner
    remove_helper_func(channel_id, removed_person)
    return {}
示例#3
0
def channel_invite(token, channel_id, u_id):
    '''
    Inviting a user to join the channel.
    '''
    #Checked invalid channel
    if helper_functions.check_channelid_valid(channel_id):
        raise error.InputError("Channel not valid")

    # user id is not valid
    if helper_functions.check_uid_valid(u_id):
        raise error.InputError("User not valid")

    # user token is invalid
    if helper_functions.check_token(token).get('token_status'):
        raise error.InputError(description="Token invalid")

    auth_id = helper_functions.check_token(token).get('u_id')

    #If token is in channel
    if helper_functions.check_u_id_in_channel(auth_id, channel_id):
        raise error.AccessError("Authorised user not in channel")

    #User already in channel
    if helper_functions.check_u_id_in_channel(u_id, channel_id) == False:
        raise error.AccessError("Already in channel")

    # add to user to channel if everything is valid
    # details_user =  {u_id, email, name_first, name_last, handle_str}
    for user in channels.channel_data:
        if user.get("channel_id") == channel_id:
            user["member_ids"].append(u_id)
            break

    return {}
示例#4
0
def message_unpin(token, message_id):

    # check for valid user
    caller = check_token(token)

    # check for valid message_id
    target_message = find_message_in_messages(message_id)
    if not target_message['is_pinned']:
        raise error.InputError('Message is not pinned')

    # Find the channel the message is in
    target_channel = find_channel(target_message['channel_id'])

    # Check to see if caller is part of that channel
    is_member = is_member_check(caller['u_id'], target_channel)
    if not is_member:
        raise error.AccessError('You are not part of this channel.')

    # check user is owner
    is_allowed = is_owner_check(caller['u_id'], target_channel)
    if not is_allowed:
        raise error.AccessError('You do not have permission to unpin message')

    for message in target_channel['messages']:
        if message['message_id'] == message_id:
            message['is_pinned'] = False
    for message in data['messages']:
        if message_id == message['message_id']:
            message['is_pinned'] = False
            return {}
示例#5
0
def channel_addowner(token, channel_id, u_id):

    # ORDER OF BUSINESS:
    # 1. Find the first name and last name of the user with u_id
    # 2. Ensure that the owner with th
    # 3. Ensure the user being added as an owner is not already an owner
    # 4. Ensure that the user adding the user as an owner is an owner themself
    # 5. Ensure that the user being added as an owner is a part of the channel to begin with
    channel_id = int(channel_id)
    u_id = int(u_id)
    decoded_jwt = jwt.decode(token.encode('utf-8'),
                             data.secret,
                             algorithms=['HS256'])
    decoded_token = decoded_jwt['token']
    owner = token_find_user(decoded_token)
    channel = find_channel(channel_id)
    user_added_as_owner = {}
    user_added_as_owner_dict = find_user(u_id)

    user_added_as_owner['u_id'] = user_added_as_owner_dict['u_id']
    user_added_as_owner['name_first'] = user_added_as_owner_dict['name_first']
    user_added_as_owner['name_last'] = user_added_as_owner_dict['name_last']
    user_added_as_owner['profile_img_url'] = user_added_as_owner_dict[
        'profile_img_url']

    # 3. Ensure the user being added is not already an owner
    for user in channel['owner_members']:
        if user['u_id'] == user_added_as_owner['u_id']:
            raise error.InputError(
                description="User is already an owner of this channel")

    # 4. Ensure that the user adding another user as an owner is an owner themself
    user_is_owner = False
    for user in channel['owner_members']:
        if user['u_id'] == owner['u_id']:
            user_is_owner = True
            #break

    if user_is_owner == False:
        raise error.AccessError(
            description=
            "User attempting to add an owner is not an owner themself")

    # Ensure that the user being added as owner is in the channel
    user_in_channel = False
    for user in channel['all_members']:
        if user['u_id'] == user_added_as_owner['u_id']:
            user_in_channel = True
    if not user_in_channel:
        raise error.AccessError(
            description="User to be added as owner is not part of the channel")

    channel['owner_members'].append(user_added_as_owner)

    return
示例#6
0
def channel_invite(token, channel_id, u_id):
    # The user with id :u_id will be added to the server
    channel_id = int(channel_id)
    u_id = int(u_id)
    decoded_jwt = jwt.decode(token.encode('utf-8'),
                             data.secret,
                             algorithms=['HS256'])
    decoded_token = decoded_jwt['token']
    inviter = token_find_user(decoded_token)
    required_channel = find_channel(channel_id)

    invited_user = {}
    invited_user_dict = find_user(u_id)

    #
    invited_user['u_id'] = u_id
    invited_user['name_first'] = invited_user_dict['name_first']
    invited_user['name_last'] = invited_user_dict['name_last']
    invited_user['profile_img_url'] = invited_user_dict['profile_img_url']
    permission = invited_user_dict['permission_id']

    if not required_channel['is_public']:  # If channel is private
        # Find the u_id of the owner and ensure the u_id is a part of the owned members field
        is_owner = False
        for owned_member in required_channel['owner_members']:
            if owned_member['u_id'] == inviter[
                    'u_id']:  #if owner is found in owned_members
                is_owner = True

        if not is_owner:  # If the inviter is not an owner of the private channel
            raise error.AccessError(
                description="Inviter is not owner of private channel")
    else:  # if channel is public
        is_part_of_channel = False
        # Check if the user is part of the all_members in the channel
        for member in required_channel['all_members']:
            if member['u_id'] == inviter['u_id']:
                is_part_of_channel = True

        if not is_part_of_channel:
            raise error.AccessError(
                description="Inviter is not owner of public channel")

    # Check if user is in channel
    for member in required_channel['all_members']:
        if member['u_id'] == u_id:
            raise error.AccessError(
                description="Invited user is already part of channel")

    required_channel['all_members'].append(invited_user)
    if permission == 1:
        required_channel['owner_members'].append(invited_user)
    return
示例#7
0
def standup_send(token, channel_id, message):

    # check for valid token
    caller = check_token(token)

    # check valid channel
    target_channel = find_channel(channel_id)

    # check if user is in channel
    is_member = is_member_check(caller['u_id'], target_channel)
    if not is_member:
        raise error.AccessError('You are not part of the channel')

    # check the message length for issues
    if len(message) > 1000 or len(message) < 1 or len(message.strip()) < 1:
        raise error.InputError(
            'Invalid message. Please shorten to less than 1000 characters.')

    # check for active standup
    standup = standup_active(token, channel_id)
    if standup['is_active'] is False:
        raise error.InputError("There is already an active standup in channel")

    # throw error if message is user trying to start standup
    if message.startswith('/standup'):
        raise error.InputError("There is already an active standup in channel")

    # update standup with message and user's details
    target_channel['standup']['standup_messages'].append(caller['name_first'] +
                                                         ': ' + message)
    return {}
示例#8
0
def standup_start(token, channel_id, length):
    # Check that the token is valid
    caller = check_token(token)

    # Find the channel
    target_channel = find_channel(channel_id)

    # Check to see if caller is part of that channe
    is_member = is_member_check(caller['u_id'], target_channel)
    if not is_member:
        raise error.AccessError('You are not part of the channel')

    # check for active standup
    standup = standup_active(token, channel_id)
    if standup['is_active'] is True:
        raise error.InputError("There is already an active standup in channel")

    # finds current time and calculates when standup finishes
    start_time = round(time.time())
    end_time = start_time + length

    # sets values on target_channel to indicate standup occuring
    target_channel['standup']['is_standup'] = True
    target_channel['standup']['time_finish'] = end_time
    target_channel['standup']['standup_messages'] = []

    # make new thread
    threading.Thread(target=end_standup,
                     args=(target_channel, token, length)).start()

    return {'time_finish': end_time}
示例#9
0
def user_profile_setname(token, name_first, name_last):
    '''
    Updates the authorised user's first and last name.
    '''

    # Checking is the token exist then getting their u_id
    if helper_functions.check_token(token).get('token_status'):
        raise error.AccessError(description="Token invalid")

    user_id = helper_functions.check_token(token).get('u_id')

    #If first_name is not 1 < first_name < 50
    if (len(name_first) < 1) or (len(name_first) > 50):
        raise error.InputError(
            "First name invalid, needs to be between 1 and 50 characters")

    #If last_name is not 1 < last_name < 50
    if (len(name_last) < 1) or (len(name_last) > 50):
        raise error.InputError(
            "Last name invalid, needs to be between 1 and 50 characters")

    # new value for keys to update name
    new_name = {'first_name': name_first, 'last_name': name_last}

    # loops through users in list
    for users in auth.registered_users:
        if users['u_id'] == user_id:
            # gets rid of existing value and replaces it with new value
            users.update(new_name)
            break

    return {}
示例#10
0
def standup_start(token, channel_id, length):
    '''
    Begin the standup
    '''
    # Checking is the token exist then getting their u_id
    if helper_functions.check_token(token).get('token_status'):
        raise error.AccessError(description="Token invalid")

    #If channel valid
    if helper_functions.check_channelid_valid(channel_id):
        raise error.InputError(description="Channel_id invalid")

    #If startup is active in channel
    if standup_active(token, channel_id)['is_active'] == True:
        raise error.InputError(description="Startup is currently active")

    #Get the time it will end
    dt_finish = datetime.now() + timedelta(seconds=length)
    time_finish = dt_finish.timestamp()

    #Append startup to STANDUPS
    STANDUPS.append({
        'channel_id': channel_id,
        'time_finish': int(time_finish)
    })

    #Append to CHANNELMSGS
    CHANNELSMSG[channel_id] = []

    t = threading.Timer(int(length),
                        helper_send_message,
                        args=[token, channel_id])
    t.start()

    return {'time_finish': int(time_finish)}
def standup_send(token, channel_id, message):
    """ Add a message to standup queue """

    # If token is valid, take u_id which is used to look through users
    u_id = database.get_current_user(token)

    # Check if user is member of channel that message is within
    # if not then raise an AccessError
    channel_data = database.get_channel_data(channel_id)
    if u_id not in channel_data['member_ids']:
        raise error.AccessError(
            description="You are not a member of this channel")

    # Check if message if more than 1000 characters long and raise InputError if that is the case
    if len(message) > 1000:
        raise error.InputError(
            description="The message entered is more than 1000 characters long"
        )

    # Check if standup is currently active in channel, raise InputError if not
    if standup_active(token, channel_id)['is_active'] is False:
        raise error.InputError(
            description="There are no standups active in this channel")

    # Format message to "handle_str: message"
    handle_str = database.get_user_data(u_id)['handle_str']
    string = handle_str + ": " + message

    # Now add string to the appropriate list in queues
    QUEUES[str(channel_id)].append(string)

    return {}
示例#12
0
def standup_send(token, channel_id, message):
    '''
    Send message in standup
    '''
    # Checking is the token exist
    if helper_functions.check_token(token).get('token_status'):
        raise error.AccessError(description="Token invalid")

    u_id = helper_functions.check_token(token).get('u_id')

    #If channel valid
    if helper_functions.check_channelid_valid(channel_id):
        raise error.InputError(description="Channel_id invalid")

    #If startup is active in channel
    if standup_active(token, channel_id)['is_active'] == False:
        raise error.InputError(description="Startup is not currently active")

    #If message is more than 1000 characters
    if len(message) > 1000:
        raise error.InputError(description="Message length too long")

    #Make a new message
    for user in auth.registered_users:
        if user['u_id'] == u_id:
            handle_str = user['handle']
            break

    string = str(handle_str) + ": " + str(message)

    #Append message to CHANNELSMSG
    CHANNELSMSG[channel_id].append(string)
    return {}
示例#13
0
def message_sendlater(token, channel_id, message, time_sent):
    # Check that the token is valid
    caller = check_token(token)

    # Capture the current time asap
    current_time = (datetime.datetime.now()).timestamp()

    # Find the channel
    target_channel = find_channel(channel_id)

    # Check to see if caller is part of that channel
    is_member = is_member_check(caller['u_id'], target_channel)
    # Access Error if the person inviting is not within the server
    if not is_member:
        raise error.AccessError(
            'You are not part of the channel you want to send messages to')

    # Check the message length for issues
    if len(message) > 1000 or len(message) < 1 or len(message.strip()) < 1:
        raise error.InputError(
            'The message you are sending is over 1000 characters')

    # Check the time is not from before current
    if (time_sent - current_time) < 0:
        raise error.InputError('Trying to send message in the past')

    delay = time_sent - current_time
    threading.Timer(delay,
                    send_message,
                    kwargs={
                        'caller': caller,
                        'message': message,
                        'target_channel': target_channel,
                        'channel_id': channel_id
                    }).start()
示例#14
0
    def wrapper_func(*args, **kwargs):
        """ Wrapper function """
        try:
            email_arg_index = argspec.args.index("email")
            email = args[email_arg_index]

            # Try to grab this users ID. If the user doesnt exist, create a warning
            # and run the function without checking the permission_id.
            try:
                target_u_id = next(u['u_id'] for u in database.get_users()
                                   if u['email'] == email)
                target_perm_id = database.get_permission_dict(target_u_id).get(
                    'permission_id')
                if target_perm_id == 66:
                    raise error.AccessError(
                        description="The account registered to this email has"
                        + " been removed from the slakr. " +
                        "[I'm sorry Dave, I'm afraid I can't do that]")
                else:
                    return func(*args, **kwargs)
            except StopIteration:
                print(
                    "\033[93m" +
                    "WARNING: This email was not found  - running function " +
                    f"{func.__name__} without permission_id check." +
                    "\033[0m")
                return func(*args, **kwargs)

        except ValueError:
            print("\033[93m" +
                  "WARNING: email arg not found - running function " +
                  f"{func.__name__} without email check." + "\033[0m")
            return func(*args, **kwargs)
def auth_login(email, password):
    """ Login user with given email and password. """

    # Check if email entered belongs to a user
    password_data = database.get_password_data(email)
    if password_data is None:
        raise error.InputError(
            description="The email you entered is incorrect")

    # Hash the password and see if it matches the hashed passowrd in the database
    passcode = hashlib.sha256(password.encode()).hexdigest()

    # Check if password matches email
    if password_data['password'] != passcode:
        raise error.InputError(
            description="The password you entered is incorrect")

    # find user's u_id from email given
    u_id = 0
    for user in database.get_users():
        if user['email'] == email:
            u_id = user['u_id']

    # Check if already logged in.
    if database.get_token_from_user(u_id) is not None:
        raise error.AccessError(
            description="Cannot login when already logged in!")

    # Generate a token
    payload = {'u_id': u_id}
    token = str(jwt.encode(payload, 'jwt_secret', algorithm='HS256'))

    dictionary = {'u_id': u_id, 'token': token}
    database.set_current_user(u_id, token)
    return dictionary
示例#16
0
def channel_addowner(token, channel_id, u_id):
    '''
    When a user is added as an owner to the channel.
    '''

    #Checked invalid channel
    if helper_functions.check_channelid_valid(channel_id):
        raise error.InputError("Channel not valid")

    # user token is invalid
    if helper_functions.check_token(token).get('token_status'):
        raise error.InputError(description="Token invalid")

    u_id_for_token = helper_functions.check_token(token).get("u_id")

    #Check if they are an owner
    if helper_functions.check_uid_owner_in_channel(u_id_for_token, channel_id):
        raise error.AccessError(
            "Authorised user not in channel or flockr owner")

    #If u_id already owner
    if helper_functions.check_uid_owner_in_channel(u_id, channel_id) == False:
        raise error.InputError("u_id already owner")

    #Append u_id to list of owners
    for user in channels.channel_data:
        if user.get("channel_id") == channel_id:
            user.get("owner_ids").append(u_id)
            break

    return {}
示例#17
0
def channel_join(token, channel_id):
    channel_id = int(channel_id)
    decoded_jwt = jwt.decode(token.encode('utf-8'),
                             data.secret,
                             algorithms=['HS256'])
    decoded_token = decoded_jwt['token']
    # checks if the channel exists and is public
    check = 0
    for channel in data.channels:
        if channel['channel_id'] == channel_id:
            if not channel['is_public']:
                raise error.AccessError(description="Channel is not public")
            check = 1
            break
    if check != 1:
        raise error.InputError(description="channel id is invalid")
    # adds user to channel_members
    user_data = {}
    permission = 0
    for user in data.users:
        if user['token'] == decoded_token:
            user_data['u_id'] = user['u_id']
            user_data['name_first'] = user['name_first']
            user_data['name_last'] = user['name_last']
            user_data['profile_img_url'] = user['profile_img_url']
            permission = user['permission_id']

    channel['all_members'].append(user_data)
    if permission == 1:
        channel['owner_members'].append(user_data)

    return
示例#18
0
def user_profile_sethandle(token, handle_str):
    '''
    Update the authorised user's handle.
    '''
    #Check if token valid and get u_id
    if helper_functions.check_token(token).get('token_status'):
        raise error.AccessError(description="Token invalid")

    u_id = helper_functions.check_token(token).get('u_id')

    #If handle_str valid
    if len(handle_str) < 3 or len(handle_str) > 20:
        raise error.InputError(description="Handle_str invalid")

    #If handle_str already being used
    for item in auth.registered_users:
        if item.get("handle") == handle_str:
            raise error.InputError(description="Handle_str being used")

    #Update handle_str
    for item in auth.registered_users:
        if item.get("u_id") == u_id:
            item["handle"] = handle_str
            break

    return {}
示例#19
0
def message_remove(token, message_id):
    # Check that the token is valid
    caller = check_token(token)

    # Find the message in the message field of data
    target_message = find_message_in_messages(message_id)

    # Find the channel the message is in
    target_channel = find_channel(target_message['channel_id'])

    # Check to see if the caller has the right to remove the message
    is_allowed = False
    # 1) Caller u_id == target_message u_id
    if caller['u_id'] == target_message['u_id']:
        is_allowed = True

    # 2) Caller is channel owner
    if not is_allowed:
        is_allowed = is_owner_check(caller['u_id'], target_channel)

    # 3) Caller is flockr owner
    if not is_allowed:
        if caller['permission_id'] == 1:
            is_allowed = True

    # If permission is found then remove the message, else access error
    if is_allowed:
        for i, message in enumerate(target_channel['messages']):
            if message['message_id'] == target_message['message_id']:
                del target_channel['messages'][i]
        for i, message in enumerate(data['messages']):
            if message_id == message['message_id']:
                del data['messages'][i]
        return {}
    raise error.AccessError('You are not allowed to remove the message')
示例#20
0
def channel_leave(token, channel_id):
    '''
    When a user leaves the channel.
    '''
    # user token is invalid
    if helper_functions.check_token(token).get('token_status'):
        raise error.InputError(description="Token invalid")

    user_id = helper_functions.check_token(token).get("u_id")

    #Checked invalid channel
    if helper_functions.check_channelid_valid(channel_id):
        raise error.InputError("Channel not valid")

    #User already in channel
    if helper_functions.check_u_id_in_channel(user_id, channel_id):
        raise error.AccessError("Already in channel")

    for current_channel in channels.channel_data:
        if current_channel.get("channel_id") == channel_id:
            for members in current_channel.get("member_ids"):
                if user_id == members:
                    current_channel["member_ids"].remove(user_id)
                    break
            break

    return {}
示例#21
0
def message_unpin(token, message_id):
    # check input error 
    #   message_id invalid:

    #Invalid token test
    if helper_functions.check_token(token).get('token_status'):
        raise error.AccessError(description="Token invalid")
    user_id = helper_functions.check_token(token).get('u_id')

    channel_id = ""
    invalid_msg_id = True
    for data in channels.channel_data:
        for msg in data['messages']:
            if msg.get('message_id') == message_id:
                channel_id = int(data.get('channel_id'))
                invalid_msg_id = False
                break

    if invalid_msg_id:
        raise error.InputError("You have entered an invalid message ID")
          
    # check access error
    #   not member of channel
    user_id = ""
    for user in auth.registered_tokens:
        if user.get("token") == token:
            user_id = int(user.get('u_id'))
            break

    #   not owner / flockr owner
    for channel_datas in channels.channel_data:
        if channel_datas.get("channel_id") == channel_id:
            if user_id not in channel_datas['owner_ids']:
                raise error.AccessError("You are not in this channel / not an owner")
            else: 
                break

    # message already pinned? if not, pin.
    for data in channels.channel_data:
        for message_data in data.get('messages'):
            if message_data.get("message_id") == message_id:
                if message_data.get("is_pinned") == False:
                    raise error.InputError("This message is already unpinned")
                else:
                    message_data['is_pinned'] = False
          
    return {}
示例#22
0
def channel_messages(token, channel_id, start):
    # Check that the token is valid
    caller = check_token(token)

    # Find the channel
    target_channel = find_channel(channel_id)

    # Check to see if calling is part of that channel
    is_member = is_member_check(caller['u_id'], target_channel)
    # Access Error if the person inviting is not within the server
    if not is_member:
        raise error.AccessError(
            'You are not part of the channel you want details about')

    # Made it through all checks so now we start building the return
    # Looping through the message data of the channel
    message_data = []
    number_of_messages = len(target_channel['messages'])
    message_number = start
    end = 0
    # Check if start is beyond range of messages
    if start > number_of_messages:
        raise error.InputError(
            'The start value entered is older than all messages')
    # Check to see if start is the least recent message
    elif start == (number_of_messages - 1):
        message = target_channel['messages'][start]

        if len(message['reacts']) > 0:
            for reacts in message['reacts']:
                reacts['is_this_user_reacted'] = False
                for u_id in reacts['u_ids']:
                    if u_id == caller['u_id']:
                        reacts['is_this_user_reacted'] = True
        message_data.append(message)
        return {
            'messages': message_data,
            'start': start,
            'end': -1,
        }
    # We can iterate from start until either end or start + 50
    else:
        while (message_number < number_of_messages) and (end <= start + 49):
            message = target_channel['messages'][message_number]

            if len(message['reacts']) > 0:
                for reacts in message['reacts']:
                    reacts['is_this_user_reacted'] = False
                    for u_id in reacts['u_ids']:
                        if u_id == caller['u_id']:
                            reacts['is_this_user_reacted'] = True
            message_data.append(message)
            message_number += 1
            end += 1
        return {
            'messages': message_data,
            'start': start,
            'end': end,
        }
示例#23
0
def channel_details(token, channel_id):
    '''
    Presenting the details of the channel.
    '''
    #Checked invalid channel
    if helper_functions.check_channelid_valid(channel_id):
        raise error.InputError("Channel not valid")

    # user token is invalid
    if helper_functions.check_token(token).get('token_status'):
        raise error.InputError(description="Token invalid")

    user_id = helper_functions.check_token(token).get('u_id')

    #User already in channel
    if helper_functions.check_u_id_in_channel(user_id, channel_id):
        raise error.AccessError("Not in channel")

    #return details about channel
    channel_detail = {
        'name': 'name',
        'owner_members': [],
        'all_members': [],
    }

    for curr_channels in channels.list_of_all_channels:
        if curr_channels.get('channel_id') == channel_id:
            channel_detail['name'] = curr_channels['name']
            break

    for curr_channels in channels.channel_data:
        if curr_channels.get('channel_id') == channel_id:
            user_ids = curr_channels.get("member_ids")
            for user in user_ids:
                for user_detail in auth.registered_users:
                    if user_detail['u_id'] == user:
                        member_details = {
                            'u_id': user,
                            'name_first': user_detail['first_name'],
                            'name_last': user_detail['last_name'],
                            'profile_img_url': user_detail['profile_img_url'],
                        }
                        channel_detail['all_members'].append(member_details)

    for curr_channels in channels.channel_data:
        if curr_channels.get('channel_id') == channel_id:
            user_ids = curr_channels.get("owner_ids")
            for user in user_ids:
                for user_detail in auth.registered_users:
                    if user_detail['u_id'] == user:
                        owner_details = {
                            'u_id': user,
                            'name_first': user_detail['first_name'],
                            'name_last': user_detail['last_name'],
                            'profile_img_url': user_detail['profile_img_url'],
                        }
                        channel_detail['owner_members'].append(owner_details)

    return channel_detail
示例#24
0
def check_token(token):

    # Searches for a logged in user through a token
    for user in data['users']:
        if user['token'] == token:  # get() returns a value for the given key (token)
            return user

    # If the token doesn't exist user isn't logged in
    raise error.AccessError("Token is not valid")
示例#25
0
def admin_userpermission_change(token, u_id, permission_id):
    '''
    Changes the permissions of the u_id entered.
    '''
    #If permission_id invalid
    if permission_id < 1 or permission_id > 2:
        raise error.InputError(description="permission_id invalid")

    # check for valid user:
    # Checking is the token exist then getting their u_id
    if helper_functions.check_token(token).get('token_status'):
        raise error.AccessError(description="Token invalid")

    token_uid = helper_functions.check_token(token).get('u_id')

    #If u_id valid
    if helper_functions.check_uid_valid(u_id):
        raise error.InputError(description="Invalid u_id")

    #If token is not owner
    not_owner = True
    for user in auth.registered_users:
        if user.get("u_id") == token_uid:
            if user.get("permissions") == 1:
                not_owner = False
                break

    if not_owner:
        raise error.AccessError("Authorised user is not owner")

    #Update u_id permissions
    for user in auth.registered_users:
        if user.get("u_id") == u_id:
            user["permissions"] = permission_id
            break

    #If member in channel also add to owner
    if permission_id == 1:
        for data in channels.channel_data:
            if u_id in data.get('member_ids'):
                if u_id not in data.get('owner_ids'):
                    data.get('owner_ids').append(u_id)

    return {}
示例#26
0
def channel_removeowner(token, channel_id, u_id):
    """
    This function intakes the token of current authorised (auth) user, channel_id and a user u_id
    It then removes the user u_id as an owner of the channel,
    as long as the current auth user is an owner of slackr/channel
    and the user u_id is an owner
    """
    # Check if token is valid and raise AccessError if not
    curr_id = database.get_current_user(token)
    # gets current channel data
    curr_channel = database.get_channel_data(channel_id)
    # gets the permissions of current user from database
    user_perms = database.get_permission_dict(curr_id)

    u_id_permission = database.get_permission_dict(u_id)
    if u_id_permission["permission_id"] == 1:
        raise error.AccessError(description="user being removed is the owner of the slackr")

    # checks if u_id is not an owner of the channel
    # also checks if current auth user is an owner of the channel
    is_u_owner = False
    is_curr_owner = False
    for owner_id in curr_channel["owner_ids"]:
        if u_id == owner_id:
            is_u_owner = True
        if curr_id == owner_id:
            is_curr_owner = True
    if is_u_owner is False:
        raise error.InputError(description="user being removed is not an owner of the channel")


    # if the auth user is owner of slackr, allows him to remove u_id as owner
    if user_perms["permission_id"] == 1:
        # removes the user from channel_owner
        curr_channel["owner_ids"].remove(u_id)
    # if the auth user is an owner of the channel, allow him to remove u_id as owner of channel
    elif is_curr_owner is True:
        # adds the user into channel_owner
        curr_channel["owner_ids"].remove(u_id)
    # else the auth user is not an owner and thus cannot use addowner
    else:
        raise error.AccessError(description="""Authorised user user is not an owner of the channel,
                                or of the slackr""")
示例#27
0
文件: other.py 项目: joey101/python
def admin_userpermission_change(token, u_id, permission_id):
    '''
    This function sets the permissions of the given user:
    permission_id 1: owner
    permission_id 2: member
    '''
    decoded_jwt = jwt.decode(token.encode('utf-8'), data.secret, algorithms=['HS256'])
    decoded_token = decoded_jwt['token']
    u_id = int(u_id)
    permission_id = int(permission_id)
    current_user = {}
    # Search for the user and get their permissions
    for user in data.users:
        if decoded_token == user['token']:
            current_user['u_id'] = user['u_id']
            current_user['permission_id'] = user['permission_id']

    # Check if the users using this function has the correct
    # permissions
    if current_user['permission_id'] != 1:
        raise error.AccessError('You do not have owner permissions')

    # Obtain the data needed to change the specified user's
    # permissions
    user_edited = {}
    member_found = False
    for user in data.users:
        if user['u_id'] == u_id:
            member_found = True
            if permission_id not in (1, 2):
                raise error.InputError
           
            user['permission_id'] = permission_id

            user_edited['name_first'] = user['name_first']
            user_edited['name_last'] = user['name_last']
            user_edited['u_id'] = user['u_id']
            user_edited['profile_img_url'] = user['profile_img_url']
        
    if not member_found:
        raise error.InputError('User with requested u_id not found')

    # Sets the user's status in the channels to owner_member in the channels they are in
    if permission_id == 1:
        for channel in data.channels:
            if user_edited not in channel['owner_members'] and user_edited in channel['all_members']:
                channel['owner_members'].append(user_edited)
    else:
        # Revoke's the user's onwer_member status for the channels they are in
        for channel in data.channels:
            if user_edited in channel['owner_members']:
                channel['owner_members'].remove(user_edited)   
示例#28
0
def message_edit(token, message_id, message):
    '''
    Given a message id and user token edit the message.
    '''
    #Token invalid check
    if helper_functions.check_token(token).get('token_status'):
        raise error.AccessError(description="Token invalid")
    user_id = helper_functions.check_token(token).get('u_id')

    # Error message too long
    if len(message) > 1000:
        raise error.InputError("You have message longer than 1000 words")

    invalid_messages_id = True

    # Testing if the message id is valid
    for data in channels.channel_data:
        for msg in data['messages']:
            if msg.get('message_id') == message_id:
                channel_id = data.get("channel_id")
                invalid_messages_id = False
    
    # Raising the error
    if invalid_messages_id:
        raise error.InputError("You have entered an invalid message id")


    # Editing the message
    for data in channels.channel_data:
        for message_data in data.get('messages'):
            if message_data.get("message_id") == message_id:
                #check if owner
                if helper_functions.check_uid_owner_in_channel(user_id, channel_id):
                        if message_data.get('user_id') != user_id:
                            raise error.AccessError("Not an owner or not user who sent msg")
                    
                message_data['message_sent'] = message
                break
    return {}
示例#29
0
def message_remove(token, message_id):
    '''
    Removing a message that is requested by the user.
    '''
    #If token invalid
    if helper_functions.check_token(token).get('token_status'):
        raise error.AccessError(description="Token invalid")
    user_id = helper_functions.check_token(token).get('u_id')

    # Checking if message ID is valid
    invalid_m_id = True
    for data in channels.channel_data:
        for msg in data['messages']:
            if msg.get('message_id') == message_id:
                channel_id = data.get('channel_id')
                invalid_m_id = False
                break

    if invalid_m_id:
        raise error.InputError("You have entered an invalid message ID")
    
    
    #Check if message is from the authorised user
    # Go inside message to check if message_id is the same in order to remove the message
    # Return error if message no longer existing
    for data in channels.channel_data:
        for message_data in data.get('messages'):
            if message_data.get('message_id') == message_id:
                #check if owner
                if helper_functions.check_uid_owner_in_channel(user_id, channel_id):
                        if message_data.get('user_id') != user_id:
                            raise error.AccessError("Not an owner or not user who sent msg")

                if msg['message_sent'] == None: 
                    raise error.InputError("Message no longer exists")
                else:
                    data.get('messages').remove(message_data)
                break
    return {}
示例#30
0
def search(token, query_str):
    '''
    Searches all channel messages and uses regex to find similar messages.
    '''
    # Checking is the token exist then getting their u_id
    if helper_functions.check_token(token).get('token_status'):
        raise error.AccessError(description="Token invalid")

    u_id = helper_functions.check_token(token).get('u_id')

    messages = []

    #return dictionary of details of query string
    for chan in channels.channel_data:
        for user in chan.get("member_ids"):
            if user == u_id:
                for line in chan.get("messages"):
                    if line.get('message_sent') is None:
                        break

                    #Seeing if user has reacted
                    is_this_user_reacted = False

                    if u_id in line.get('reacts')[0]['u_ids']:
                        is_this_user_reacted = True

                    if re.search(str(query_str), line.get('message_sent')):
                        msg = {
                            'message_id':
                            line.get('message_id'),
                            'u_id':
                            line.get('user_id'),
                            'message':
                            line.get('message_sent'),
                            'time_created':
                            line.get('time_created'),
                            'reacts': [{
                                'react_id':
                                line.get('reacts')[0].get('react_id'),
                                'u_ids':
                                line.get('reacts')[0].get('u_ids'),
                                'is_this_user_reacted':
                                is_this_user_reacted,
                            }],
                            'is_pinned':
                            line.get('is_pinned'),
                        }

                        messages.append(msg)

    return {'messages': messages}