def register(): """Register user""" if request.method == 'POST': username = request.form.get('username') if not username: return apology("You must provide a user name.") row = mydb.execute("select * from users where name = ?", (username, )) if len(row) == 1: return apology('This user is already registered.') # just to make it sure. It could never happen elif len(row) > 1: return apology('Duplicates in the database') password = request.form.get('password') if not password: return apology("You must provide a passord") confirmation = request.form.get('confirmation') if not confirmation: return apology("You must confirm your passord.") hash_passw = generate_password_hash(password) if not check_password_hash(hash_passw, confirmation): return apology('Passwords do not match.') else: mydb.execute('insert into users(name, password) values(?,?)', username, hash_passw) flash("You are registered.") return redirect(url_for('auth_bp.login')) else: return render_template('register.html')
def change(): menu = viewMenu.catsMenu() if request.method == 'POST': # access post parameters old = request.form.get('oldpassword') new = request.form.get('newpassword') conf = request.form.get('confirmation') # see if new and confirmation password match if new != conf: return apology("New passord and confirmation don't match.") # query database to access user data row = mydb.execute("select * from users where id = ?", (session['user_id'], )) oldhash = row[0]['hash'] if not check_password_hash(oldhash, old): return apology('Current password is wrong.') newhash = generate_password_hash(new) # update database with new user password mydb.execute('update users set hash = ? where id = ?', ( newhash, session['user_id'], )) return redirect(url_for('auth_bp.logout')) else: return render_template('change.html', menu=menu)
def rem_book_id(id): bid = int(id) rows = mydb.execute('select * from bookmarks where id = ? and user_id = ?', bid, session['user_id']) title = rows[0]['title'] mydb.execute('delete from bookmarks where id = ?', (bid, )) flash(f'Bookmark with Title: {title} removed.') return (url_for('index'))
def setChecked(self, name, truthy): for item in self.menu: if item['name'].lower() == name.lower(): item['checked'] = truthy if truthy: visible = 1 else: visible = 0 # print('user_id', session['user_id']) # print('visible', visible) mydb.execute( '''update menu set visible = ? where cat_name = ? and user_id = ?''', visible, name.lower(), session['user_id']) break
def check(): """Return true if username available, else false, in JSON format""" name = request.args.get('username') # query database to see if there are any row with this username row = mydb.execute("select * from users where name = ?", (name,)) # print('register row', row) if len(row) == 0: avail = True else: avail = False return jsonify(avail)
def edit_id(id): menu = viewMenu.catsMenu() categories = list(map(lambda x: {'cat_name': x['name']}, menu)) bid = int(id) rows = mydb.execute('select * from bookmarks where id = ? and user_id = ?', bid, session['user_id']) listCats = list(map(lambda x: x['cat_name'], categories)) html = render_template('edit_id.html', row=rows[0], categories=listCats, menu=menu) return html
def create(): menu = viewMenu.catsMenu() categories = list(map(lambda x: {'cat_name': x['name']}, menu)) listCats = list(map(lambda x: x['cat_name'], categories)) if request.method == 'POST': # category always case independent category = request.form.get('category').lower() url = request.form.get('url') # see: https://www.urlencoder.io/python/ url = quote(url) title = request.form.get('title') description = request.form.get('description') if category not in listCats: mydb.execute( 'insert into categories(cat_name, user_id) values(?,?)', category, session['user_id']) mydb.execute( 'insert into menu(cat_name,user_id,visible) values(?,?,?)', category, session['user_id'], 1) mydb.execute( '''insert into bookmarks(categ_name, user_id, url, title, description) values(?,?,?,?,?)''', category, session['user_id'], url, title, description) urlImage(mydb, url) flash(f"Bookmark added to category {category}") return redirect(url_for('index')) else: # print(listCats) return render_template('create.html', categories=listCats, menu=menu)
def apply(): if request.method == 'POST': # categories always case independent category = request.form.get('category').lower() title = request.form.get('title') url = request.form.get('url') description = request.form.get('description') bookmark_id = int(request.form.get('bid')) # Have to test if the categories changed? Not # But if it is a new category, then I have to update categories categories = select_cats(mydb) listCats = list(map(lambda x: x['cat_name'], categories)) if category not in listCats: mydb.execute( 'insert into categories(cat_name, user_id) values(?,?)', category, session['user_id']) mydb.execute( 'insert into menu(cat_name,user_id,visible) values(?,?,?)', category, session['user_id'], 1) mydb.execute( '''update bookmarks set categ_name = ?, user_id = ?, title = ?, url = ?, description = ? where id = ? ''', category, session['user_id'], title, url, description, bookmark_id) # update image if needed urlImage(mydb, url) flash(f'Bookmark with Title: {title} edited.') return redirect(url_for('index'))
def catsMenu(view): catsMenu = [] cats = mydb.execute( '''select * from menu where user_id = ? order by cat_name''', (session['user_id'], )) for cat in cats: catDict = {} catDict['name'] = cat['cat_name'] catDict['checked'] = cat['visible'] catDict['menu_item'] = shorten_title(cat['cat_name'], 15) if cat['visible'] == 1: catDict['status'] = '[ On ]' else: catDict['status'] = '[ Off ]' catsMenu.append(catDict) view.setMenu(catsMenu) return catsMenu
def login(): """Log user in""" # Forget any user_id session.clear() # User reached route via POST (as by submitting a form via POST) if request.method == "POST": # Ensure username was submitted if not request.form.get("username"): return apology("You must provide a username.") # Ensure password was submitted elif not request.form.get("password"): return apology("You must provide a password.") # Query database for username rows = mydb.execute("SELECT * FROM users WHERE name = :username", username=request.form.get("username")) # Ensure username exists and password is correct if len(rows) != 1 or not check_password_hash( rows[0]["password"], request.form.get("password")): return apology("Invalid username and/or password") # Remember which user has logged in session["user_id"] = rows[0]["id"] session["list_view"] = True session["grid_view"] = False # Redirect user to home page flash('You are now logged in') return redirect(url_for('index')) # User reached route via GET (as by clicking a link or via redirect) else: return render_template("login.html")
def rem_cat_name(): categories = select_cats(mydb) listCats = list(map(lambda x: x['cat_name'], categories)) if request.method == 'POST': name = request.form.get('category') if name in listCats: mydb.execute( 'delete from bookmarks where categ_name = ? and user_id = ?', (name, session['user_id'])) mydb.execute('delete from menu where cat_name = ? and user_id = ?', (name, session['user_id'])) mydb.execute( 'delete from categories where cat_name = ? and user_id = ?', (name, session['user_id'])) flash(f'Category: {name} and all its posts removed') return redirect(url_for('index')) else: flash(f'Category: {name} is unknown') return redirect(url_for('index'))
def import_bms(): menu = viewMenu.catsMenu() known_cats = mydb.execute( 'select cat_name from categories where user_id = ?', (session['user_id'], )) listCats = list(map(lambda x: x['cat_name'], known_cats)) if request.method == 'POST': categories = [] urls = mydb.execute('select url from bookmarks where user_id = ?', (session['user_id'], )) listUrls = list(map(lambda x: x['url'], urls)) # see: https://www.kite.com/python/docs/werkzeug.FileStorage#:~:text=The%20%3Aclass%3A%60FileStorage%60%20class,the%20long%20form%20%60%60storage. try: file = request.files['filename'] except: return apology('Sorry, could not open the file') else: try: file_content = file.read().decode('utf-8') except UnicodeDecodeError: return apology('Sorry, this does not seem to be a text file.') else: # json -> python dictionary try: bm_dict = json.loads(file_content) except: return apology( 'Sorry, could not recognize this as a JSON file.') else: # consider only bookmarks bar # in the application, test if the if the key ['root']['bookmar_bar'] is defined! try: bm_dict = bm_dict['roots']['bookmark_bar']['children'] except: return apology( 'Sorry, could not find bookmark_bar inside the file.' ) else: for child in bm_dict: if child['type'] == 'url': categories.append(processURL(child)) if child['type'] == 'folder': categories += processFolder(child) for category in categories: print('category', category['category'].lower()) print('ListCats', listCats) if category['category'].lower() not in listCats: mydb.execute( 'insert into categories(cat_name, user_id) values(?,?)', category['category'].lower(), session['user_id']) mydb.execute( 'insert into menu(cat_name,user_id,visible) values(?,?,?)', category['category'].lower(), session['user_id'], 1) listCats.append(category['category'].lower()) if category['url'] in listUrls: # print('updating bookmarks in import') mydb.execute( '''update bookmarks set categ_name=?, title = ?, description = ? where user_id = ? and url = ?''', category['category'].lower(), category['title'], category['description'], session['user_id'], category['url']) else: mydb.execute( '''insert into bookmarks(categ_name, user_id, url, title, description) values(?,?,?,?,?)''', category['category'].lower(), session['user_id'], category['url'], category['title'], category['description']) return redirect(url_for('index')) else: return render_template('import.html', categories=listCats, menu=menu)