def edit(news_id=None): if not ModuleAPI.can_write('news'): return abort(403) if news_id: news_item = News.query.get_or_404(news_id) else: news_item = News() form = NewsForm(request.form, news_item) if request.method == 'POST': if form.validate_on_submit(): # fill the news_item with the form entries. form.populate_obj(news_item) # Only set writer if post is brand new if not news_item.id: news_item.user_id = current_user.id db.session.add(news_item) db.session.commit() news_id = news_item.id flash(_('News item saved'), 'success') return redirect(url_for('news.view', news_id=news_id)) else: flash_form_errors(form) return render_template('news/edit.htm', form=form, news_id=news_id)
def create_issue(): if current_user.is_anonymous or not current_user.has_paid: abort(403) form = CreateIssueForm(request.form) if form.validate_on_submit(): # Use JiraAPI to do a POST request to https://viaduct.atlassian.net response = JiraAPI.create_issue(form) print(response, bool(response)) if response: flash('The bug has been reported!', 'success') redir = request.args.get('redir') if redir: return redirect(redir) else: return redirect(url_for('home.home')) else: flash(_('Something went wrong.'), 'danger'), 500 else: flash_form_errors(form) return render_template('jira/create_issue.htm', form=form)
def edit(contact_id=None): """Create or edit a contact, frontend.""" if not ModuleAPI.can_read('contact'): return abort(403) if contact_id: contact = Contact.query.get(contact_id) else: contact = Contact() form = ContactForm(request.form, contact) locations = Location.query.order_by('address').order_by('city') form.location_id.choices = \ [(l.id, '%s, %s' % (l.address, l.city)) for l in locations] if form.validate_on_submit(): if not contact.id and Contact.query.filter( Contact.email == form.email.data).count(): flash(_('Contact email "%s" is already in use.' % form.email.data), 'danger') return render_template('contact/edit.htm', contact=contact, form=form) form.populate_obj(contact) db.session.add(contact) db.session.commit() flash(_('Contact person saved.'), 'success') return redirect(url_for('contact.edit', contact_id=contact.id)) else: flash_form_errors(form) return render_template('contact/edit.htm', contact=contact, form=form)
def delete(path): if not ModuleAPI.can_write('page'): return abort(403) page = Page.get_by_path(path) if not page: flash(_('The page you tried to delete does not exist.'), 'danger') return redirect(url_for('page.get_page', path=path)) abort(404) rev = page.get_latest_revision() class DeleteForm(Form): title = StringField(_('Page title')) form = DeleteForm(request.form) if form.validate_on_submit(): if rev.title == form.title.data: db.session.delete(page) db.session.commit() flash(_('The page has been deleted'), 'success') return redirect(url_for('home.home')) else: flash(_('The given title does not match the page title.'), 'warning') else: flash_form_errors(form) return render_template('page/delete.htm', rev=rev, form=form)
def edit_seo(): # TODO CHANGE THIS TO SEO if not ModuleAPI.can_write('seo'): return abort(403) module = request.args['module'] path = request.args['path'] seo = SeoAPI.get_seo(module, path) # Retrieve form info. form = SeoForm(request.form, seo) # On Seo submit (edit or create) if form.validate_on_submit(): if seo: # Edit the seo entry seo.nl_title = form.nl_title.data.strip() seo.en_title = form.en_title.data.strip() seo.nl_description = form.nl_description.data.strip() seo.en_description = form.en_description.data.strip() seo.nl_tags = form.nl_tags.data.strip() seo.en_tags = form.en_tags.data.strip() print("SEO") db.session.add(seo) db.session.commit() if not seo: # Get seo resources to indentify the seo in the database. res = SeoAPI.get_resources(module, path) # Create the new seo entry seo = SEO(res['page'], res['page_id'], res['activity'], res['activity_id'], res['url'], form.nl_title.data.strip(), form.en_title.data.strip(), form.nl_description.data.strip(), form.en_description.data.strip(), form.nl_tags.data.strip(), form.en_tags.data.strip()) print(vars(seo)) db.session.add(seo) db.session.commit() flash(_('The seo settings have been saved'), 'success') # redirect newly created page return redirect(url_for('page.get_page', path=path)) else: flash_form_errors(form) return render_template('seo/edit_seo.htm', form=form)
def sign_up(): # Redirect the user to the index page if he or she has been authenticated # already. if current_user.is_authenticated: return redirect(url_for('home.home')) form = SignUpForm(request.form) # Add education. educations = Education.query.all() form.education_id.choices = [(e.id, e.name) for e in educations] if form.validate_on_submit(): query = User.query.filter(User.email == form.email.data) if query.count() > 0: flash(_('A user with this e-mail address already exists'), 'danger') return render_template('user/sign_up.htm', form=form) user = User(form.email.data, bcrypt.hashpw(form.password.data, bcrypt.gensalt()), form.first_name.data, form.last_name.data, form.student_id.data, form.education_id.data, form.birth_date.data, form.study_start.data, form.receive_information.data) user.phone_nr = form.phone_nr.data user.address = form.address.data user.zip = form.zip.data user.city = form.city.data user.country = form.country.data db.session.add(user) db.session.commit() group = Group.query.filter(Group.name == 'all').first() group.add_user(user) db.session.add(group) db.session.commit() copernica.update_user(user, subscribe=True) login_user(user) flash(_('Welcome %(name)s! Your profile has been succesfully ' 'created and you have been logged in!', name=current_user.first_name), 'success') return redirect(url_for('home.home')) else: flash_form_errors(form) return render_template('user/sign_up.htm', form=form)
def edit(summary_id): if not ModuleAPI.can_write('summary', True): session['prev'] = 'summary.edit_summary' return abort(403) summary = Summary.query.get(summary_id) if not summary: flash(_('Summary could not be found.'), 'danger') return redirect(url_for('summary.view')) session['summary_edit_id'] = summary_id form = EditForm(request.form, summary) courses = Course.query.order_by(Course.name).all() educations = Education.query.order_by(Education.name).all() form.course.choices = [(c.id, c.name) for c in courses] form.education.choices = [(e.id, e.name) for e in educations] if request.method == 'POST': if form.validate_on_submit(): file = request.files['summary'] summary.title = form.title.data summary.course_id = form.course.data summary.education_id = form.education.data summary.date = form.date.data new_path = upload_file_real(file, summary.path) if new_path: summary.path = new_path elif new_path is None: flash(_('Wrong format summary.'), 'danger') if not new_path: flash(_('Old summary preserved.'), 'info') db.session.commit() flash(_('Summary succesfully changed.'), 'success') return redirect(url_for('summary.edit', summary_id=summary_id)) else: flash_form_errors(form) path = '/static/uploads/summaries/' return render_template( 'summary/edit.htm', path=path, summary=summary, courses=courses, educations=educations, new_summary=False, form=form)
def request_password(): """Create a ticket and send a email with link to reset_password page.""" if current_user.is_authenticated: return redirect(url_for('user.view_single', user_id=current_user.id)) def create_hash(bits=96): assert bits % 8 == 0 required_length = bits / 8 * 2 s = hex(random.getrandbits(bits)).lstrip('0x').rstrip('L') if len(s) < required_length: return create_hash(bits) else: return s form = RequestPassword(request.form) if form.validate_on_submit(): user = User.query.filter( User.email == form.email.data).first() if not user: flash(_('%(email)s is unknown to our system.', email=form.email.data), 'danger') else: _hash = create_hash(256) ticket = PasswordTicket(user.id, _hash) db.session.add(ticket) db.session.commit() reset_link = url_for('user.reset_password', hash=_hash, _external=True) send_email(to=user.email, subject='Password reset https://svia.nl', email_template='email/forgot_password.html', sender='via', user=user, reset_link=reset_link) flash(_('An email has been sent to %(email)s with further ' 'instructions.', email=form.email.data), 'success') return redirect(url_for('home.home')) else: flash_form_errors(form) return render_template('user/request_password.htm', form=form)
def view(page_nr=1): if not (ModuleAPI.can_read("group")): return abort(403) form = ViewGroupForm(request.form) pagination = Group.query.order_by(Group.name).paginate(page_nr, 15, False) if form.validate_on_submit(): if form.delete_group.data: if ModuleAPI.can_write("group"): group_ids = [] for group, form_entry in zip(pagination.items, form.entries): if form_entry.select.data: group_ids.append(group.id) groups = Group.query.filter(Group.id.in_(group_ids)).all() for group in groups: db.session.delete(group) db.session.commit() if len(groups) > 1: flash("The selected groups have been deleted.", "success") else: flash("The selected group has been deleted.", "success") return redirect(url_for("group.view")) else: flash("This incident has been reported to our authorities.", "warning") else: for group in pagination.items: form.entries.append_entry() flash_form_errors(form) return render_template( "group/view.htm", form=form, pagination=pagination, groups=zip(pagination.items, form.entries), current_user=current_user, title="Groups", )
def add(): if not ModuleAPI.can_write('summary', True): session['prev'] = 'summary.edit_summary' return abort(403) form = EditForm(request.form) courses = Course.query.order_by(Course.name).all() educations = Education.query.order_by(Education.name).all() form.course.choices = [(c.id, c.name) for c in courses] form.education.choices = [(e.id, e.name) for e in educations] path = '/static/uploads/summaries/' if request.method == 'POST': if form.validate_on_submit(): file = request.files['summary'] new_path = upload_file_real(file) if new_path: summary = Summary(form.title.data, new_path, form.date.data, form.course.data, form.education.data) db.session.add(summary) db.session.commit() flash(_('Summary uploaded succesfully.'), 'success') elif new_path is None: flash(_('Wrong format summary.'), 'danger') if not new_path: flash(_('Summary required.'), 'danger') # TODO: Fix dummy summary to show previous information on new # page return render_template( 'summary/edit.htm', path=path, courses=courses, educations=educations, new_summary=True, form=form) return redirect(url_for('summary.edit', summary_id=summary.id)) else: flash_form_errors(form) return render_template( 'summary/edit.htm', path=path, courses=courses, educations=educations, new_summary=True, form=form)
def edit(vacancy_id=None): """Create, view or edit a vacancy.""" if not ModuleAPI.can_write('vacancy'): return abort(403) # Select vacancy. if vacancy_id: vacancy = Vacancy.query.get(vacancy_id) else: vacancy = Vacancy() form = VacancyForm(request.form, vacancy) # Add companies. form.company_id.choices = [(c.id, c.name) for c in Company.query .order_by('name')] if form.validate_on_submit(): if not vacancy.id and Vacancy.query.filter( Vacancy.title == form.title.data).count(): flash(_('Title "%s" is already in use.' % form.title.data), 'danger') return render_template('vacancy/edit.htm', vacancy=vacancy, form=form, title="Vacatures") vacancy.title = form.title.data vacancy.description = form.description.data vacancy.start_date = form.start_date.data vacancy.end_date = form.end_date.data vacancy.contract_of_service = form.contract_of_service.data vacancy.workload = form.workload.data vacancy.company = Company.query.get(form.company_id.data) db.session.add(vacancy) db.session.commit() if vacancy_id: flash(_('Vacancy saved'), 'success') else: flash(_('Vacancy created'), 'success') return redirect(url_for('vacancy.list')) else: flash_form_errors(form) return render_template('vacancy/edit.htm', vacancy=vacancy, form=form, title="Vacatures")
def add_education(): r = request.args.get('redir', True) if r in REDIR_PAGES: session['origin'] = url_for(REDIR_PAGES[r]) elif r == 'edit' and 'examination_edit_id' in session: session['origin'] = '/examination/edit/{}'.format( session['examination_edit_id']) if not ModuleAPI.can_write('examination', True): session['prev'] = 'examination.add_education' return abort(403) form = EducationForm(request.form) if request.method == 'POST': if form.validate_on_submit(): title = form.title.data education = Education.query.filter(Education.name == title).first() if not education: new_education = Education(title) db.session.add(new_education) db.session.commit() flash("'%s': " % title + _('Education succesfully added.'), 'success') else: flash("'%s': " % title + _('Already exists in the database'), 'danger') if 'origin' in session: redir = session['origin'] else: redir = url_for('examination.add') return redirect(redir) else: flash_form_errors(form) return render_template('education/edit.htm', form=form, new=True)
def edit(location_id=None): """FRONTEND, Create, view or edit a location.""" if not ModuleAPI.can_write('location'): return abort(403) # Select location.. if location_id: location = Location.query.get(location_id) else: location = Location() form = LocationForm(request.form, location) if form.validate_on_submit(): form.populate_obj(location) db.session.add(location) db.session.commit() flash(_('Location saved.'), 'success') return redirect(url_for('location.edit', location_id=location.id)) else: flash_form_errors(form) return render_template('location/edit.htm', location=location, form=form)
def sign_in(): # Redirect the user to the index page if he or she has been authenticated # already. if current_user.is_authenticated: return redirect(url_for('home.home')) form = SignInForm(request.form) if form.validate_on_submit(): user = form.validate_signin() if user: # Notify the login manager that the user has been signed in. login_user(user) if user.disabled: flash(_('Your account has been disabled, you are not allowed ' 'to log in'), 'danger') else: flash(_('Hey %(name)s, you\'re now logged in!', name=current_user.first_name), 'success') referer = request.headers.get('Referer') denied = ( re.match(r'(?:https?://[^/]+)%s$' % (url_for('user.sign_in')), referer) is not None) denied_from = session.get('denied_from') if not denied: if referer: return redirect(referer) elif denied_from: return redirect(denied_from) return redirect(url_for('home.home')) if form.errors: flash_form_errors(form) return render_template('user/sign_in.htm', form=form)
def reset_password(hash=0): """ Reset form existing of two fields, password and password_repeat. Checks if the hash in the url is found in the database and timestamp has not expired. """ form = ResetPassword(request.form) # Request the ticket to validate the timer ticket = PasswordTicket.query.filter( db.and_(PasswordTicket.hash == hash)).first() # Check if the request was followed within a hour if ticket is None or ((datetime.now() - ticket.created_on).seconds > 3600): flash(_('No valid ticket found')) return redirect(url_for('user.request_password')) if form.validate_on_submit(): user = User.query.filter(User.id == ticket.user).first() if not user: flash(_('There is something wrong with the reset link.'), 'danger') return redirect(url_for('user.request_password')) # Actually reset the password of the user user.password = bcrypt.hashpw(form.password.data, bcrypt.gensalt()) login_user(user) db.session.add(user) db.session.commit() flash(_('Your password has been updated.'), 'success') return redirect(url_for('user.view_single', user_id=user.id)) else: flash_form_errors(form) return render_template('user/reset_password.htm', form=form)
def create(company_id=None): # Select company. if company_id: company = Company.query.get_or_404(company_id) else: company = Company() data = {} data["name"] = company.name data["description"] = company.description data["contract_start_date"] = company.contract_start_date data["contract_end_date"] = company.contract_end_date data["website"] = company.website # Select locations. if company.location_id: location = Location.query.get(company.location_id) else: location = Location() data['location_city'] = location.city data['location_country'] = location.country data['location_address'] = location.address data['location_zip'] = location.zip data['location_postoffice_box'] = location.postoffice_box data['location_email'] = location.email data['location_phone_nr'] = location.phone_nr if company.contact_id: contact = Contact.query.get(company.contact_id) else: contact = Contact() data['contact_name'] = contact.name data['contact_email'] = contact.email data['contact_phone_nr'] = contact.phone_nr form = init_form(NewCompanyForm, data=data) if form.validate_on_submit(): if not contact.id and Contact.query.filter( Contact.name == form.contact_name.data).count(): flash(_('Contact name "%s" is already in use.' % form.contact_name.data), 'danger') return render_template('company/create.htm', company=company, form=form) if not contact.id and Contact.query.filter( Contact.email == form.contact_email.data).count(): flash(_('Contact email "%s" is already in use.' % form.contact_email.data), 'danger') return render_template('company/create.htm', company=company, form=form) contact.name = form.contact_name.data contact.email = form.contact_email.data contact.phone_nr = form.contact_phone_nr.data # Create or update to contact db.session.add(contact) db.session.commit() # Create or update to location location.city = form.location_city.data location.country = form.location_country.data location.address = form.location_address.data location.zip = form.location_zip.data location.postoffice_box = form.location_postoffice_box.data location.email = form.location_email.data location.phone_nr = form.location_phone_nr.data db.session.add(location) db.session.commit() # if not company.id and Company.query.filter( Company.name == form.name.data).count(): flash(_('Name "%s" is already in use.' % form.name.data), 'danger') return render_template('company/edit.htm', company=company, form=form) company.name = form.name.data company.description = form.description.data company.contract_start_date = form.contract_start_date.data company.contract_end_date = form.contract_end_date.data company.location = location company.contact = contact company.website = form.website.data if request.files['file']: logo = request.files['file'] _file = file_service.add_file(FileCategory.COMPANY_LOGO, logo, logo.filename) company.logo_file = _file db.session.add(company) db.session.commit() flash(_('Company "%s" saved.' % company.name), 'success') return redirect(url_for('company.view', company_id=company.id)) else: flash_form_errors(form) return render_template('company/create.htm', company=company, form=form)
def create(form_id=None): if not ModuleAPI.can_write('custom_form') or current_user.is_anonymous: return abort(403) if form_id: custom_form = CustomForm.query.get_or_404(form_id) prev_max = custom_form.max_attendants else: custom_form = CustomForm() form = CreateForm(request.form, custom_form) if request.method == 'POST': custom_form.name = form.name.data custom_form.origin = form.origin.data custom_form.html = form.html.data custom_form.msg_success = form.msg_success.data custom_form.max_attendants = form.max_attendants.data if form.price.data is None: form.price.data = 0.0 custom_form.price = form.price.data custom_form.transaction_description = form.transaction_description.data custom_form.terms = form.terms.data follower = None if not form_id: follower = CustomFormFollower(owner_id=current_user.id) flash('You\'ve created a form successfully.', 'success') else: flash('You\'ve updated a form successfully.', 'success') cur_max = int(custom_form.max_attendants) # print("Current maximum: " + cur_max) # print("Previous maximum: " + prev_max) # print("Current submissions: " + len(all_sub)) if cur_max > prev_max: all_sub = CustomFormResult.query.filter( CustomFormResult.form_id == form_id ).all() # Update for users that were on the reserve list that they # can now attend. if prev_max < len(all_sub): for x in range(prev_max, max(cur_max, len(all_sub) - 1)): sub = all_sub[x] copernica_data = { "Reserve": "Nee" } copernica.update_subprofile( copernica.SUBPROFILE_ACTIVITY, sub.owner_id, sub.form_id, copernica_data) elif cur_max < prev_max: all_sub = CustomFormResult.query.filter( CustomFormResult.form_id == form_id ).all() if cur_max < len(all_sub): for x in range(cur_max, max(prev_max, len(all_sub) - 1)): sub = all_sub[x] copernica_data = { "Reserve": "Ja" } copernica.update_subprofile( copernica.SUBPROFILE_ACTIVITY, sub.owner_id, sub.form_id, copernica_data) db.session.add(custom_form) db.session.commit() if follower is not None: follower.form_id = custom_form.id db.session.add(follower) db.session.commit() return redirect(url_for('custom_form.view')) else: flash_form_errors(form) return render_template('custom_form/create.htm', form=form)
def edit(entry_id=None, parent_id=None): entry = NavigationEntry.query.get_or_404(entry_id) if entry_id else None form = init_form(NavigationEntryForm, obj=entry) form.page_id.choices = [(-1, '-- {} --'.format(_('Custom URL')))] + \ db.session.query(Page.id, Page.path).all() parent = NavigationEntry.query.get(parent_id) if parent_id else None if parent_id and not parent: flash(_('Cannot find parent navigation entry.'), 'danger') return redirect(url_for('navigation.view')) if form.validate_on_submit(): url = None if form.page_id.data == -1: url = form.url.data if not re.compile('^/').match(url): url = '/' + url page_id = None if form.page_id.data == -1 else form.page_id.data if entry: entry.nl_title = form.nl_title.data entry.en_title = form.en_title.data entry.url = url entry.page_id = page_id entry.external = form.external.data entry.activity_list = form.activity_list.data entry.order_children_alphabetically = \ form.order_children_alphabetically.data else: last_entry = NavigationEntry.query.filter_by(parent_id=None) \ .order_by(NavigationEntry.position.desc()).first() # If there is no parent position the new entry at the end of the # top level entry. position = (last_entry.position + 1) if last_entry else 0 entry = NavigationEntry(parent, form.nl_title.data, form.en_title.data, url, page_id, form.external.data, form.activity_list.data, position) db.session.add(entry) db.session.commit() flash(_('The navigation entry has been saved.'), 'success') if not page_id and not form.external.data: # Check if the page exists, if not redirect to create it path = form.url.data.lstrip('/') page = page_service.get_page_by_path(path) if url.rstrip('/') in get_all_routes(): return redirect(url_for('navigation.view')) if not page and form.url.data != '/': flash(_('The link refers to a page that does not exist, please' 'create the page!'), 'warning') return redirect(url_for('page.edit_page', path=path)) return redirect(url_for('navigation.view')) else: flash_form_errors(form) parents = NavigationEntry.query.filter_by(parent_id=None) if entry: parents = parents.filter(NavigationEntry.id != entry.id) return render_template('navigation/edit.htm', entry=entry, form=form, parents=parents.all())
def create(form_id=None): if form_id: custom_form = custom_form_service.get_form_by_form_id(form_id) prev_max = custom_form.max_attendants else: custom_form = CustomForm() form = init_form(CreateForm, obj=custom_form) if request.method == 'POST': custom_form.name = form.name.data custom_form.origin = form.origin.data custom_form.group = form.group.data custom_form.html = form.html.data custom_form.msg_success = form.msg_success.data custom_form.max_attendants = form.max_attendants.data custom_form.introductions = form.introductions.data if form.price.data is None: form.price.data = 0.0 custom_form.price = form.price.data custom_form.terms = form.terms.data custom_form.requires_direct_payment = form.requires_direct_payment.data if form_id: flash('You\'ve updated a form successfully.', 'success') cur_max = int(custom_form.max_attendants) # print("Current maximum: " + cur_max) # print("Previous maximum: " + prev_max) # print("Current submissions: " + len(all_sub)) if cur_max > prev_max: all_sub = CustomFormResult.query.filter( CustomFormResult.form_id == form_id ).all() # Update for users that were on the reserve list that they # can now attend. if prev_max < len(all_sub): for x in range(prev_max, min(cur_max, len(all_sub))): sub = all_sub[x] copernica_data = { "Reserve": "Nee" } copernica.update_subprofile( app.config['COPERNICA_ACTIVITEITEN'], sub.owner_id, sub.form_id, copernica_data) elif cur_max < prev_max: all_sub = CustomFormResult.query.filter( CustomFormResult.form_id == form_id ).all() if cur_max < len(all_sub): for x in range(cur_max, max(prev_max, len(all_sub) - 1)): sub = all_sub[x] copernica_data = { "Reserve": "Ja" } copernica.update_subprofile( app.config['COPERNICA_ACTIVITEITEN'], sub.owner_id, sub.form_id, copernica_data) db.session.add(custom_form) db.session.commit() if form_id is None: flash('You\'ve created a form successfully.', 'success') custom_form_service.follow_form( form=custom_form, user_id=current_user.id) return redirect(url_for('custom_form.view')) else: flash_form_errors(form) return render_template('custom_form/create.htm', form=form)
def edit_page(path=''): if not ModuleAPI.can_write('page'): return abort(403) page = Page.get_by_path(path) form = request.form if page: revision = page.get_latest_revision() # Add the `needs_paid` option to the revision, so it will be inside # the form. revision.needs_paid = revision.page.needs_paid form = PageForm(form, revision) else: form = PageForm() groups = Group.query.all() # on page submit (edit or create) if form.validate_on_submit(): # if there was no page we want to create an entire new page (and not # just a revision) if not page: page = Page(path) page.needs_paid = form['needs_paid'].data db.session.add(page) db.session.commit() custom_form_id = int(form.custom_form_id.data) if custom_form_id == 0: custom_form_id = None new_revision = PageRevision(page, form.nl_title.data.strip(), form.en_title.data.strip(), form.comment.data.strip(), current_user, form.nl_content.data.strip(), form.en_content.data.strip(), 'filter_html' in form, custom_form_id) db.session.add(new_revision) db.session.commit() # Enter permission in db for form_entry, group in zip(form.permissions, groups): permission_entry = PagePermission.query\ .filter(PagePermission.group_id == group.id, PagePermission.page_id == page.id).first() permission_level = form_entry.select.data if permission_entry: permission_entry.permission = permission_level else: permission_entry = PagePermission(group.id, page.id, permission_level) db.session.add(permission_entry) db.session.commit() flash(_('The page has been saved'), 'success') # redirect newly created page return redirect(url_for('page.get_page', path=path)) else: flash_form_errors(form) for group in groups: permission = None if page: permission = PagePermission.query\ .filter(PagePermission.group_id == group.id, PagePermission.page_id == page.id)\ .first() if permission: form.permissions\ .append_entry({'select': permission.permission}) else: form.permissions.append_entry({}) return render_template('page/edit_page.htm', page=page, form=form, path=path, groups=zip(groups, form.permissions))
def edit_course(course_id): r = request.args.get('redir') if r in REDIR_PAGES: session['origin'] = url_for(REDIR_PAGES[r]) elif r == 'edit' and 'examination_edit_id' in session: session['origin'] = '/examination/edit/{}'.format( session['examination_edit_id']) if not ModuleAPI.can_write('examination', True): session['prev'] = 'examination.edit_course' return abort(403) course = Course.query.get(course_id) if not course: flash(_('Course could not be found.'), 'danger') return redirect(url_for('examination.view_courses')) exam_count = Examination.query.filter(Examination.course == course).count() if 'delete' in request.args: if exam_count > 0: flash(_('Course still has examinations in the database.'), 'danger') form = CourseForm(title=course.name, description=course.description) return render_template('course/edit.htm', new=False, form=form, course=course, redir=r, exam_count=exam_count) Course.query.filter_by(id=course_id).delete() db.session.commit() flash(_('Course succesfully deleted.'), 'success') if 'origin' in session: redir = session['origin'] else: redir = url_for('examination.add') return redirect(redir) if request.method == 'POST': form = CourseForm(request.form) if form.validate_on_submit(): title = form.title.data if title != course.name and Course.query.filter( Course.name == title).count() >= 1: flash("'%s': " % title + _('Already exists in the database'), 'danger') return render_template('course/edit.htm', new=False, form=form, redir=r, course=course, exam_count=exam_count) else: description = form.description.data course.name = title course.description = description db.session.commit() flash(_('Course succesfully saved.'), 'success') if 'origin' in session: redir = session['origin'] else: redir = url_for('examination.add') return redirect(redir) else: flash_form_errors(form) else: form = CourseForm(title=course.name, description=course.description) return render_template('course/edit.htm', new=False, form=form, redir=r, course=course, exam_count=exam_count)
def edit(exam_id): if not ModuleAPI.can_write('examination', True): session['prev'] = 'examination.edit_examination' return abort(403) exam = Examination.query.get(exam_id) if not exam: flash(_('Examination could not be found.'), 'danger') return redirect(url_for('examination.view_examination')) session['examination_edit_id'] = exam_id form = EditForm(request.form, exam) courses = Course.query.order_by(Course.name).all() educations = Education.query.order_by(Education.name).all() form.course.choices = [(c.id, c.name) for c in courses] form.education.choices = [(e.id, e.name) for e in educations] form.test_type.choices = test_types.items() if request.method == 'POST': if form.validate_on_submit(): file = request.files['examination'] answers = request.files['answers'] exam.date = form.date.data exam.comment = form.comment.data exam.course_id = form.course.data exam.education_id = form.education.data exam.test_type = form.test_type.data new_path = upload_file_real(file, exam.path) if new_path: exam.path = new_path elif new_path is None: flash(_('Wrong format examination.'), 'danger') if not new_path: flash(_('Old examination preserved.'), 'info') new_answer_path = upload_file_real(answers, exam.answer_path) if new_answer_path: exam.answer_path = new_answer_path elif new_answer_path is None: flash(_('Wrong format answers.'), 'danger') if not new_answer_path: flash(_('Old answers preserved.'), 'info') db.session.commit() flash(_('Examination succesfully changed.'), 'success') return redirect(url_for('examination.edit', exam_id=exam_id)) else: flash_form_errors(form) path = '/static/uploads/examinations/' return render_template('examination/edit.htm', form=form, path=path, examination=exam, title=_('Examinations'), courses=courses, educations=educations, new_exam=False)
def edit_committee(committee=''): if not ModuleAPI.can_write('committee'): return abort(403) path = 'commissie/' + committee page = Page.get_by_path(path) form = request.form if page: revision = page.get_latest_revision() form = CommitteeForm(form, revision) else: revision = None form = CommitteeForm() try: url_group_id = int(request.args.get('group_id', None)) except: url_group_id = None form.group_id.choices = [(group.id, group.name) for group in Group.query.order_by(Group.name).all()] if len(request.form) == 0: if revision: selected_group_id = revision.group_id elif url_group_id is not None: selected_group_id = url_group_id else: selected_group_id = form.group_id.choices[0][0] else: selected_group_id = int(form.group_id.data) form.group_id.data = selected_group_id selected_group = Group.query.get(selected_group_id) form.coordinator_id.choices = [ (user.id, user.name) for user in selected_group.users.order_by(User.first_name, User.last_name).all()] form.nl_title.data = selected_group.name if form.validate_on_submit(): committee_nl_title = form.nl_title.data.strip() committee_en_title = form.en_title.data.strip() if not page: root_entry_url = url_for('committee.list').rstrip('/') root_entry = NavigationEntry.query\ .filter(NavigationEntry.url == root_entry_url)\ .first() # Check whether the root navigation entry exists. if not root_entry: last_root_entry = NavigationEntry.query\ .filter(NavigationEntry.parent_id == None)\ .order_by(NavigationEntry.position.desc()).first() # noqa root_entry_position = 1 if last_root_entry: root_entry_position = last_root_entry.position + 1 root_entry = NavigationEntry( None, 'Commissies', 'Committees', root_entry_url, False, False, root_entry_position) db.session.add(root_entry) db.session.commit() page = Page(path, 'committee') # Never needs paid. page.needs_paid = False # Create a navigation entry for the new committee. last_navigation_entry = NavigationEntry.query\ .filter(NavigationEntry.parent_id == root_entry.id)\ .first() entry_position = 1 if last_navigation_entry: entry_position = last_navigation_entry.position + 1 navigation_entry = NavigationEntry( root_entry, committee_nl_title, committee_en_title, '/' + path, False, False, entry_position) db.session.add(navigation_entry) db.session.commit() # Sort these navigation entries. NavigationAPI.alphabeticalize(root_entry) # Assign the navigation entry to the new page (committee). page.navigation_entry_id = navigation_entry.id db.session.add(page) db.session.commit() # Assign read rights to all, and edit rights to BC. all_group = Group.query.filter(Group.name == 'all').first() bc_group = Group.query.filter(Group.name == 'BC').first() all_entry = PagePermission(all_group.id, page.id, 1) bc_entry = PagePermission(bc_group.id, page.id, 2) db.session.add(all_entry) db.session.add(bc_entry) db.session.commit() else: # If the committee's title has changed, the navigation needs to be # updated. Look for the entry, compare the titles, and change where # necessary. entry = NavigationEntry.query\ .filter(NavigationEntry.url == '/' + path).first() if entry.title != committee_nl_title: entry.title = committee_nl_title db.session.add(entry) db.session.commit() group_id = int(form.group_id.data) coordinator_id = int(form.coordinator_id.data) # Add coordinator to BC bc_group = Group.query.filter(Group.name == "BC").first() if bc_group is not None: new_coordinator = User.query.filter( User.id == coordinator_id).first() bc_group.add_user(new_coordinator) new_revision = CommitteeRevision( page, committee_nl_title, committee_en_title, form.comment.data.strip(), current_user.id, form.nl_description.data.strip(), form.en_description.data.strip(), group_id, coordinator_id, form.interim.data) db.session.add(new_revision) db.session.commit() flash(_('The committee has been saved.'), 'success') return redirect(url_for('page.get_page', path=path)) else: flash_form_errors(form) return render_template('committee/edit.htm', page=page, form=form, path=path)
def create(activity_id=None): # Need to be logged in + actie group or admin etc. if not ModuleAPI.can_write('activity'): return abort(403) if activity_id: activity = Activity.query.get(activity_id) if not activity: abort(404) title = _("Edit") + " " + str(activity.name) else: activity = Activity() title = _('Create activity') form = CreateForm(request.form, activity) if request.method == 'POST': if form.validate_on_submit(): picture = activity.picture form.populate_obj(activity) file = request.files['picture'] if file.filename and allowed_file(file.filename): picture = secure_filename(file.filename) if not activity.picture and os.path.isfile( os.path.join('app/static/activity_pictures', picture)): flash(_('An image with this name already exists.'), 'danger') return render_template('activity/create.htm', activity=activity, form=form, title=title) fpath = os.path.join('app/static/activity_pictures', picture) file.save(fpath) os.chmod(fpath, 0o644) # Remove old picture if activity.picture: try: os.remove(os.path.join( 'app/static/activity_pictures', activity.picture)) except OSError: print(_('Cannot delete image, image does not exist') + ": " + str(activity.picture)) elif not picture: picture = None activity.venue = 1 # Facebook ID location, not used yet # noqa # Set a custom_form if it actually exists form_id = int(form.form_id.data) if form_id == 0: form_id = None activity.form_id = form_id activity.picture = picture activity.owner_id = current_user.id if activity.id and activity.google_event_id: flash(_('The activity has been edited.'), 'success') google.update_activity(activity.google_event_id, form.nl_name.data, form.nl_description.data, form.location.data, form.start_time.data.isoformat(), form.end_time.data.isoformat()) else: flash(_('The activity has been created.'), 'success') google_activity = google.insert_activity( form.nl_name.data, form.nl_description.data, form.location.data, form.start_time.data.isoformat(), form.end_time.data.isoformat()) if google_activity: activity.google_event_id = google_activity['id'] db.session.add(activity) db.session.commit() return redirect(url_for('activity.get_activity', activity_id=activity.id)) else: flash_form_errors(form) return render_template('activity/create.htm', activity=activity, form=form, title=title)
def edit_education(education_id): r = request.args.get('redir') if r in REDIR_PAGES: session['origin'] = url_for(REDIR_PAGES[r]) elif r == 'edit' and 'examination_edit_id' in session: session['origin'] = '/examination/edit/{}'.format( session['examination_edit_id']) if not ModuleAPI.can_write('examination', True): session['prev'] = 'examination.edit_education' return abort(403) education = Education.query.get(education_id) if not education: flash(_('Education could not be found.'), 'danger') return redirect(url_for('examination.view_educations')) exam_count = Examination.query.filter( Examination.education == education).count() if 'delete' in request.args: if exam_count > 0: flash(_('Education still has examinations in the database.'), 'danger') form = CourseForm(title=education.name) return render_template('education/edit.htm', new=False, form=form, education=education, redir=r, exam_count=exam_count) Education.query.filter_by(id=education_id).delete() db.session.commit() flash(_('Education succesfully deleted.'), 'success') if 'origin' in session: redir = session['origin'] else: redir = url_for('examination.add') return redirect(redir) if request.method == 'POST': form = EducationForm(request.form) if form.validate_on_submit(): name = form.title.data if name != education.name and Education.query.filter( Education.name == name).count() >= 1: flash("'%s': " % name + _('Already exists in the database'), 'danger') return render_template('education/edit.htm', new=False, form=form, redir=r, exam_count=exam_count, education=education) else: education.name = name db.session.commit() flash("'%s': " % name + _('Education succesfully saved.'), 'success') if 'origin' in session: redir = session['origin'] else: redir = url_for('examination.view_educations') return redirect(redir) else: flash_form_errors(form) else: form = CourseForm(title=education.name) return render_template('education/edit.htm', new=False, form=form, redir=r, exam_count=exam_count, education=education)
def edit(entry_id=None, parent_id=None): if not ModuleAPI.can_read('navigation'): return abort(403) if entry_id: entry = db.session.query(NavigationEntry)\ .filter_by(id=entry_id).first() if not entry: return abort(404) else: entry = None form = NavigationEntryForm(request.form, entry) if parent_id: parent = NavigationEntry.query.filter_by(id=parent_id).first() if not parent: flash(_('Cannot find parent navigation entry.'), 'danger') return redirect(url_for('navigation.view')) if form.validate_on_submit(): url = form.url.data if not re.compile('^/').match(url): url = '/' + url if entry: entry.nl_title = form.nl_title.data entry.en_title = form.en_title.data entry.url = url entry.external = form.external.data entry.activity_list = form.activity_list.data else: # If there is no parent position the new entry at the end of the # top level entry. if not parent_id: parent = None last_entry = db.session.query(NavigationEntry)\ .filter_by(parent_id=None)\ .order_by(NavigationEntry.position.desc()).first() position = last_entry.position + 1 else: last_entry = db.session.query(NavigationEntry)\ .filter_by(parent_id=parent_id)\ .order_by(NavigationEntry.position.desc()).first() if last_entry: position = last_entry.position + 1 else: position = 0 entry = NavigationEntry(parent, form.nl_title.data, form.en_title.data, url, form.external.data, form.activity_list.data, position) db.session.add(entry) db.session.commit() flash(_('The navigation entry has been saved.'), 'success') if not form.external.data: # Check if the page exists, if not redirect to create it path = form.url.data.lstrip('/') page = Page.get_by_path(path) if url.rstrip('/') in get_all_routes(): return redirect(url_for('navigation.view')) if not page and form.url.data != '/': flash(_('The link refers to a page that does not exist, please' 'create the page!'), 'warning') return redirect(url_for('page.edit_page', path=path)) return redirect(url_for('navigation.view')) else: flash_form_errors(form) parents = db.session.query(NavigationEntry).filter_by(parent_id=None) if entry: parents = parents.filter(NavigationEntry.id != entry.id) parents = parents.all() return render_template('navigation/edit.htm', entry=entry, form=form, parents=parents)
def edit(user_id=None): """Create user for admins and edit for admins and users.""" if not ModuleAPI.can_write('user') and\ (current_user.is_anonymous or current_user.id != user_id): return abort(403) # Select user if user_id: user = User.query.get_or_404(user_id) else: user = User() user.avatar = UserAPI.has_avatar(user_id) if ModuleAPI.can_write('user'): form = EditUserForm(request.form, user) is_admin = True else: form = EditUserInfoForm(request.form, user) is_admin = False # Add education. educations = Education.query.all() form.education_id.choices = [(e.id, e.name) for e in educations] def edit_page(): return render_template('user/edit.htm', form=form, user=user, is_admin=is_admin) if form.validate_on_submit(): # Only new users need a unique email. query = User.query.filter(User.email == form.email.data) if user_id: query = query.filter(User.id != user_id) if query.count() > 0: flash(_('A user with this e-mail address already exist.'), 'danger') return edit_page() # Because the user model is constructed to have an ID of 0 when it is # initialized without an email adress provided, reinitialize the user # with a default string for email adress, so that it will get a unique # ID when committed to the database. if not user_id: user = User('_') group = Group.query.filter(Group.name == 'all').first() group.add_user(user) try: user.update_email(form.email.data.strip()) except HttpError as e: if e.resp.status == 404: flash(_('According to Google this email does not exist. ' 'Please use an email that does.'), 'danger') return edit_page() raise(e) user.first_name = form.first_name.data.strip() user.last_name = form.last_name.data.strip() user.locale = form.locale.data if ModuleAPI.can_write('user'): user.has_paid = form.has_paid.data user.honorary_member = form.honorary_member.data user.favourer = form.favourer.data user.disabled = form.disabled.data user.alumnus = form.alumnus.data user.student_id = form.student_id.data.strip() user.education_id = form.education_id.data user.birth_date = form.birth_date.data user.study_start = form.study_start.data user.receive_information = form.receive_information.data user.phone_nr = form.phone_nr.data.strip() user.address = form.address.data.strip() user.zip = form.zip.data.strip() user.city = form.city.data.strip() user.country = form.country.data.strip() if form.password.data != '': user.password = bcrypt.hashpw(form.password.data, bcrypt.gensalt()) db.session.add(user) db.session.add(group) db.session.commit() avatar = request.files['avatar'] if avatar: UserAPI.upload(avatar, user.id) if user_id: copernica.update_user(user) flash(_('Profile succesfully updated')) else: copernica.update_user(user, subscribe=True) flash(_('Profile succesfully created')) return redirect(url_for('user.view_single', user_id=user.id)) else: flash_form_errors(form) return edit_page()
def add(): if not ModuleAPI.can_write('examination', True): session['prev'] = 'examination.add' return abort(403) form = EditForm(request.form, ) courses = Course.query.order_by(Course.name).all() educations = Education.query.order_by(Education.name).all() form.course.choices = [(c.id, c.name) for c in courses] form.education.choices = [(e.id, e.name) for e in educations] form.test_type.choices = test_types.items() if request.method == 'POST': if form.validate_on_submit(): file = request.files.get('examination', None) answers = request.files.get('answers', None) error = False filename = upload_file_real(file) if file: if not filename: flash(_('Wrong format examination.'), 'danger') error = True answer_path = upload_file_real(answers) if answer_path is False: flash(_('No answers uploaded.'), 'warning') answer_path = None elif answer_path is None: flash(_('Wrong format answers.'), 'danger') error = True else: flash(_('No examination uploaded.'), 'danger') error = True if error: dummy_exam = Examination(filename, form.date.data, form.comment.data, form.course.data, form.education.data, test_type=form.test_type.data) return render_template('examination/edit.htm', courses=courses, educations=educations, examination=dummy_exam, form=form, test_types=test_types, new_exam=False) exam = Examination(filename, form.date.data, form.comment.data, form.course.data, form.education.data, answers=answer_path, test_type=form.test_type.data) db.session.add(exam) db.session.commit() flash(_('Examination successfully uploaded.'), 'success') return redirect(url_for('examination.edit', exam_id=exam.id)) else: flash_form_errors(form) return render_template('examination/edit.htm', courses=courses, educations=educations, new_exam=True, form=form)
def edit_permissions(group_id, page_nr=1): if not (ModuleAPI.can_read("group")): return abort(403) group = Group.query.filter(Group.id == group_id).first() if not group: flash("There is no group with id {}".format(group_id), "danger") return redirect(url_for("group.view")) permissions = ( GroupPermission.query.order_by(GroupPermission.module_name).filter(GroupPermission.group_id == group_id).all() ) form = EditGroupPermissionForm() # The app's blueprints are stored as a dict, with key # 'blueprint.name' and value '<Blueprint object>'. modules = list(app.blueprints.keys()) # Remove current permission. for permission in permissions: try: modules.remove(permission.module_name) except ValueError: continue form.add_module_name.choices = [("", "")] + list(zip(modules, modules)) if form.validate_on_submit(): for form_entry, permission in zip(form.permissions, permissions): if permission.permission != form_entry.select.data: permission.permission = form_entry.select.data db.session.add(permission) db.session.commit() # If a permission is empty, remove it. permissions_cpy = copy.copy(permissions) for permission in permissions_cpy: if permission.permission == 0: permissions.remove(permission) db.session.delete(permission) db.session.commit() if form.add_module_name.data: new_permission = GroupPermission(form.add_module_name.data, group_id, form.add_module_permission.data) db.session.add(new_permission) db.session.commit() flash("Permission for module %s created!" % (form.add_module_name.data)) return redirect(url_for("group.edit_permissions", group_id=group_id, page_nr=page_nr)) else: flash_form_errors(form) # add the permissions as drop down boxes for permission in permissions: data = {} data["select"] = permission.permission form.permissions.append_entry(data) return render_template( "group/edit_permissions.htm", form=form, can_write=ModuleAPI.can_write("group"), group_name=group.name, title="Module permissions", permissions=zip(permissions, form.permissions), )