def create_admin():
    if admin_exists():
        flash(gettext(
            u"Cannot access admin creation form if an admin user "
            u"already exists."), "error")
        return redirect(url_for('general_routes.home'))

    # If login token cookie from previous session exists, delete
    if request.cookies.get('remember_token'):
        response = clear_cookie_auth()
        return response

    form = flaskforms.CreateAdmin()
    if request.method == 'POST':
        if form.validate():
            username = form.username.data.lower()
            error = False
            if form.password.data != form.password_repeat.data:
                flash(gettext(u"Passwords do not match. Please try again."),
                      "error")
                error = True
            if not test_username(username):
                flash(gettext(
                    u"Invalid user name. Must be between 2 and 64 characters "
                    u"and only contain letters and numbers."),
                    "error")
                error = True
            if not test_password(form.password.data):
                flash(gettext(
                    u"Invalid password. Must be between 6 and 64 characters "
                    u"and only contain letters, numbers, and symbols."),
                      "error")
                error = True
            if error:
                return redirect(url_for('general_routes.home'))

            new_user = User()
            new_user.name = username
            new_user.email = form.email.data
            new_user.set_password(form.password.data)
            new_user.role = 1  # Admin
            new_user.theme = 'slate'
            try:
                db.session.add(new_user)
                db.session.commit()
                flash(gettext(u"User '%(user)s' successfully created. Please "
                              u"log in below.", user=username),
                      "success")
                return redirect(url_for('authentication_routes.do_login'))
            except Exception as except_msg:
                flash(gettext(u"Failed to create user '%(user)s': %(err)s",
                              user=username,
                              err=except_msg), "error")
        else:
            flash_form_errors(form)
    return render_template('create_admin.html',
                           form=form)
Beispiel #2
0
def add_user(admin=False):
    new_user = User()

    print('\nAdd user to database')

    while True:
        user_name = raw_input('User (a-z, A-Z, 2-64 chars): ').lower()
        if test_username(user_name):
            new_user.name = user_name
            break

    while True:
        user_password = getpass.getpass('Password: '******'Password (again): ')
        if user_password != user_password_again:
            print("Passwords don't match")
        else:
            if test_password(user_password):
                new_user.set_password(user_password)
                break

    while True:
        email = raw_input('Email: ')
        if is_email(email):
            new_user.email = email
            break

    if admin:
        new_user.role = 1
    else:
        new_user.role = 4

    new_user.theme = 'slate'
    try:
        with session_scope(MYCODO_DB_PATH) as db_session:
            db_session.add(new_user)
        sys.exit(0)
    except sqlalchemy.exc.OperationalError:
        print("Failed to create user.  You most likely need to "
              "create the DB before trying to create users.")
        sys.exit(1)
    except sqlalchemy.exc.IntegrityError:
        print("Username already exists.")
        sys.exit(1)
Beispiel #3
0
def user_add(form):
    action = '{action} {controller} {user}'.format(
        action=gettext("Add"),
        controller=gettext("User"),
        user=form.user_name.data.lower())
    error = []

    if form.validate():
        new_user = User()
        new_user.name = form.user_name.data.lower()
        if not test_username(new_user.name):
            error.append(
                gettext(
                    "Invalid user name. Must be between 2 and 64 characters "
                    "and only contain letters and numbers."))

        new_user.email = form.email.data
        if User.query.filter_by(email=new_user.email).count():
            error.append(
                gettext("Another user already has that email address."))

        if not test_password(form.password_new.data):
            error.append(
                gettext(
                    "Invalid password. Must be between 6 and 64 characters "
                    "and only contain letters, numbers, and symbols."))

        if form.password_new.data != form.password_repeat.data:
            error.append(gettext("Passwords do not match. Please try again."))

        if not error:
            new_user.set_password(form.password_new.data)
            role = Role.query.filter(Role.name == form.addRole.data).first().id
            new_user.role = role
            new_user.theme = form.theme.data
            try:
                new_user.save()
            except sqlalchemy.exc.OperationalError as except_msg:
                error.append(except_msg)
            except sqlalchemy.exc.IntegrityError as except_msg:
                error.append(except_msg)

        flash_success_errors(error, action,
                             url_for('routes_settings.settings_users'))
    else:
        flash_form_errors(form)
def create_admin():
    if admin_exists():
        flash(
            gettext("Cannot access admin creation form if an admin user "
                    "already exists."), "error")
        return redirect(url_for('routes_general.home'))

    # If login token cookie from previous session exists, delete
    if request.cookies.get('remember_token'):
        response = clear_cookie_auth()
        return response

    form_create_admin = forms_authentication.CreateAdmin()
    form_notice = forms_authentication.InstallNotice()

    if request.method == 'POST':
        form_name = request.form['form-name']
        if form_name == 'acknowledge':
            mod_misc = Misc.query.first()
            mod_misc.dismiss_notification = 1
            db.session.commit()
        elif form_create_admin.validate():
            username = form_create_admin.username.data.lower()
            error = False
            if form_create_admin.password.data != form_create_admin.password_repeat.data:
                flash(gettext("Passwords do not match. Please try again."),
                      "error")
                error = True
            if not test_username(username):
                flash(
                    gettext(
                        "Invalid user name. Must be between 2 and 64 characters "
                        "and only contain letters and numbers."), "error")
                error = True
            if not test_password(form_create_admin.password.data):
                flash(
                    gettext(
                        "Invalid password. Must be between 6 and 64 characters "
                        "and only contain letters, numbers, and symbols."),
                    "error")
                error = True
            if error:
                return redirect(url_for('routes_general.home'))

            new_user = User()
            new_user.name = username
            new_user.email = form_create_admin.email.data
            new_user.set_password(form_create_admin.password.data)
            new_user.role = 1  # Admin
            new_user.theme = 'slate'
            try:
                db.session.add(new_user)
                db.session.commit()
                flash(
                    gettext(
                        "User '%(user)s' successfully created. Please "
                        "log in below.",
                        user=username), "success")
                return redirect(url_for('routes_authentication.do_login'))
            except Exception as except_msg:
                flash(
                    gettext("Failed to create user '%(user)s': %(err)s",
                            user=username,
                            err=except_msg), "error")
        else:
            utils_general.flash_form_errors(form_create_admin)

    dismiss_notification = Misc.query.first().dismiss_notification

    return render_template('create_admin.html',
                           dismiss_notification=dismiss_notification,
                           form_create_admin=form_create_admin,
                           form_notice=form_notice)