def edit(article_handle='0'): setExits() g.title = "Article" articles = Article(g.db) #import pdb; pdb.set_trace() rec_id = cleanRecordID(article_handle) rec = articles.get(article_handle) if not rec and not rec_id == 0: flash('Could not find that artcle') return redirect(g.homeURL) if rec_id == 0: rec = articles.new() #Is there a form? if request.form: #import pdb; pdb.set_trace() articles.update(rec,request.form) if valid_form(rec): if request.form['publication_date']: # convert to a date time rec.publication_date = getDatetimeFromString(request.form['publication_date']) try: articles.save(rec) g.db.commit() return redirect(g.homeURL) except Exception as e: g.db.rollback() flash(printException("Error when attepting to save article.",e)) return render_template('news/article_edit.html',rec=rec)
def delete(rec_id=None): setExits() delete_by_admin = request.args.get('delete', None) if delete_by_admin: user = User(g.db) rec = user.select_one( where='access_token = "{}"'.format(delete_by_admin.strip())) if rec: rec_id = rec.id if rec_id == None: rec_id = request.form.get('id', request.args.get('id', -1)) rec_id = cleanRecordID(rec_id) if rec_id <= 0: flash("That is not a valid record ID") return redirect(g.listURL) rec = User(g.db).get(rec_id, include_inactive=True) if not rec: flash("Record not found") else: User(g.db).delete(rec.id) g.db.commit() flash('User Record Deleted') return redirect(g.listURL)
def edit(rec_id=None): setExits() g.title = "Edit {} Record".format(g.title) role = Role(g.db) rec = None if rec_id == None: rec_id = request.form.get('id', request.args.get('id', -1)) rec_id = cleanRecordID(rec_id) #import pdb;pdb.set_trace if rec_id < 0: flash("That is not a valid ID") return redirect(g.listURL) if not request.form: """ if no form object, send the form page """ if rec_id == 0: rec = role.new() else: rec = role.get(rec_id) if not rec: flash("Unable to locate that record") return redirect(g.listURL) else: #have the request form #import pdb;pdb.set_trace() if rec_id and request.form['id'] != 'None': rec = role.get(rec_id) else: # its a new unsaved record rec = role.new() role.update(rec, request.form) if validForm(rec): #update the record role.update(rec, request.form) # make names lower case rec.name = request.form['name'].lower().strip() try: role.save(rec) g.db.commit() except Exception as e: g.db.rollback() flash( printException( 'Error attempting to save ' + g.title + ' record.', "error", e)) return redirect(g.listURL) else: # form did not validate pass # display form return render_template('role/role_edit.html', rec=rec)
def get_roles(self, userID, **kwargs): """Return a list of the role namedlist objects for the user's roles""" order_by = kwargs.get('order_by', 'rank desc, name') sql = """select * from role where id in (select role_id from user_role where user_id = ?) order by {} """.format(order_by) return Role(self.db).rows_to_namedlist( self.db.execute(sql, (cleanRecordID(userID), )).fetchall())
def get(self, handle): """Get a single Article record by id or slug line""" rec_id = cleanRecordID(handle) if rec_id >= 0: # it looks like an id return super().get(rec_id) else: sql = 'select * from {} where slug = ?'.format(self.table_name) return self.select_one_raw(sql, (handle, ))
def test_cleanRecordID(): """Tesst the cleanRecordID utility fuction""" assert utils.cleanRecordID(1234) == 1234 assert utils.cleanRecordID("1234") == 1234 assert utils.cleanRecordID("this is a test4455") == -1 assert utils.cleanRecordID("1234this is a test") == -1 assert utils.cleanRecordID(-4) == -4 assert utils.cleanRecordID('-4') == -1 assert utils.cleanRecordID(None) == -1
def get(self, id, **kwargs): """Return a single namedlist for the user with this id A keyword argument for include_inactive controls filtering of active users only """ #if the 'id' is a string, try to find the user by username or email if type(id) is str: return self.get_by_username_or_email(id, **kwargs) include_inactive = kwargs.get('include_inactive', False) where = 'id = {} {}'.format(cleanRecordID(id), self._active_only_clause(include_inactive)) return self.select_one(where=where)
def admin(id=None): """Administrator access for the User table records """ setExits() if id == None: flash("No User identifier supplied") return redirect(g.listURL) #import pdb;pdb.set_trace() id = cleanRecordID(id) if (id < 0): flash("That is an invalid id") return redirect(g.listURL) #session['user_edit_token'] = id return edit(id)
def delete(rec_id=None): setExits() g.title = "Delete {} Record".format(g.title) if rec_id == None: rec_id = request.form.get('id', request.args.get('id', -1)) rec_id = cleanRecordID(rec_id) if rec_id <= 0: flash("That is not a valid record ID") return redirect(g.listURL) rec = Pref(g.db).get(rec_id) if not rec: flash("Record not found") else: Pref(g.db).delete(rec.id) g.db.commit() return redirect(g.listURL)
def get(self, name, user_name=None, **kwargs): """can get by pref name and user_name""" user_clause = '' if user_name: user_clause = ' and user_name = {}'.format(user_name) if type(name) is str: where = ' lower(name) = lower("{}") {}'.format(name, user_clause) else: where = ' id = {}'.format(cleanRecordID(name)) result = self.select_one(where=where) if not result and 'default' in kwargs and type(name) is str: # create a record with the default value rec = self.new() rec.name = name rec.value = kwargs['default'] self.save(rec) self.db.commit() result = rec return result
def validForm(rec): # Validate the form goodForm = True if request.form['name'].strip() == '': goodForm = False flash('Name may not be blank') else: # name must be unique (but not case sensitive) where = 'lower(name)="{}"'.format( request.form['name'].lower().strip(), ) if rec.id: where += ' and id <> {}'.format(rec.id) if Role(g.db).select(where=where) != None: goodForm = False flash('Role names must be unique') # Rank must be in a reasonalble range temp_rank = cleanRecordID(request.form['rank']) if temp_rank < 0 or temp_rank > 1000: goodForm = False flash("The Rank must be between 0 and 1000") return goodForm
def edit(rec_handle=None): setExits() g.title = "Edit {} Record".format(g.title) #import pdb;pdb.set_trace() user = User(g.db) rec = None request_rec_id = cleanRecordID( request.form.get('id', request.args.get('id', -1))) is_admin = g.admin.has_access(g.user, User) no_delete = not is_admin session_roles = session["user_roles"] #roles of currnet user new_password = '' confirm_password = '' user_roles = ['user'] # default roles = Role(g.db).select() include_inactive = True if not is_admin: g.listURL = g.homeURL # Non admins can't see the list include_inactive = False if rec_handle != None: pass #rec_handle has to come from admin() at this point elif rec_handle == None and g.user != None and request_rec_id == -1: rec_handle = g.user else: rec_handle = request_rec_id if rec_handle < 0: flash("That is not a valid User ID") return redirect(g.listURL) if not request.form: """ if no form object, send the form page """ if rec_handle != g.user and not is_admin: flash("You do not have access to that area") return redirect(g.homeURL) elif rec_handle == 0: rec = user.new() else: rec = user.get(rec_handle, include_inactive=include_inactive) if not rec: flash("Unable to locate user record") return redirect('/') user_roles = get_user_role_names(rec) else: #have the request form #import pdb;pdb.set_trace() is_new_user = False if rec_handle and request.form['id'] != 'None': rec = user.get(rec_handle, include_inactive=include_inactive) user_roles = get_user_role_names(rec) else: # its a new unsaved record is_new_user = True rec = user.new() user.update(rec, request.form) if validForm(rec): #Are we editing the current user's record? editingCurrentUser = '' if (g.user == rec.username): if 'new_username' in request.form: editingCurrentUser = request.form['new_username'].strip() else: editingCurrentUser = g.user else: if (g.user == rec.email): editingCurrentUser = request.form['email'].strip() #update the record user.update(rec, request.form) set_username_from_form(rec) set_password_from_form(rec) try: user.save(rec) # update the user roles if 'roles_select' in request.form: #delete all the users current roles user.clear_roles(rec.id) for role_name in request.form.getlist('roles_select'): #find the role by name role = Role(g.db).select_one( where='name = "{}"'.format(role_name)) if role: user.add_role(rec.id, role.id) # if the username or email address are the same as g.user # update g.user if it changes if (editingCurrentUser != ''): setUserStatus(editingCurrentUser, rec.id) g.db.commit() except Exception as e: g.db.rollback() flash( printException( 'Error attempting to save ' + g.title + ' record.', "error", e)) return redirect(g.listURL) if is_new_user == True and rec.email: from takeabeltof.mailer import send_message # send an email to welcome the new user full_name = '{} {}'.format(rec.first_name, rec.last_name).strip() context = { 'rec': rec, 'full_name': full_name, } to_address_list = [(full_name, rec.email)] sent, msg = send_message( to_address_list, subject="Welcome to {{config.SITE_NAME}}", context=context, html_template='user/email/welcome.html', text_template='user/email/welcome.txt', ) if not sent: flash('The welcome message could not be sent. Error: {}'. format(msg)) return redirect(g.listURL) else: # form did not validate, give user the option to keep their old password if there was one #need to restore the username user.update(rec, request.form) if 'new_username' in request.form: rec.username = request.form[ 'new_username'] #preserve user input # preserve the selected roles #import pdb;pdb.set_trace() if 'roles_select' in request.form: user_roles = request.form.getlist('roles_select') #and password new_password = request.form.get('new_password', '') confirm_password = request.form.get('confirm_password', '') # display form return render_template( 'user/user_edit.html', rec=rec, no_delete=no_delete, is_admin=is_admin, user_roles=user_roles, roles=roles, session_roles=session_roles, new_password=new_password, confirm_password=confirm_password, )
def get(self, id, **kwargs): """Return a single namedlist for the ID or None""" return self._single_row( self.select(where='id = {}'.format(cleanRecordID(id), )))
def add_role(self, user_id, role_id): self.db.execute('insert into user_role (user_id,role_id) values (?,?)', ( cleanRecordID(user_id), cleanRecordID(role_id), ))
def clear_roles(self, user_id): """Delete all user_role records from this user""" self.db.execute('delete from user_role where user_id = ?', (cleanRecordID(user_id), ))