def channels_listall(token): '''List all channels of server''' database = db.load_DB() if not Token.isValid(token): raise AccessError('Invalid Token') return dumps({'channels': [channel for channel in database['channels']]})
def admin_userpermission_change(token, u_id, permission_id): '''Change a users permissions''' u_id = int(u_id) permission_id = int(permission_id) if not Token.isValid(token): raise AccessError("Not a valid token!") data = db.load_DB() token_permission_id = db.get_from_token('permission_id', token, data) all_uids = [user['u_id'] for user in data['users']] if not u_id in all_uids: raise ValueError("u_id does not refer to a valid user") if permission_id not in [1, 2, 3]: raise ValueError("Permission_id does not refer to a valid permission") if token_permission_id not in [1, 2]: raise AccessError("The authorised user is not an admin or owner") for user in data['users']: if u_id == user['u_id']: user['permission_id'] = permission_id db.save_DB(data) return dumps({})
def channel_addowner(token, channel_id, u_id): '''Add ownership rights to a user of a channel''' if not Token.isValid(token): raise AccessError("Not a valid token!") channel_id = int(channel_id) u_id = int(u_id) database = db.load_DB() if channel_id not in db.get_all_channels(database): raise ValueError('Channel (based on ID) does not exist') for channel in database['channels']: if channel['channel_id'] == channel_id: if u_id in channel['owner_members']: raise ValueError('User already owner of this channel') if db.get_from_token('u_id', token, database) not in\ channel['owner_members'] and \ db.get_from_token('permission_id', token, database) == 3: raise AccessError('authorised user is not an owner of \ the slackr, or an owner of this channel') channel['owner_members'].append(u_id) db.save_DB(database) return {}
def message_edit(token, message_id, message): '''Edit a message''' if not Token.isValid(token): raise AccessError("Not a valid token!") data = db.load_DB() message_id = int(message_id) if message_id not in db.get_all_messages(data): raise ValueError('Message doesnt exist') u_id = db.get_from_token('u_id', token, data) cur_message = [msg for msg in data['messages'] if msg['message_id'] == message_id][0] channel = [channel for channel in data['channels'] if channel['channel_id'] ==\ cur_message['in_channel']][0] if u_id != cur_message['u_id'] and db.get_from_token('permission_id', token, data) == 3 and\ u_id not in channel['owner_members']: raise AccessError('The authorised user is an admin or owner of this channel or the slackr') if message == "": data['messages'].remove(cur_message) else: cur_message['message'] = message data['messages'].remove(cur_message) data['messages'].append(cur_message) db.save_DB(data) return dumps({})
def user_profile_setemail(token, email): '''Change a user profile's email''' if not Token.isValid(token): raise AccessError("Not a valid token!") database = db.load_DB() u_id = db.get_from_token('u_id', token, database) if database['users']: all_emails = [user['email'] for user in database['users']] else: all_emails = [] if not db.check_mail(email): raise ValueError('Email entered is not a valid email') if email in all_emails: raise ValueError('Email address is already being used by another user') for user in database['users']: if u_id == user['u_id']: user['email'] = email db.save_DB(database) return {}
def channel_invite(token, channel_id, u_id): '''Adds existing user to a new channel''' channel_id = int(channel_id) u_id = int(u_id) # Raise error if invalid token if not Token.isValid(token): raise AccessError('Invalid Token.') database = db.load_DB() # Check if valid channel_id if channel_id not in db.get_all_channels(database): raise ValueError('Invalid Channel ID.') # Check if authorised user is a member of the channel channel = db.get_channel_by_id(database, channel_id) if not db.get_from_token('u_id', token, database) in channel['members']: raise AccessError('You are not a member of this channel so \ you cannot invite others to join.') # Check if valid user ID for user to be adde if u_id not in db.get_all_users(database): raise AccessError('Invalid user id.') if u_id in channel['members']: raise AccessError('User already part of the channel') database['channels'].remove(channel) channel['members'].append(u_id) database['channels'].append(channel) db.save_DB(database) return dumps({})
def message_pin(token, message_id): '''Pin existing message in a channel''' if not Token.isValid(token): raise AccessError("Not a valid token!") message_id = int(message_id) database = db.load_DB() permission_id = db.get_from_token('permission_id', token, database) #true or false #loop through database for message ID if message_id not in db.get_all_messages(database): raise ValueError('message_id is not a valid message') #check admin of user if permission_id not in [1, 2]: raise ValueError('The authorised user is not an admin') #check if message_id is pinned for message in database['messages']: if message['message_id'] == message_id: if message['is_pinned']: raise ValueError('Message is already pinned') message['is_pinned'] = True db.save_DB(database) return dumps({})
def channels_list(token): '''List all the channels of a certain user''' database = db.load_DB() u_id = db.get_from_token('u_id', token, database) return dumps({'channels': [channel for channel in database['channels'] \ if u_id in channel['members']]})
def message_unreact(token, message_id, react_id): '''Remove react from message''' if not Token.isValid(token): raise AccessError("Not a valid token!") if not message_id: raise ValueError('Invalid message_id') if react_id != '1': raise ValueError('Invalid react id') message_id = int(message_id) react_id = int(react_id) data = db.load_DB() u_id = db.get_from_token('u_id', token, data) if message_id not in db.get_all_messages(data): raise ValueError('Invalid message_id') reactusers = db.get_react_users(data, u_id, message_id, react_id, False) if u_id not in reactusers: raise AccessError('Message with ID message_id does not contain\ an active React with ID react_id') cur_message = [ msg for msg in data['messages'] if msg['message_id'] == message_id ][0] for react in cur_message['reacts']: if react['react_id'] == react_id: react['u_ids'].remove(u_id) db.save_DB(data) return dumps({})
def auth_passwordreset_reset(reset_code, new_password, testing=False): '''Reset a users password to a new password''' reset_code = int(reset_code) data = db.load_DB() if len(new_password) < 6: raise ValueError('Password entered is not a valid password.') valid = False for user in data['users']: if 'psw_code' in user.keys(): if user['psw_code'] == reset_code: cur_user = user valid = True break if testing: return dumps({}) if not valid: raise ValueError('Reset Code is not a valid reset code.') cur_user["password"] = db.hash_password(new_password) db.save_DB(data) return dumps({})
def user_profile_sethandle(token, handle_str): '''Change a user profile's handle''' if not Token.isValid(token): raise AccessError("Not a valid token!") database = db.load_DB() u_id = db.get_from_token('u_id', token, database) users = database['users'] if len(handle_str) > 20 or len(handle_str) < 3: raise ValueError('handle_str must be between 3 and 20 characters') #check if handle_str is already used if users: all_handle = [user['handle_str'] for user in users] else: all_handle = [] if handle_str in all_handle: raise ValueError('handle is already used by another user') for user in database['users']: if u_id == user['u_id']: user['handle_str'] = handle_str db.save_DB(database) return {}
def message_sendlater(token, channel_id, message, time_sent, testing=False): '''Send a message at a later point in time''' if not Token.isValid(token): raise AccessError("Not a valid token!") database = db.load_DB() channel_id = int(channel_id) time_sent = float(time_sent) all_channel_ids = [channel['channel_id'] for channel in database['channels'] if \ channel_id == channel['channel_id']] if channel_id not in all_channel_ids: raise ValueError('Channel ID is not a valid channel') if len(message) > 1000: raise ValueError('Message is greater than 1000') if time_sent < datetime.now().timestamp(): raise ValueError('Time sent is a time in the past') length = time_sent - datetime.now().timestamp() timer = Timer(length, message_send, args=(token, channel_id, message, testing)) timer.start() return dumps({})
def channel_removeowner(token, channel_id, u_id): '''Remove ownership rights from user of a channel''' if not Token.isValid(token): raise AccessError("Not a valid token!") channel_id = int(channel_id) u_id = int(u_id) database = db.load_DB() if channel_id not in db.get_all_channels(database): raise ValueError('Channel (based on ID) does not exist') tok_u_id = db.get_from_token('u_id', token, database) channel = db.get_channel_by_id(database, channel_id) user = [user for user in database['users'] if user['u_id'] == tok_u_id][0] for channel in database['channels']: if channel['channel_id'] == channel_id: if u_id not in channel['owner_members']: raise ValueError('User not owner of this channel') if tok_u_id not in channel['owner_members'] and \ db.get_from_token('permission_id', token, database) == 3: raise AccessError('authorised user is not\ an owner of the slackr, or an owner of this channel') channel['owner_members'].remove(u_id) db.save_DB(database) return {}
def message_send(token, channel_id, message, testing=False): '''Send message to a channel''' if testing: return dumps({'message_id': 1}) if not Token.isValid(token): raise AccessError("Not a valid token!") channel_id = int(channel_id) data = db.load_DB() u_id = db.get_from_token('u_id', token, data) if len(message) > 1000: raise ValueError('Message cannot contain more than 1000 characters') channel = [ ch for ch in data['channels'] if ch['channel_id'] == channel_id ][0] if u_id not in channel['members']: raise AccessError( 'Authorised user is not a member of channel with channel_id') time = datetime.datetime.now() timestamp = time.replace(tzinfo=timezone.utc).timestamp() msg_id = db.new_message_id(data) data['messages'].append({'message_id' : msg_id, 'u_id' : u_id, 'message' : message, \ 'time_created' : timestamp, 'reacts' : [], 'is_pinned' : False, 'in_channel' : channel_id, \ 'is_unread' : True}) db.save_DB(data) return dumps({'message_id': msg_id})
def channel_join(token, channel_id): '''Join existing user to a new channel''' if not Token.isValid(token): raise AccessError("Not a valid token!") channel_id = int(channel_id) database = db.load_DB() u_id = db.get_from_token('u_id', token, database) if channel_id not in db.get_all_channels(database): raise ValueError('Channel (based on ID) does not exist') channel = db.get_channel_by_id(database, channel_id) if not channel['is_public']: if db.get_from_token('permission_id', token, database) not in [1, 2]: raise AccessError('channel_id refers to a channel that is private \ (when the authorised user is not an admin)') for channel in database['channels']: if channel['channel_id'] == channel_id: if not u_id in channel['members']: channel['members'].append(u_id) db.save_DB(database) return {}
def removeToken(token): data = db.load_DB() email = db.get_from_token('email', token, data) for user in data['users']: if user['email'] == email: user['tokens'].remove(token) db.save_DB(data)
def test_user_profile_validUser(): db.reset_DB() data = db.load_DB() auth_register('*****@*****.**', 'pas123456', 'Bob', 'Smith') token = Token.generateToken('*****@*****.**') u_id = db.new_u_id(data) user_profile_sethandle(token, 'Baggins') assert (user_profile(token, u_id) != {})
def user_profile(token, u_id): '''Get user profile details''' if not Token.isValid(token): raise ValueError("Not a valid token!") data = db.load_DB() user = [user for user in data['users'] if user['u_id'] == int(u_id)][0] return dumps(user)
def users_all(token): '''Get a list of all users on the server''' data = db.load_DB() users = data['users'] if not Token.isValid(token): raise AccessError("Not a valid token!") return dumps({'users': users})
def channel_messages(token, channel_id, start): '''Load and return all messages from a channel''' if not Token.isValid(token): raise AccessError("Not a valid token!") database = db.load_DB() channel_id = int(channel_id) start = int(start) if channel_id not in db.get_all_channels(database): raise ValueError('Channel ID is not a valid channel') if database['messages']: if int(start) > len([message for message in database['messages'] \ if message['in_channel'] == channel_id]): raise ValueError('start is greater than or equal to the total\ number of messages in the channel') u_id = db.get_from_token("u_id", token, database) if database['messages']: messages = [ msg for msg in database['messages'] if msg['in_channel'] == channel_id ] messages = sorted(messages, key=itemgetter('time_created'), reverse=True) end = start + 50 fmessages = [] for message in messages: d = {} d['message_id'] = message['message_id'] d['u_id'] = message['u_id'] d['message'] = message['message'] d['time_created'] = message['time_created'] d['is_pinned'] = message['is_pinned'] reacts = [] for react in message['reacts']: d2 = {} d2['react_id'] = react['react_id'] d2['u_ids'] = react['u_ids'] d2['is_this_user_reacted'] = db.get_user_reacted(database, \ u_id, message['message_id'], react['react_id']) reacts.append(d2) d['reacts'] = reacts fmessages.append(d) if len(messages) < 50: end = -1 else: fmessages = [] end = -1 return dumps({'messages': fmessages, 'start': start, 'end': end})
def isValid(token): try: decoded = decodeToken(token) if decoded: tokens = db.get_from_token('tokens', token, db.load_DB()) # print("tokens in db:", tokens) # print("token given", token) if token in tokens: return True except: return False
def generateToken(email): newtoken = jwt.encode({'email' : email, 'timestamp': datetime.datetime.now().timestamp()}, get_secret(), algorithm='HS256').decode('utf-8') data = db.load_DB() tokens = db.get_from_token('tokens', newtoken, data) tokens.append(newtoken) for user in data['users']: if user['email'] == email: user['tokens'] = tokens db.save_DB(data) return newtoken
def auth_passwordreset_request(email): '''Let a user request a password reset''' data = db.load_DB() allmails = [user['email'] for user in data['users']] if email in allmails: code = randint(999, 9999) for user in data['users']: if user['email'] == email: user['psw_code'] = code db.save_DB(data) return (True, code) return (False, 0000)
def search(token, query_str): '''Search all messages on server by keyword''' if not Token.isValid(token): raise AccessError('Invalid Token.') data = db.load_DB() u_id = db.get_from_token('u_id', token, data) channels = [ ch['channel_id'] for ch in data['channels'] if u_id in ch['members'] ] messages = [] for channel in channels: messages.extend([msg for msg in data['messages'] if msg['in_channel'] == \ channel if query_str in msg['message']]) return dumps({'messages': messages})
def user_profile_setname(token, name_first, name_last): '''Change a user profile's name''' if not Token.isValid(token): raise AccessError("Not a valid token!") database = db.load_DB() if len(name_first) > 50 or len(name_first) < 0: raise ValueError('Your First Name cannot be more than 50 characters.') if len(name_last) > 50 or len(name_last) < 0: raise ValueError('Your Last Name cannot be more than 50 characters.') u_id = db.get_from_token('u_id', token, database) for user in database['users']: if u_id == user['u_id']: user['name_first'] = name_first user['name_last'] = name_last db.save_DB(database) return {}
def channel_leave(token, channel_id): '''Remove existing user from a channel''' if not Token.isValid(token): raise AccessError("Not a valid token!") channel_id = int(channel_id) database = db.load_DB() if channel_id not in db.get_all_channels(database): raise ValueError('Channel (based on ID) does not exist') u_id = db.get_from_token('u_id', token, database) channel = db.get_channel_by_id(database, channel_id) for channel in database['channels']: if channel['channel_id'] == channel_id: if u_id in channel['members']: channel['members'].remove(u_id) db.save_DB(database) return {}
def message_react(token, message_id, react_id): '''Join existing user to a new channel''' if not Token.isValid(token): raise AccessError("Not a valid token!") if not message_id: raise ValueError('Invalid message_id') if react_id != "1": raise ValueError('Invalid react id') message_id = int(message_id) react_id = int(react_id) data = db.load_DB() u_id = db.get_from_token('u_id', token, data) if message_id not in db.get_all_messages(data): raise ValueError('Invalid message_id') if u_id in db.get_react_users(data, u_id, message_id, react_id, False): raise AccessError('Message with ID message_id already\ contains an active React with ID react_id') cur_message = [ msg for msg in data['messages'] if msg['message_id'] == message_id ][0] channel = [channel for channel in data['channels'] if channel['channel_id'] ==\ cur_message['in_channel']][0] valid = False for react in cur_message['reacts']: if 'react_id' in react.keys(): if react['react_id'] == react_id: react['u_ids'].append(u_id) valid = True if not valid: cur_message['reacts'].append({'react_id': react_id, 'u_ids': \ db.get_react_users(data, u_id, message_id, react_id)}) db.save_DB(data) return dumps({})
def auth_register(email, password, name_first, name_last): '''Register a user''' data = db.load_DB() users = data["users"] if users: all_emails = [user['email'] for user in users] else: all_emails = [] if not db.check_mail(email): raise ValueError('Email is not a valid email adress') if email in all_emails: raise ValueError('Email address is already being used by another user') if len(password) < 6: raise ValueError('Password entered is not a valid password.') if len(name_first) > 50 or not name_first: raise ValueError('Your First Name cannot be more than 50 characters.') if len(name_last) > 50 or not name_last: raise ValueError('Your Last Name cannot be more than 50 characters.') u_id = db.new_u_id(data) data['users'].append({ 'tokens': [], 'profile_img_url': 'https://www.thehumanenterprise.com.au/wp-content/uploads/2017/06/\ Empty-Profile-Testimonials.jpg', 'handle_str': name_first + name_last, 'u_id': u_id, 'email': email.lower(), 'password': db.hash_password(password), 'name_first': name_first, 'name_last': name_last, 'permission_id': 3 }) db.save_DB(data) return dumps({'u_id': u_id, 'token': Token.generateToken(email)})
def channel_details(token, channel_id): '''Gets the details of the channel''' if not Token.isValid(token): raise AccessError("Not a valid token!") database = db.load_DB() channel_id = int(channel_id) if channel_id not in db.get_all_channels(database): raise ValueError('Channel ID is not a valid channel') channel = db.get_channel_by_id(database, channel_id) if db.get_from_token("u_id", token, database) not in channel['members']: raise AccessError('Not authorised to view this channel') return dumps({ "name" : channel['name'], "all_members" : [user for user in database["users"] if user['u_id'] in channel['members']], "owner_members" : [user for user in database["users"] if \ user['u_id'] in channel['owner_members']] })
def user_profiles_uploadphoto(token, img_url, x_start, y_start, x_end, y_end, port): '''Allow a user to upload a photo''' if not Token.isValid(token): raise AccessError("Not a valid token!") data = db.load_DB() u_id = db.get_from_token("u_id", token, data) print("URL ==", img_url) resp = urllib.request.urlopen(img_url) image = np.asarray(bytearray(resp.read()), dtype="uint8") image = cv2.imdecode(image, -1) crop = image[int(y_start):int(y_end), int(x_start):int(x_end)] cv2.imwrite(f'imgurl/{u_id}.jpg', crop) for user in data['users']: if user['u_id'] == u_id: user[ 'profile_img_url'] = f'http://127.0.0.1:{port}/imgurl?id={u_id}' db.save_DB(data) return dumps({})