def createdb(): """Create a new empty database with a single administrator.""" print("* Creating database schema") # Create the database schema db.create_all() print("* Adding alembic stamp") # Create alembic_version table migrations_directory = current_app.extensions['migrate'].directory config = alembic.config.Config( os.path.join(migrations_directory, 'alembic.ini')) config.set_main_option('script_location', migrations_directory) alembic.command.stamp(config, "head") # Add required groups print("* Adding administrators' and 'BC' groups") _add_group('administrators') _add_group('BC') # Add educations, which must be present to create the administrator user print("* Adding educations") education_names = [ "BSc Informatica", "BSc Kunstmatige Intelligentie", "BSc Informatiekunde", "MSc Information Studies", "MSc Software Engineering", "MSc System and Network Engineering", "MSc Artificial Intelligence", "MSc Logic", "MSc Computational Science", "MSc Computer Science", "MSc Medical Informatics", "MSc Grid Computing", "Other", "Minor programmeren", "Minor Informatica", "Minor Kunstmatige Intelligentie"] for name in education_names: if not Education.query.filter(Education.name == name).first(): db.session.add(Education(name=name)) else: print("-> Education {} exists".format(name)) db.session.commit() # Add some default navigation print("* Adding default navigation entries") navigation_entries = [ ('via', 'via', '/via', False, [ ('Nieuws', 'News', '/news/', False, []), ('PimPy', 'PimPy', '/pimpy', False, []), ('Commissies', 'Committees', '/commissie', False, []), ('Admin', 'Admin', '/admin', False, [ ('Navigatie', 'Navigation', '/navigation', False, []), ('Formulieren', 'Forms', '/forms', False, []), ('Redirect', 'Redirect', '/redirect', False, []), ('Users', 'Users', '/users', False, []), ('Groups', 'Groups', '/groups', False, []), ('Files', 'Files', '/files', False, []) ]), ]), ('Activiteiten', 'Activities', '/activities', True, [ ('Activiteiten Archief', 'Activities archive', '/activities/archive', False, []), ('Activiteiten Overzicht', 'Activities overview', '/activities/view', False, []) ]), ('Vacatures', 'Vacancies', '/vacancies/', False, []), ('Tentamenbank', 'Examinations', '/examination', False, []), ('Samenvattingen', 'Summaries', '/summary', False, []) ] _add_navigation(navigation_entries) print("* Adding administrator user") first_name = prompt("\tFirst name") last_name = prompt("\tLast name") email_regex = re.compile("^[^@]+@[^@]+\.[^@]+$") while True: email = prompt("\tEmail") if email_regex.match(email): break print("\tInvalid email address: " + email) while True: passwd_plain = prompt_pass("\tPassword") passwd_plain_rep = prompt_pass("\tRepeat password") if passwd_plain == passwd_plain_rep: break print("\tPasswords do not match") passwd = bcrypt.hashpw(passwd_plain.encode('utf-8'), bcrypt.gensalt()) admin = User( first_name=first_name, last_name=last_name, email=email, password=passwd, education_id=Education.query.first().id) admin.has_paid = True _add_user(admin, "A user with email '{}' already exists".format(email)) # Add admin user to administrators group admin_group = Group.query.filter_by(name='administrators').first() admin_group.add_user(admin) db.session.commit() roles = [] for role in Roles: group_role = GroupRole() group_role.group_id = admin_group.id group_role.role = role.name roles.append(group_role) # Grant read/write privilege to administrators group on every module db.session.bulk_save_objects(roles) db.session.commit() print("* Adding default settings") settings = {'SECRET_KEY': 'localsecret', "CSRF_ENABLED": "True", "CSRF_SESSION_KEY": "localsession", "RECAPTCHA_PUBLIC_KEY": "", "RECAPTCHA_PRIVATE_KEY": "", "GOOGLE_SERVICE_EMAIL": "*****@*****.**", "GOOGLE_CALENDAR_ID": "", "ELECTIONS_NOMINATE_START": "2014-12-12", "ELECTIONS_VOTE_START": "2015-01-05", "ELECTIONS_VOTE_END": "2015-01-16", "GITLAB_TOKEN": "", "MOLLIE_URL": "https://api.mollie.nl/v1/payments/", "MOLLIE_KEY": "", "COPERNICA_ENABLED": "False", "COPERNICA_API_KEY": "", "COPERNICA_DATABASE_ID": "", "COPERNICA_ACTIEPUNTEN": "", "COPERNICA_ACTIVITEITEN": "", "COPERNICA_NEWSLETTER_TOKEN": "", "DOMJUDGE_ADMIN_USERNAME": "******", "DOMJUDGE_ADMIN_PASSWORD": "", "DOMJUDGE_URL": "", "DOMJUDGE_USER_PASSWORD": "", "SENTRY_DSN": "DUMMY", "ENVIRONMENT": "Development", "PRIVACY_POLICY_URL_EN": "/static/via_privacy_policy_nl.pdf", "PRIVACY_POLICY_URL_NL": "/static/via_privacy_policy_en.pdf"} for key, value in settings.items(): if Setting.query.filter(Setting.key == key).count() > 1: print(f"-> {key} already exists") else: db.session.add(Setting(key=key, value=value)) print(f"-> {key} added to database.") db.session.commit() print("Done!")
def edit(user_id, form_cls): """ Create user for admins and edit for admins and users. User and form type are passed based on routes below. """ if user_id: user = user_service.get_user_by_id(user_id) user.avatar = user_service.user_has_avatar(user_id) else: user = User() form = init_form(form_cls, obj=user) form.new_user = user.id == 0 # Add education. educations = Education.query.all() form.education_id.choices = [(e.id, e.name) for e in educations] def edit_page(): is_admin = role_service.user_has_role(current_user, Roles.USER_WRITE) 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('_') # TODO Move this into the service call. 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 # Note: student id is updated separately. user.first_name = form.first_name.data.strip() user.last_name = form.last_name.data.strip() user.locale = form.locale.data if role_service.user_has_role(current_user, Roles.USER_WRITE): 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.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() db.session.add(user) db.session.commit() avatar = request.files.get('avatar') if avatar: user_service.set_avatar(user.id, avatar) if user_id: copernica.update_user(user) flash(_('Profile succesfully updated')) else: copernica.update_user(user, subscribe=True) flash(_('Profile succesfully created')) if current_user.id == user_id: return redirect(url_for('user.view_single_self')) else: return redirect(url_for('user.view_single_user', user_id=user.id)) return edit_page()