def add_user(email, password, roles, admin_first_run=False): """ Add a new user. :param email: email of the new user :type email: str :param password: password of the new user :type password: str :param roles: site roles the new user should have :type roles: list or tuple :param admin_first_run: if first run, automatically set the user "confirmed_at" field :type admin_first_run: bool """ email_test = _DummyEmailField(email) email_validator = Email() try: email_validator(None, email_test) except ValidationError: print("Email is invalid") sys.exit(2) with current_app.app_context(): if User.query.filter_by(email=email).first(): print("User already exists") sys.exit(2) fullname = email.split("@")[0] if admin_first_run: user_datastore.create_user(email=email, password=encrypt_password(password), fullname=fullname, confirmed_at=datetime.now()) else: user_datastore.create_user(email=email, password=encrypt_password(password), fullname=fullname) try: db.session.commit() except exc.IntegrityError: db.session.rollback() raise AddUserError("User already exists") for role in roles: role_obj = user_datastore.find_role(role) if role_obj: user_datastore.add_role_to_user(email, role_obj) try: db.session.commit() except exc.IntegrityError: db.session.rollback() raise AddUserError("User roles not added correctly")
def new(): """ Create new user :return: HTML view of users :rtype: jinja2.Template """ user_form = UserForm(request.form) if user_form.validate_on_submit(): user_email = user_form.email.data user_password = encrypt_password(user_form.password.data) uid = user_datastore.create_user(email=user_email, password=user_password, fullname=user_form.fullname.data, active=user_form.active.data) for role in user_form.roles.data: user_datastore.add_role_to_user(user_email, role.name) db.session.commit() flash("User added successfully", "success") return redirect(url_for("users.profile", user_id=uid.id)) return render_template("users/new.html", form=user_form)