def send_confirmation_email(fname, email, code, userid): # Sends confirmation email # Return bool kwlog.log("Create email request") server = smtplib.SMTP('smtp.gmail.com', 587) server.ehlo() server.starttls() server.login("*****@*****.**", "KitchenWizard") kwlog.log("Login to email - complete") msg = MIMEMultipart() msg['From'] = "*****@*****.**" msg['To'] = email msg['Subject'] = "Welcome To Kitchen Wizard - Account Activation" body = """ Welcome %s, Let us be the first to welcome you to the easiest way to track what is happening in your kitchen. Before we get started we need you to complete the activation process by clicking the link below. CLICK HERE: http://52.36.126.156:8080?command=activate&code=%s& Thank You, Kitchen Wizard Support Team """ % (fname, code) msg.attach(MIMEText(body, 'plain')) kwlog.log("Sending message...") try: server.sendmail("*****@*****.**", email, msg.as_string()) server.close() kwlog.log("Message sent") return True except: server.close() kwlog.log("Message Failed") return False
def get_shopping_lists(session_key): userid = __get_userid_from_key(session_key) if userid == 'BAD_KEY': kwlog.log("Invaild session key") return "BAD_KEY" else: return __create_shopping_list(userid)
def __get_userid_from_key(key): # Gets userid from session key # Return str kwlog.log("Get userid from key") if __vaildate_sessionkey(key): return MySQL.get_userid_from_session_key(key) else: return "BAD_KEY"
def __clean_barcode(barcode): # Clean '+' out of some barcode # Return: str kwlog.log("Clean barcode") if '+' in barcode: return barcode.strip('+') else: return barcode
def encrypt_password(password): # Make password more secure # Return str kwlog.log("hashing hash") h = hashlib.md5() h.update(password) h.update(b"EVERYONE_LOVES_KITCHENWIZARD!") return h.hexdigest()
def __clean_barcode(barcode): # Clean '+' out of some barcode # Return: str kwlog.log("Clean barcode") if "+" in barcode: return barcode.strip("+") else: return barcode
def __get_userid_from_key(key): # Gets userid from session key # Return str kwlog.log("Get userid from key") if (__vaildate_sessionkey(key)): return MySQL.get_userid_from_session_key(key) else: return "BAD_KEY"
def value_from_header(data, attribute): kwlog.log("looking for " + str(attribute)) result = re.search(str(attribute) + "=[^&]*&", data[0]) kwlog.log("found: " + str(result)) if result is None: return "Error" else: result = result.group(0).split("=")[1].split('&')[0] return result.replace("+", " ")
def check_active_status(username): # Checks if account has been activated # Return bool if MySQL.get_active_status(username)[0] == 0: kwlog.log("Account not activated") return False else: kwlog.log("Account activated") return True
def value_from_header(data, attribute): kwlog.log("looking for "+ str(attribute)) result = re.search(str(attribute)+"=[^&]*&", data[0]) kwlog.log("found: " + str(result)) if result is None: return "Error" else: result = result.group(0).split("=")[1].split('&')[0] return result.replace("+"," ")
def update_group_of_item(groupid, barcode, session_key): userid = __get_userid_from_key(session_key) if userid == "BAD_KEY": kwlog.log("Bad Session Key") return "BAD_KEY" else: kwlog.log("Updating group for product") return MySQL.update_group_of_item(groupid, barcode)
def get_group_by_name(name): kwlog.log("Get category by name") sql = "SELECT * FROM Grouping WHERE GroupName = %s;" cursor.execute(sql, name) k = cursor.fetchone() if not k: return "NONE" else: return str(k[0])
def update_group_of_item(groupid, barcode, session_key): userid = __get_userid_from_key(session_key) if userid == 'BAD_KEY': kwlog.log("Bad Session Key") return "BAD_KEY" else: kwlog.log("Updating group for product") return MySQL.update_group_of_item(groupid, barcode)
def put_confirmation_code_in_database(code, username): sql = "INSERT INTO Activation_Key (Code, UserID) VALUES (%s, %s);" try: cursor.execute(sql, (str(code), str(username))) db.commit() return True except: db.rollback() kwlog.log("Error adding confirmation code to DB") return False
def update_activation_status_for_user(userid): kwlog.log("Update activation status") sql = "UPDATE User_Information SET IsActivated = '1' WHERE UserID = %s;" try: cursor.execute(sql, userid) db.commit() return True except: db.rollback() return False
def __check_code(userid, code): # Check code aginst DB # Return bool d_code = MySQL.get_act_code(userid) if d_code == code: kwlog.log("Activation code matches") return True else: kwlog.log("Activation code does not match") return False
def __session_key_exist(key): # Checks Session Key exist # Return bool if __check_vaild_date(key): if MySQL.get_userid_from_session_key(key): return True else: return False else: kwlog.log("Key has expired") return False
def put_group(name): kwlog.log("Put group") sql = "INSERT INTO `KitchenWizard`.`Grouping` (`GroupName`, `DateAdded`) VALUES (%s, %s);" try: cursor.execute(sql, (str(name), str(datetime.now()))) db.commit() return True except: db.rollback() kwlog.log("Error adding new group") return False
def remove_recipe_from_db(recipeId): kwlog.log(str(recipeId)) sql = "DELETE FROM Recipe WHERE RecipeID = %s;" try: cursor.execute(sql, (recipeId)) db.commit() return True except: raise db.rollback() return False
def put_new_product(item): kwlog.log("Put new product") sql = "INSERT INTO `KitchenWizard`.`ProductInformation` (`ProductID`, `ProductName`, `ProductDiscription`, `Manufacturer`, `Quantity`) VALUES (%s, %s, %s, %s, %s);" try: cursor.execute(sql,(str(item[0]), str(item[1]), str(item[2]), str(item[3]), str(item[4]))) db.commit() return True except: db.rollback() kwlog.log("Error adding new product") return False
def get_item_list(session_key): # Get items for a userid # Return list kwlog.log("Get items for a user") userid = __get_userid_from_key(session_key) if userid == 'BAD_KEY': kwlog.log("Bad Session Key") return "BAD_KEY" else: user_list = __get_items_for_user(userid) return __create_response_list(user_list)
def user_exist(usr): # Check if userid exist # Return str kwlog.log("Checking if user is in DB") if (safetyCheck(usr)): if MySQL.is_userid_in_DB(usr): return "ID_FOUND" else: return "NO_ID_FOUND" else: kwlog.log("safety check, failed") return "BAD_ID"
def create_account(username, fname, lname, email, hash): # Create account and add to DB # Return bool if MySQL.put_new_account(username, fname, lname, email, hash): if create_confirmation_email(fname, email, username): kwlog.log("Account Created, all good") return True else: kwlog.log("Error during creating confirmation email") return False else: return False
def put_new_product(item): kwlog.log("Put new product") sql = "INSERT INTO `KitchenWizard`.`ProductInformation` (`ProductID`, `ProductName`, `ProductDiscription`, `Manufacturer`, `Quantity`) VALUES (%s, %s, %s, %s, %s);" try: cursor.execute(sql, (str(item[0]), str(item[1]), str( item[2]), str(item[3]), str(item[4]))) db.commit() return True except: db.rollback() kwlog.log("Error adding new product") return False
def remove_job(thread): global job_queue global job_queue_blocked while True: if job_queue_blocked is True: continue else: job_queue_blocked = True job_queue.remove(thread) job_queue_blocked = False break kwlog.log("Job removed from queue")
def update_recipe_name(name, rec_id): sql = "UPDATE Recipe SET Name = %s WHERE RecipeID = %s;" kwlog.log("SQL update name request") try: cursor.execute(sql, (name, rec_id)) db.commit() return True except: db.rollback() if kwlog.debug: raise return False
def user_exist(usr): # Check if userid exist # Return str kwlog.log("Checking if user is in DB") if(safetyCheck(usr)): if MySQL.is_userid_in_DB(usr): return "ID_FOUND" else: return "NO_ID_FOUND" else: kwlog.log("safety check, failed") return "BAD_ID"
def __add_item_to_inventory(barcode, userid): # Add item to inventory # Return bool if not __product_is_in_DB(barcode): item = __get_product_details_from_api(barcode) if item == "No_Information": kwlog.log("API does not contain product") return "No_Information_Available" if not __add_product_to_DB(item): return False # Add item to inventory return [put_item_in_inventory(barcode, userid), get_group_by_barcode(barcode)]
def put_item_in_inventory(barcode, userid): kwlog.log("Put item in inventory") sql = "INSERT INTO `KitchenWizard`.`Inventory` (`UserID`, `ProductID`, `DateAdded`) VALUES (%s, %s, %s);" d = str(datetime.now()) try: cursor.execute(sql, (str(userid), str(barcode), d)) db.commit() return get_single_inventory(userid, d) #return True except: db.rollback() kwlog.log("Error adding item to inventory") raise return False
def update_inventory_item(info, uid, session_key): # Update inventory information for user # Return: string # info[] = [ExperationDate, PercentUsed] userid = __get_userid_from_key(session_key) for i in info: i = __clean_barcode(str(i)) if userid == 'BAD_KEY': kwlog.log("Bad Session Key") return "BAD_KEY" else: if MySQL.is_item_owned_by_user(userid, uid): return MySQL.update_inventory_item(uid, info) else: "INVAILD_INVENTORY_ID"
def update_inventory_item(info, uid, session_key): # Update inventory information for user # Return: string # info[] = [ExperationDate, PercentUsed] userid = __get_userid_from_key(session_key) for i in info: i = __clean_barcode(str(i)) if userid == "BAD_KEY": kwlog.log("Bad Session Key") return "BAD_KEY" else: if MySQL.is_item_owned_by_user(userid, uid): return MySQL.update_inventory_item(uid, info) else: "INVAILD_INVENTORY_ID"
def create_new_list(name, sessionkey): if len(sessionkey) > 0: userid = __get_userid_from_key(sessionkey) else: return "INVAILD_FORMAT" if userid == 'BAD_KEY': kwlog.log("Invaild session key") return "BAD_KEY" else: if not len(name) > 0: return "INVAILD_FORMAT" if MySQL.create_new_shopping_list(name, userid): return "LIST_CREATED" else: return "FAILED_TO_CREATE_LIST"
def __send_email(userid, sid): email = MySQL.get_email_for_user(userid) list_str = __create_list(sid) if list_str == "FAILED": return False kwlog.log("Create email request") server = smtplib.SMTP("smtp.gmail.com", 587) server.ehlo() server.starttls() server.login("*****@*****.**", "KitchenWizard") kwlog.log("Login to email - complete") msg = MIMEMultipart() msg["From"] = "*****@*****.**" msg["To"] = email msg["Subject"] = "Kitchen Wizard - Shopping List" body = """ <html> <head></head> <body> <h1>Shopping List</h1> <table cellpadding = \"15\" border = \"1\"> <tr><th>Item</th><th>Quantity</th></tr> %s </table> <br/><br/><br/> <p> Remember,<br/> Everyone Loves KitchenWizard!!! </p> </body> </html> """ % ( list_str ) msg.attach(MIMEText(body, "html")) kwlog.log("Sending message...") try: server.sendmail("*****@*****.**", email, msg.as_string()) server.close() kwlog.log("Message sent") return True except: server.close() kwlog.log("Message Failed") return False
def update_account_information(fname, lname, email, password, sessionkey): kwlog.log("request to update account information") userid = __get_userid_from_key(sessionkey) if len(fname) > 0: if not MySQL.update_first_name_for_user(userid, fname): return False if len(lname) > 0: if not MySQL.update_last_name_for_user(userid, lname): return False if len(email) > 0: if not MySQL.update_email_for_user(userid, email): return False if len(password) > 0: password = __encrypt_password(password) if not MySQL.update_password_for_user(userid, password): return False return True
def remove_item_from_list(rid, gid, session): userid = __get_userid_from_key(session) if userid == 'BAD_KEY': kwlog.log("Invaild session key") return "BAD_KEY" else: if not MySQL.is_vaild_group(gid): return "INVAILD_GROUP" if not MySQL.is_vaild_shopping_list(rid, userid): kwlog.log("List not owned by user") return "INVAILD_SHOPPING_LIST" else: if not MySQL.remove_item_from_shopping_list(gid, rid): return "UNABLE_TO_REMOVE_ITEM" else: return "REMOVE_ITEM_COMPLETE"
def __send_email(userid, sid): email = MySQL.get_email_for_user(userid) list_str = __create_list(sid) if list_str == "FAILED": return False kwlog.log("Create email request") server = smtplib.SMTP('smtp.gmail.com', 587) server.ehlo() server.starttls() server.login("*****@*****.**", "KitchenWizard") kwlog.log("Login to email - complete") msg = MIMEMultipart() msg['From'] = "*****@*****.**" msg['To'] = email msg['Subject'] = "Kitchen Wizard - Shopping List" body = """ <html> <head></head> <body> <h1>Shopping List</h1> <table cellpadding = \"15\" border = \"1\"> <tr><th>Item</th><th>Quantity</th></tr> %s </table> <br/><br/><br/> <p> Remember,<br/> Everyone Loves KitchenWizard!!! </p> </body> </html> """ % (list_str) msg.attach(MIMEText(body, 'html')) kwlog.log("Sending message...") try: server.sendmail("*****@*****.**", email, msg.as_string()) server.close() kwlog.log("Message sent") return True except: server.close() kwlog.log("Message Failed") return False
def remove_recipe(recipe_id, session_key): userid = __get_userid_from_key(session_key) recipe_id = int(recipe_id) if not __recipe_in_inventory(recipe_id, userid): kwlog.log("Recipe not in inventory") return False else: if MySQL.remove_all_items_from_recipe(recipe_id): kwlog.log("removed all items") if __remove_recipe_from_db(recipe_id): kwlog.log("recipe removed from DB") return True else: kwlog.log("could not remove recipe") return False else: kwlog.log("failed to remove all items") return False
def get_list_of_ingredients(session_key, recipeid): try: userid = __get_userid_from_key(session_key) if userid == "BAD_KEY": kwlog.log("bad key") raise ingredients = get_ingredients_for_recipe(userid, recipeid) result = "" if ingredients is None: return "" for ingredient in ingredients: result += str(get_group_name_from_group_id(ingredient[0])[0])+ "-" + str(ingredient[1])+"\n" return result except: if kwlog.debug: raise return "Problem processing request"
def get_list_of_recipes(session_key): try: userid = __get_userid_from_key(session_key) if userid == "BAD_KEY": kwlog.log("bad key") raise recipes = get_recipes_for_user(userid) recipe_arr = [] for recipe in recipes: recipe = list(recipe) recipe[7] = str(recipe[7]) recipe_arr.append(recipe) return recipe_arr except: if kwlog.debug: raise return "Problem processing request"
def listen(): try: serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) serversocket.bind(('', 8080)) serversocket.listen(5) kwlog.log("Server is listening") except: kwlog.log("There was a problem while starting the server socket") while True: try: (clientsocket, address) = serversocket.accept() kwlog.log("Connection from: " + str(address)) manager.start_job(clientsocket) except: kwlog.log("Connection failed:") raise kwlog.log("Server has stopped listening")