def validate_remove(data, token, messageId): if token in data['tokens']: pass else: raise ValueError("invalid token") channel_id = 0 messagereal = False for channel in data['channels']: for message in channel['messages']: if message['message_id'] == messageId: channel_id = channel['channel_id'] messagereal = True if messagereal == False: raise ValueError("cant find message") u_id = getUserFromToken(token) #userIsInChannel(data, channel_id, getUserFromToken(token)) if isUserinChannelbool(data, channel_id, u_id) == False: raise AccessError("User is not in that channel 184msg helper") exists = False ownmessage = False #adminCalling = False adminCalling = isAdminOrOwner(data, u_id) for channel in data['channels']: for message in channel['messages']: if message['message_id'] == messageId: exists = True if message['u_id'] == u_id: ownmessage = True if exists == False: raise ValueError("Invalid IDs") if ownmessage == False: if adminCalling == False: raise AccessError("Not an admin or owner or own message")
def user_profile_sethandle(data, token, handle_str): # Check if the handle is valid letter_number = True # Assumption: Has to be letter or number for i in handle_str: if not (i.isdigit() or i.isalpha()): letter_number = False if len(handle_str) > 20: raise ValueError("Should be no more than 20 characters") elif letter_number == False: raise ValueError("Handle can only be letters and digits") elif not handle_str: raise ValueError("Handle cannot be empty") # Reset it # Decode token to match user u_id = getUserFromToken(token) for user in data['users']: if user['handle'] == handle_str: raise ValueError("Handle is already being used") elif user['u_id'] == u_id: user['handle'] = handle_str
def admin_userpermission_change(data, token, u_id, permission_id): # Decode token to match user auth_u_id = getUserFromToken(token) # Check whether auth_u_id has the permission to change for auth_user in data['users']: if auth_user['u_id'] == auth_u_id: if not auth_user['is_admin'] == PERMISSION1 and \ not auth_user['is_admin'] == PERMISSION2: raise AccessError( 'The authorised user is not an admin or owner') # Check permission_id if permission_id != PERMISSION1 and \ permission_id != PERMISSION2 and \ permission_id != PERMISSION3: raise ValueError('permission_id does not refer to a value permission') # Check if u_id (the one that needs to be modified) exists exist = False for user in data['users']: if user['u_id'] == u_id: exist = True user['is_admin'] = permission_id # Raise error if u_id does not exist if exist == False: raise ValueError("u_id does not refer to a valid user")
def checkName(nameFirst, nameLast): if len(nameFirst) > NAME_MAX_LENGTH or len(nameFirst) < NAME_MIN_LENGTH: raise ValueError( 'First name is not between 1 and 50 characters in length') if len(nameLast) > NAME_MAX_LENGTH or len(nameLast) < NAME_MIN_LENGTH: raise ValueError( 'Last name is not between 1 and 50 characters in length')
def checkEmail(email): if len(email) > EMAIL_MAX_LENGTH: raise ValueError('Email cannot be more than 50 characters') regex = "^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$" if (re.search(regex, email)): return True else: raise ValueError('Email entered is not a valid')
def removeUserFromChannel(data, channel_id, u_id): for channel in data['channels']: if channel_id == channel['channel_id']: if u_id not in channel['members']: raise ValueError ('User is not a member of the channel!') else: channel['members'].remove(u_id) return True raise ValueError ('Channel does not exist.')
def addOwnerToChannel(data, channel_id, auth_u_id, u_id): for channel in data['channels']: if channel_id == channel['channel_id']: if u_id in channel['owners']: raise ValueError ('User is already an owner of the channel!') elif auth_u_id not in channel['owners'] or isServerOwner(data, auth_u_id): raise AccessError ('Invalid permission level; you are not an owner of this channel or server.') else: channel['owners'].append(u_id) return True raise ValueError ('Channel does not exist.')
def removeOwnerFromChannel(data, channel_id, auth_u_id, target_u_id): for channel in data['channels']: if channel_id == channel['channel_id']: if target_u_id not in channel['owners']: raise ValueError ('User is not an owner of the channel!') elif auth_u_id not in channel['owners'] or isServerOwner(data, auth_u_id): raise AccessError ('Invalid permission level; you are not an owner of this channel or server.') else: channel['owners'].remove(target_u_id) return True raise ValueError ('Channel does not exist.')
def joinChannel(data, channel_id, u_id): for channel in data['channels']: if channel_id == channel['channel_id']: if u_id in channel['members']: raise ValueError ('User is already a member of the channel!') elif channel['is_public'] is False and isAdmin(data, u_id) is False: raise AccessError ('Channel is private and you do not have admin permission access.') else: channel['members'].append(u_id) return True raise ValueError ('Channel does not exist.')
def validate_message(data, message, channelid, token, u_id): exists = False for channel in data['channels']: if str(channel['channel_id']) == str(channelid): exists = True if exists == False: raise ValueError("bad channel Id") u_id = getUserFromToken(token) #userIsInChannel(data, channelid, u_id) if isUserinChannelbool(data, channelid, u_id) == False: raise AccessError("User is not in that channel 184msg helper") if len(message) > 1000: raise ValueError( "ValueError when:Message is more than 1000 characters")
def standupSendFunc(data, token, channel_id, message): u_id = getUserFromToken(token) if channelExists(data, channel_id) is False: raise ValueError("Channel ID is not a valid channel.") if userIsInChannel(data, channel_id, u_id) is False: return AccessError("User is not in the channel.") if len(message) > 1000: raise ValueError ("Message exceeds 1000 char limit.") if standupStillActive(data, channel_id, u_id): alteredMessage = str(u_id) + ":" + message for channel in data['channels']: if channel == channel_id: channel['standup_message'].append(alteredMessage) else: raise ValueError ("An active standup is not currently running in this channel.")
def validate_messageLater(data, message, channelid, token, timeSend, Realtime): if channelid in data['channels']: pass else: raise ValueError("invalid token") u_id = getUserFromToken(token) #userIsInChannel(data, channelid, u_id) if isUserinChannelbool(data, channelid, u_id) == False: raise AccessError("User is not in that channel 184msg helper") #value error: Time sent is a time in the past #Value Error time sent is in past if len(message) > 1000: raise ValueError( "ValueError when:Message is more than 1000 characters")
def create(): data = getData() email, password, nameFirst, nameLast = (request.form[x] for x in ('email', 'password', 'name_first', 'name_last')) handle = createHandle( nameFirst, nameLast ) # In the form 'firstNamelastName' or if already taken: 'firstNamelastName123'. u_id = createU_ID(data) # In the form '123456'. if emailExists(email, data): raise ValueError('Email entered is already being used.') handle = uniqueHandle(data, handle) checkEmail(email) checkPassword(password) checkName(nameFirst, nameLast) createUser(data, email, hashPassword(password), nameFirst, nameLast, handle, u_id, PERMISSION3) data['users'][0][ 'is_admin'] = PERMISSION1 # The very first user who signs up is an owner data['tokens'].append(generateToken(u_id)) print(data) return sendSuccess({ 'u_id': u_id, 'token': generateToken(u_id), })
def resetPasswordFunc(data, resetCode, newPassword): for user in data['users']: if user['resetCode'] == resetCode: user['password'] = hashPassword(newPassword) user['resetCode'] = None return None raise ValueError('Reset code is not valid.')
def addUserToChannel(data, channel_id, u_id): for channel in data['channels']: if channel_id == channel['channel_id']: if u_id in channel['members']: raise ValueError ('User is already a member of the channel!') else: channel['members'].append(int(u_id)) return True
def user_profile_setname(data, token, name_first, name_last): # Check if the names are valid # Error will arise if vaild if not name_first.isalpha() or not name_last.isalpha(): raise ValueError("Should contain alpha letters only") elif len(name_first) > 50: raise ValueError("First name can not be more than 50 characters") elif len(name_last) > 50: raise ValueError("Last name can not be more than 50 characters") # Decode token to match user u_id = getUserFromToken(token) # Reset for user in data['users']: if user['u_id'] == u_id: user['name_last'] = name_last user['name_first'] = name_first
def userIsInChannel(data, channel_id, auth_u_id): for channel in data['channels']: if channel_id == channel['channel_id']: if str(auth_u_id) in channel['members']: # if str(auth_u_id) in channel['members'] or int(auth_u_id) in channel['members']: return True else: raise AccessError ('Requesting user is not an authorised member of the channel') raise ValueError ('Channel does not exist.')
def connect(): data = getData() email = request.form.get('email') password = request.form.get('password') checkEmail(email) for user in data['users']: if user['email'] == email and user['password'] == hashPassword( password): data['tokens'].append(generateToken(user['u_id'])) return sendSuccess({ 'u_id': user['u_id'], 'token': generateToken(user['u_id']), }) elif user['email'] == email and user['password'] != hashPassword( password): raise ValueError('Password is incorrect.') raise ValueError('Email does not belong to a user.')
def unpinMessage(data, token, messageId): if not messageExists(data, messageId): raise ValueError("That message does not exist") u_id = getUserFromToken(token) # Check whether user has the permission to pin for channels in data['channels']: for message in channels['messages']: if message['message_id'] == messageId: cid = channels['channel_id'] present = False for channels in data['channels']: #if channels['channel_id'] == cid: #print(channels['members']) #print("and we have") #print(u_id) for members in channels['members']: if members == str(u_id): #print("found him") present = True #print(members) if present == False: raise AccessError("user is not a part of that channel") for user in data['users']: if user['u_id'] == u_id: if user['is_admin'] == 3: raise ValueError( 'The authorised user is not an admin or owner') ispinned = isPinned(data, messageId) if ispinned == False: raise ValueError('That message is not yet pinned') #get the channels id for channel in data['channels']: for message in channel['messages']: if messageId == message['message_id']: cId = channel['channel_id'] #userIsInChannel(data, cId, u_id) if isUserinChannelbool(data, cId, u_id) == False: raise AccessError( "User is not in that channel 184msg helper") #end of error checking message['is_pinned'] = 0
def channelInvite(): data = getData() token = request.form.get('token') checkTokenValidity(token, data) channel_id, u_id = (request.form[x] for x in ('channel_id', 'u_id')) userIsInChannel(data, int(channel_id), getUserFromToken(token)) if validUser(data, int(u_id)) is False: raise ValueError('The invitee is an invalid user.') addUserToChannel(data, int(channel_id), int(u_id)) return sendSuccess({})
def reset(): data = getData() resetCode = int(request.form.get('reset_code')) newPassword = request.form.get('new_password') checkPassword(newPassword) for user in data['users']: if user['resetCode'] == resetCode: user['password'] = hashPassword(newPassword) user['resetCode'].remove(resetCode) return sendSuccess({}) raise ValueError('Reset code is not valid.')
def unreactMessage(data, messageId, reactId, token): valid = False for channel in data['channels']: for message in channel['messages']: if messageId == message['message_id']: cId = channel['channel_id'] valid = True if valid == False: raise ValueError("Didnt find message") u_id = getUserFromToken(token) #userIsInChannel(data, cId, u_id) if isUserinChannelbool(data, cId, u_id) == False: raise AccessError("User is not in that channel 184msg helper") if reactId != 1: raise ValueError("invalid reactId") # reacted = False for channel in data['channels']: for message in channel['messages']: if message['message_id'] == messageId: if message['is_reacted'] != reactId: raise ValueError("does not have that react id") message['is_reacted'] = 0
def user_profile_setemail(data, token, email): # Decode token to match user u_id = getUserFromToken(token) # Check email is vaild, use function in auth_register_helper checkEmail(email) # Reset for user in data['users']: if email in user['email']: raise ValueError("Email address is already being used") elif user['u_id'] == u_id: user['email'] = email
def pinMessage(data, token, messageId): if not messageExists(data, messageId): raise ValueError("That message does not exist") u_id = str(getUserFromToken(token)) # Check whether user has the permission to pin #print("PINNN THISSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS") useradmin = False #print(u_id) for user in data['users']: #print(user['u_id']) #print("compared to") #print(u_id) if str(user['u_id']) == str(u_id): #print("how'd we get in here lol") #print(user['is_admin']) if user['is_admin'] == 1: useradmin = True #print("you're a wizard harry") if user['is_admin'] == 2: useradmin = True #print(useradmin) if useradmin == False: raise ValueError('user is not an admin') ipinned = isPinned(data, messageId) if ipinned == True: raise ValueError('That message is already pinned') #print(ipinned) #get the channels id for channel in data['channels']: for message in channel['messages']: if messageId == message['message_id']: cId = channel['channel_id'] #userIsInChannel(data, cId, u_id) if isUserinChannelbool(data, cId, u_id) == False: raise AccessError( "User is not in that channel 184msg helper") #end of error checking message['is_pinned'] = 1
def standupStartFunc(data, token, channel_id): u_id = getUserFromToken(token) now = datetime.datetime.now() finish = now + datetime.timedelta(minutes = 15) checkTokenValidity(token, data) userIsInChannel(data, channel_id, u_id) if channelExists(data, channel_id) is False: raise ValueError('Channel ID is not a valid channel.') if standupNotActive(data, channel_id, u_id) is True: for channel in data['channels']: if str(channel_id) == channel['channel_id']: channel['standup_active'] = True channel['standup_end'] = finish else: raise ValueError ('A standup is already running in this channel.') ##sets timer to end standup at 'finish' time/posts the standup message standupEnd (data, channel_id, token, finish) return { 'time_finish': finish, }
def user_profile_uploadphoto(data, token, img_url, x_start, y_start, x_end, y_end): # Decode token to match user u_id = getUserFromToken(token) # Eroor checking req = requests.head(img_url) status = req.status_code if status != 200: raise ValueError("Invaild URL: HTTP status is not 200") elif img_url[-3:] != 'jpg': raise ValueError("Invaild URL: Not a JPG image") # Image down save_name = "./photo/" + str(u_id) + "photo.jpg" urllib.request.urlretrieve(img_url, save_name) # Error checking: Out of dimension data = requests.get(img_url).content im = Image.open(BytesIO(data)) width, height = im.size if x_start < 0 or x_start > width or x_end < 0 or x_end > width or y_start < 0 or y_start > height or y_end < 0 or y_end > height: raise ValueError("Out of dimension") elif x_end <= x_start or y_end <= y_start: raise ValueError( "x_start, y_start are left top corner; x_end, y_end are right bottom corner" ) # Crop save_crop_name = "./photo/" + str(u_id) + "photoCrop.jpg" imageObject = Image.open(save_name) cropped = imageObject.crop((x_start, y_start, x_end, y_end)) cropped.save(save_crop_name) # Reset '''
def reactToMessage(data, messageId, reactId, token): valid = False # channelId = "what the f**k" # for channel in data['channels']: # for message in channel['messages']: # if message['message_id'] == messageId: # channelId = channel['channel_id'] for channel in data['channels']: for message in channel['messages']: # print("comparing..") # print(messageId) # print(" ...and ... ") # print(message['message_id']) if messageId == message['message_id']: cId = channel['channel_id'] valid = True if valid == False: raise ValueError("Didnt find message") u_id = getUserFromToken(token) #userIsInChannel(data, cId, u_id) if isUserinChannelbool(data, cId, u_id) == False: raise AccessError("User is not in that channel 184msg helper") #print("AFTER THE DUMB THING ===============================") #print(cId) if valid == False: raise ValueError("Invalid IDs") if reactId != 1: raise ValueError("invalid reactId") # reacted = False for channel in data['channels']: for message in channel['messages']: if message['message_id'] == messageId: if message['is_reacted'] == 1: raise ValueError("Already reacted") message['is_reacted'] = 1
def user_profile(data, token, u_id): profile = {} # Check if u_id exists exist = False for user in data['users']: if user['u_id'] == u_id: exist = True profile['email'] = user['email'] profile['name_first'] = user['name_first'] profile['name_last'] = user['name_last'] profile['handle_str'] = user['handle'] # Raise error u_id if not exist if exist == False: raise ValueError("u_id does not refer to a valid user") return profile
def create(): data = getData() email = request.form.get('email') password = request.form.get('password') nameFirst = request.form.get('name_first') nameLast = request.form.get('name_last') handle = createHandle( nameFirst, nameLast ) # In the form 'firstNamelastName' or if already taken: 'firstNamelastName123'. u_id = createU_ID(data) # In the form 'U123456'. for users in data['users']: if email in users['email']: raise ValueError('Email entered is already being used.') while handle in users['handle']: handle = randomHandle(handle) checkEmail(email) checkPassword(password) checkName(nameFirst, nameLast) data['users'].append({ 'email': email, 'password': hashPassword(password), 'name_first': nameFirst, 'name_last': nameLast, 'handle': handle, 'u_id': u_id, 'resetCode': None, 'is_admin': PERMISSION3, }) # The very first user who signs up is an owner data['users'][0]['is_admin'] = PERMISSION1 data['tokens'].append(generateToken(u_id)) print(data) return sendSuccess({ 'u_id': u_id, 'token': generateToken(u_id), })
def vSendMsg(self, sMsg, iTimestamp): log.msg("SEND (" + self.username + ") = " + str(sMsg)) # If the client haven't started a connection via StartRemote command... if self.username not in self.factory.active_connections: err_msg = 'Connection not available.' log.msg(err_msg) raise SlotErrorNotification(err_msg) # ... if the SC operator is not connected, sent messages will be saved # as passive messages... elif (self.factory.active_connections[self.username] is None and self.is_user_gs is True): log.msg("No SC operator connected, stored as a passive message") self.rpc.store_message_unconnected(sMsg) # ... if the GS operator is not connected, the remote SC client will be # notified to wait for the GS to connect... elif (self.factory.active_connections[self.username] is None and self.is_user_gs is False): self.callRemote(NotifyEvent, iEvent=NotifyEvent.REMOTE_DISCONNECTED, sDetails=None) else: # Try to send a message to remote client try: self.factory.active_protocols[self.factory.active_connections[ self.username]].callRemote(NotifyMsg, sMsg=sMsg) except: raise ValueError("Error forwarding frame to remote user.") # Try to store the message in the remote SatNet server forwarded = '' if not self.rpc.testing: self.rpc.store_message(self.slot_id, self.is_user_gs, False, iTimestamp, sMsg) log.msg('>>> TESTING mode, not saving message in DB...') return {'bResult': True}