예제 #1
0
def edit_user(user_id):
    if g.user.role != 0:
        return abort(403)
    if user_id != 1:
        user = User.query.filter_by(id=user_id).first()
        form = EditUserForm(user.username,user.name,user.password,user.role)
        if form.validate_on_submit():
            user.name = form.name.data
            user.username = form.username.data
            user.password = form.password.data
            user.role = form.role.data
            rows = User.query.filter_by(id=user_id).update({
                    'name': user.name,
                    'username': user.username,
                    'password': generate_password_hash(user.password),
                    'role': user.role
                    })
            db.session.commit()
            return redirect(url_for('index'))
        elif request.method != "POST":
            form.name.data = user.name
            form.username.data = user.username
            form.password.data = user.password
            form.role.data = user.role
        return render_template('edit_user.html', form=form)
    else:
        return abort(403)
예제 #2
0
파일: routes.py 프로젝트: zhmaylovv/bets
def edituser(username):

    form = EditUserForm()
    user = User.query.filter_by(username=username).first_or_404()
    posts = [{'author': user, 'body': 'Test post #1'},
            {'author': user, 'body': 'Test post #2'}]
    avatar = base64.b64encode ( user.avatar ).decode ( 'ascii' )

    if form.validate_on_submit():
        if form.password.data:
            user.set_password(form.password.data)
        if form.email.data:
            user.email=form.email.data
        if form.fio.data:
            user.fio=form.fio.data
        if form.photo.data:
            f = form.photo.data
            if form.photo.data.content_type.split('/')[0] != 'image' and form.photo.data.content_length > 1024:

                flash('Small image only plz')
                return redirect(url_for('edituser'))

            user.avatar = f.stream.read()
        db.session.commit()
        flash('Edit ok')
        return redirect(url_for('index'))
    return render_template('edituser.html', user=user, posts=posts, avatar= avatar, form=form)
예제 #3
0
def user(slug):
    """View and edit the profile of a user.

    **Route:** ``/admin/user/<slug>``

    **Methods:** ``GET, POST``
    """
    try:
        user = User.objects().get(slug=slug)
    except DoesNotExist:
        flash("Invalid user slug '{}'".format(slug), ERROR_FLASH)
        return redirect(url_for('.index'))

    form = EditUserForm(
        request.form,
        name=user.name,
        email=user.email,
        # image_url=user.get_profile_picture(),
        user_type=user.user_type)
    if request.method == 'POST':
        if form.validate_on_submit():
            user.name = form.name.data
            user.email = form.email.data
            user.user_type = form.user_type.data
            # user.image_url = form.image_url.data
            user.save()
            return redirect(url_for('.index'))
        else:
            flash("Your Form had errors: {}".format(form.errors), ERROR_FLASH)

    return render_template('admin/users/user.html',
                           user=user,
                           form=form,
                           current_user=g.user)
예제 #4
0
파일: routes.py 프로젝트: wujiahui62/XCEL
def user(username):
    form = EditUserForm()
    user = User.query.filter_by(email=username).first_or_404()
    members = Member.query.filter_by(account_id=user.id)
    count = members.count()
    if form.validate_on_submit():
        member = request.form.get('member')
        if member is not None:
            global first_name
            global last_name
            first_name, last_name = member.split(" ")
            if form.edit.data:
                return redirect(url_for('edit_profile'))
            elif form.delete.data:
                member = Member.query.filter_by(fname=first_name,
                                                lname=last_name,
                                                account=current_user).first()
                db.session.delete(member)
                db.session.commit()
                first_name = None
                last_name = None
                flash('The member was deleted!')
                return redirect(url_for('index'))
    return render_template('user.html',
                           user=user,
                           members=members,
                           form=form,
                           count=count)
예제 #5
0
def user(slug):
    """"""
    try:
        user = User.objects().get(slug=slug)
    except DoesNotExist:
        flash("Invalid user slug '%s'" % slug)
        return redirect(url_for('.index'))

    form = EditUserForm(
        request.form,
        name=user.name,
        email=user.email,
        # image_url=user.get_profile_picture(),
        user_type=user.user_type)
    if request.method == 'POST':
        if form.validate_on_submit():
            user.name = form.name.data
            user.email = form.email.data
            user.user_type = form.user_type.data
            # user.image_url = form.image_url.data
            user.save()
            return redirect(url_for('.index'))
        else:
            flash("Your Form had errors: %s" % (form.errors))

    return render_template('admin/users/user.html',
                           user=user,
                           form=form,
                           current_user=g.user)
예제 #6
0
def edit_user(user_id):
    if g.user.role != 0:
        return abort(403)
    if user_id != 1:
        user = User.query.filter_by(id=user_id).first()
        form = EditUserForm(user.username, user.name, user.password, user.role)
        if form.validate_on_submit():
            user.name = form.name.data
            user.username = form.username.data
            user.password = form.password.data
            user.role = form.role.data
            rows = User.query.filter_by(id=user_id).update({
                'name':
                user.name,
                'username':
                user.username,
                'password':
                generate_password_hash(user.password),
                'role':
                user.role
            })
            db.session.commit()
            return redirect(url_for('index'))
        elif request.method != "POST":
            form.name.data = user.name
            form.username.data = user.username
            form.password.data = user.password
            form.role.data = user.role
        return render_template('edit_user.html', form=form)
    else:
        return abort(403)
예제 #7
0
def edit_user():
    form = EditUserForm()
    if form.validate_on_submit():
        current_user.user_about_me = form.user_about_me.data
        current_user.user_name = form.user_name.data
        current_user.user_email = form.user_email.data
        current_user.user_password = generate_password_hash(
            form.user_password.data)
        current_user.user_department = form.user_department.data
        current_user.user_grade = form.user_grade.data

        try:
            with dbHelper.get_session() as session:
                session.commit()

        except Exception as e:
            abort(500)

        flash('Your changes have been saved.')
        return redirect(url_for('user', user_id=current_user.user_id))

    form.user_id.data = current_user.user_id or ''
    form.user_email.data = current_user.user_email
    form.user_name.data = current_user.user_name
    form.user_about_me.data = current_user.user_about_me
    form.user_department.data = current_user.user_department
    form.user_grade.data = str(current_user.user_grade)

    return render_template('edit_user.html', form=form)
예제 #8
0
def update_user():
    """
    Update user information
    """
    form = EditUserForm()
    form['csrf_token'].data = request.cookies['csrf_token']
    if form.validate_on_submit():
        user = User.query.get(current_user.id)
        try:
            user.username = form.data['username'],
            user.email = form.data['email'],
            if form.data['password']:
                user.hashed_password = generate_password_hash(
                    form.data['password']),
            user.user_avatar = form.data['avatar'],
            user.user_background = form.data['background'],
            user.user_bio = form.data['bio']
        except Exception as err:
            print(f'{err.__class__.__name__}: {err}')
            return {'errors': ['Sorry, cannot process your request']}, 400
        else:
            db.session.add(user)
            db.session.commit()
            return user.to_dict()
    return {'errors': validation_errors_to_error_messages(form.errors)}, 400
예제 #9
0
def edit_user(request):
    '''
    '''

    data = {}
    
    if request.method == "POST":
        form = EditUserForm(request.POST)
        if form.is_valid():
            changes = form.cleaned_data
            profile = UserProfile.objects.get(user_id=request.user.id)
            user = authenticate(username=profile.user.username, password=changes['current_password'])
            if user is not None:
                if changes['new_password'] != '':
                    profile.user.set_password(changes['new_password'])
                    profile.user.save()
                if changes['email'] != '':
                    profile.user.email = changes['email']
                    profile.user.save()
                if changes['location']:
                    profile.location = changes['location']
                    profile.save()
                return HttpResponseRedirect('/user/%d' % profile.id)
            else:
                data = errors('Invalid password Supplied', data)
                return HttpResponse(json.dumps(data), content_type="application/json")
    else:
        form = EditUserForm()

    return render(request, 'app/settings.html', {'form': form})
예제 #10
0
파일: users.py 프로젝트: Howon/eventum
def user(slug):
    """View and edit the profile of a user.

    **Route:** ``/admin/user/<slug>``

    **Methods:** ``GET, POST``
    """
    try:
        user = User.objects().get(slug=slug)
    except DoesNotExist:
        flash("Invalid user slug '{}'".format(slug))
        return redirect(url_for('.index'))

    form = EditUserForm(request.form,
                        name=user.name,
                        email=user.email,
                        # image_url=user.get_profile_picture(),
                        user_type=user.user_type)
    if request.method == 'POST':
        if form.validate_on_submit():
            user.name = form.name.data
            user.email = form.email.data
            user.user_type = form.user_type.data
            # user.image_url = form.image_url.data
            user.save()
            return redirect(url_for('.index'))
        else:
            flash("Your Form had errors: {}".format(form.errors))

    return render_template('admin/users/user.html', user=user, form=form,
                           current_user=g.user)
예제 #11
0
파일: routes.py 프로젝트: jubuc/jubuc
def edit_user(username):
    user = db.session.query(User).filter_by(username=username).first_or_404()
    form = EditUserForm()

    if request.method == "GET":
        form.username.data = user.username
        form.email.data = user.email
        form.first_name.data = user.first_name
        form.last_name.data = user.last_name
        form.bio.data = user.bio
        form.facebook.data = user.facebook
        form.twitter.data = user.twitter

    if form.validate_on_submit():
        user.email = form.email.data
        user.first_name = form.first_name.data
        user.last_name = form.last_name.data
        user.bio = form.bio.data
        user.facebook = form.facebook.data
        user.twitter = form.twitter.data

        db.session.add(user)
        db.session.commit()
        message = Markup(
            '<div class="alert alert-success alert-dismissible"><button type="button" class="close" data-dismiss="alert">&times;</button> User {} settings saved</div>'
            .format(user.username))
        flash(message)
        return redirect(url_for('admin_users'))

    return render_template('admin/user_edit.html', form=form, user=user)
예제 #12
0
def edit(id):
    if id != None:
        user = mongo.db.user.find_one({'_id': ObjectId(id)})
        form = EditUserForm()
        form.city.choices = [('Bangalore', 'Bangalore'),
                             ('Chennai', 'Chennai'),
                             ('Mangalore', 'Mangalore')]
        #form.submit = SubmitField('Update')

        if form.validate_on_submit():
            new_user = {
                'name': form.name.data,
                'age': form.age.data,
                'city': form.city.data,
                'mobile': form.mobile.data
            }
            mongo.db.user.update_one({'_id': ObjectId(id)}, {'$set': new_user})
            flash('%s Updated successfully!' % (new_user['name']), 'success')
            return redirect(url_for('index'))
        elif request.method == 'GET':
            form.name.data = user['name']
            form.age.data = user['age']
            form.city.data = user['city']
            form.mobile.data = user['mobile']
        return render_template('edit.html', title='Edit User', form=form)
    else:
        return redirect(url_for('index'))
예제 #13
0
def user(slug):
    """"""
    try:
        user = User.objects().get(slug=slug)
    except DoesNotExist:
        flash("Invalid user slug '%s'" % slug)
        return redirect(url_for('.index'))

    form = EditUserForm(request.form,
                        name=user.name,
                        email=user.email,
                        # image_url=user.get_profile_picture(),
                        user_type=user.user_type)
    if request.method == 'POST':
        if form.validate_on_submit():
            user.name = form.name.data
            user.email = form.email.data
            user.user_type = form.user_type.data
            # user.image_url = form.image_url.data
            user.save()
            return redirect(url_for('.index'))
        else:
            flash("Your Form had errors: %s" % (form.errors))

    return render_template('admin/users/user.html', user=user, form=form,
                           current_user=g.user)
예제 #14
0
def admin_edit_user(user_id):
    user = User.query.filter_by(id=user_id).first_or_404()
    form = EditUserForm(original_username=user.username, original_email=user.email, original_id=user.id)

    if form.validate_on_submit():
        if form.username.data:
            user.username = form.username.data
        if form.email.data and user.email != form.email.data:
            user.email = form.email.data
        if form.firstname.data:
            user.firstname = form.firstname.data
        if form.lastname.data:
            user.lastname = form.lastname.data
        if form.contact.data:
            user.contact = form.contact.data
        if form.address.data:
            user.address = form.address.data
        if form.sex.data:
            user.sex = form.sex.data
        if form.access_level.data:
            user.access_level = form.access_level.data
        if form.password.data:
            user.set_password(form.password.data)
            
        db.session.commit()
        flash('Successfully saved!')
        return redirect(url_for('student_management', page_num=1))

    return render_template('./admin_templates/admin_edit_user.html', title="Edit user- Admin Dashboard page", form=form, user=user)
예제 #15
0
def route_edit_user():
    form = EditUserForm()
    user = current_user
    #user = User.query.filter_by(id=user_id).first_or_404()
    if form.validate_on_submit():
        shortname = form.shortname.data.upper()
        sn_user = User.query.filter_by(shortname=shortname).first()
        if sn_user is not None and sn_user.id != user.id:
            flash('That shortname is already taken')
            return redirect(url_for('route_edit_user', user_id=user.id))
        nn_user = User.query.filter_by(nickname=form.nickname.data).first()
        if nn_user is not None and nn_user != user:
            flash('That nickname is already taken')
            return redirect(url_for('route_edit_user', user_id=user.id))
        tasks.update_user(
            user=user,
            shortname=shortname,
            nickname=form.nickname.data,
            #password=form.password.data,
        )
        flash(f'User {user} updated')
        return redirect(url_for('user', user_id=user.id))
    elif request.method == 'GET':
        form.shortname.data = user.shortname
        form.nickname.data = user.nickname
    return render_template('edit_user.html', title='Edit User', form=form)
예제 #16
0
def user_edit(id):
    form = EditUserForm()
    form.user_type.choices = make_select_list(Config.USER_TYPE)

    r = requests.get('http://192.168.1.109:10100/users/{}'.format(id),
                     verify=False)
    retdata = r.json() or {}
    if 'error' in retdata:
        flash('An Error Occored:{}'.format(retdata['message']))
        return redirect(url_for('index'))

    if form.validate_on_submit():
        if form.username.data != retdata['username']:
            tr = requests.get('http://192.168.1.109:10100/uniq/{}'.format(
                form.username.data),
                              verify=False)
            if 'error' in tr.json():
                flash('Please use a different username.')
                return render_template('edit_user.html',
                                       title='Edit User',
                                       form=form,
                                       userid=id)

        if form.email.data != retdata['email']:
            tr = requests.get('http://192.168.1.109:10100/uemail/{}'.format(
                form.email.data),
                              verify=False)
            if 'error' in tr.json():
                flash('Please use a different email.')
                return render_template('edit_user.html',
                                       title='Edit User',
                                       form=form,
                                       userid=id)

        user = {
            'username': form.username.data,
            'email': form.email.data,
            'mac_address': form.mac_address.data or "",
            'role': form.user_type.data
        }
        r = requests.put('http://192.168.1.109:10100/users/{}'.format(id),
                         json=user,
                         verify=False)
        retdata = r.json() or {}
        if 'error' in retdata:
            flash('An Error Occored:{}'.format(retdata['message']))
        return redirect(url_for('admin_user'))
    elif request.method == 'GET':
        form.user_type.data = retdata['role']
        form.username.data = retdata['username']
        form.email.data = retdata['email']
        form.mac_address.data = retdata['mac_address'] or ""
    return render_template('edit_user.html',
                           title='Edit User',
                           form=form,
                           userid=id)
예제 #17
0
def edit_user(user_id):
    """ Обработчик для изменения информации о пользователе """

    session = db_session.create_session()
    user = get_user(session, user_id)

    form = EditUserForm()
    if request.method == "GET":  # Загрузка информации в поля ввода
        form.avatar.data = f'static/img/users_img/{user.img}.jpg'
        form.nickname.data = user.nickname
        form.status.data = user.status
        form.sex.data = user.sex
        form.education.data = user.education
        form.marital_status.data = user.marital_status
        form.birthday.data = user.birthday.date() if user.birthday != dt(
            1800, 1, 1) else None
        form.about_me.data = user.about_me

    if form.validate_on_submit():  # Обновление информации у пользователя
        user.nickname = form.nickname.data
        user.status = form.status.data or 'Не указано'
        user.sex = form.sex.data
        user.education = form.education.data or 'Не указано'
        user.marital_status = form.marital_status.data
        user.about_me = form.about_me.data or 'Не указано'
        try:  # Установление даты рождения у пользователя
            user.birthday = dt.strptime(form.birthday.data, '%Y-%m-%d')
        except ValueError:
            user.birthday = dt(
                1800, 1,
                1)  # Заглушка, для сокрытия даты рождения пользователя

        if form.remove_birthday.data:  # События для сокрытия даты
            user.birthday = dt(1800, 1, 1)

        if form.avatar.data:  # Если выбран аватар пользователя
            if user.img != 'default':
                try:  # Если изображение не стандартное, то пытаемся удалить старое
                    os.remove(f'static/img/users_img/{user.img}.jpg')
                except FileNotFoundError:
                    print_warning(
                        f'File not found: static/img/users_img/{user.img}.jpg')

            # Создание нового аватара
            filename = str(uuid.uuid4())  # Генерация случайного имени файла
            request.files['avatar'].save(
                f'static/img/users_img/{filename}.jpg')
            user.img = filename
            #

        session.commit()

        return redirect(url_for('home_page', user_id=current_user.id))

    return render_template("edit_user.html", title='Редактирование', form=form)
예제 #18
0
 def post(self, request, *args, **kwargs):
     user = User.objects.filter(username=self.kwargs['username']).first()
     profile = Profile.objects.filter(user=user).first()
     user_form = EditUserForm(request.POST, instance=user)
     profile_form = EditProfileForm(request.POST, instance=profile)
     if user_form.is_valid() and profile_form.is_valid():
         user_form = user_form.save()
         custom_form = profile_form.save(False)
         custom_form.user = user_form
         custom_form.save()
         return redirect('user', username=user.username)
     return render(request, self.template_name, args)
예제 #19
0
def user_edit():
    form = EditUserForm(g.user.username)
    if form.validate_on_submit():
        g.user.username = form.username.data
        g.user.about_me = form.about_me.data
        db.session.add(g.user)
        db.session.commit()
        flash('Your changes have been saved.')
        return redirect(url_for('user_edit'))
    else:
        form.username.data = g.user.username
        form.about_me.data = g.user.about_me
    return render_template('user_edit.html',
                           form=form)
예제 #20
0
def edit_profile():
    form = EditUserForm()
    if form.validate_on_submit():
        # Update
        current_user.username = form.username.data
        current_user.email = form.email.data
        db.session.commit()
        flash('Edit User Success!')
        return redirect(url_for('edit_profile'))
    elif request.method == 'GET':
        # lấy data ra
        form.username.data = current_user.username
        form.email.data = current_user.email
    return render_template('edit_profile.html', title='Edit Profile', form=form)
예제 #21
0
def edit_user(userid):
    if current_user.permission_level is not 2:
        return redirect(url_for('index'))
    user = User.query.filter_by(id=userid).first_or_404()
    form = EditUserForm()

    if form.validate_on_submit():
        user.permission_level = form.permission_level.data
        db.session.commit()
        flash('User Updated')
        return redirect(url_for('view_user', userid=user.id))

    return render_template('edit_user.html',
                           title='Edit User',
                           user=user,
                           form=form)
예제 #22
0
def edit_user():
    form = EditUserForm()
    if form.validate_on_submit():
        current_user.year = form.year.data
        current_user.major = form.major.data
        current_user.save()
        flash('Successfully updated user details', 'success')
    elif request.method == 'GET':
        form.year.default = current_user.year
        form.major.default = current_user.major
        form.process()
    dept_by_major = Major.get_department_mapping()
    dept_by_major['None'] = 'None'
    return render_template('edit_user.html',
                           form=form,
                           dept_by_major=dept_by_major)
def user_info():
    query_form = QueryUserForm()
    edit_form = EditUserForm()
    if edit_form.submit2.data:
        vip = 'edit_form'
    else:
        vip = 'query_form'
    if query_form.submit1.data and query_form.validate_on_submit():
        tmp = 'query_profile'
        tmp += ' -c ' + str(current_user.username)
        tmp += ' -u ' + str(query_form.username.data)
        print(tmp)
        # 通信
        ret = 'User1 Nick1 [email protected] 10'
        ret = com(tmp)
        print(ret)
        if ret == '-1':
            flash('用户名不存在或权限不足!', category='danger')
            return redirect(url_for('user_info'))
        ret = ret.split()
        return render_template('user_info.html', query_form=query_form, info_post=ret, edit_form=edit_form,
                               vip=vip)

    if edit_form.submit2.data and edit_form.validate_on_submit():
        tmp = 'modify_profile '
        tmp += ' -c ' + str(current_user.username)
        tmp += ' -u ' + str(edit_form.username.data)
        if edit_form.password.data:
            tmp += ' -p ' + str(edit_form.password.data)
        if edit_form.name.data:
            tmp += ' -n ' + str(edit_form.name.data)
        if edit_form.email.data:
            tmp += ' -m ' + str(edit_form.email.data)
        if edit_form.privilege.data:
            tmp += ' -g ' + str(edit_form.privilege.data)
        print(tmp)
        # 通信
        ret = 'User1 Nick1 [email protected] 10'
        ret = com(tmp)
        if ret == '-1':
            flash('修改失败!', category='warning')
        else:
            flash('修改成功!', category='success')
        return render_template('user_info.html', query_form=query_form, info_post=None, edit_form=edit_form,
                               vip=vip)

    return render_template('user_info.html', query_form=query_form, info_post=None, edit_form=edit_form, vip=vip)
예제 #24
0
def admin_edituser():
    if(current_user.is_admin() == False):
        return "Access Denied"
    form=EditUserForm()
    if form.validate_on_submit():
        form.validate()
        #Check if user exists in database and can be modified
        present = User.query.filter_by(username=form.old_username.data).first()
        if present is None:
            flash("Error: This user does not exist in the database")
            return render_template("admin-edit.html", form=form)
        old_user = form.old_username.data
        #delete record from database unless it is the admin account or the current user
        if (form.delete.data) == True:
            if form.old_username.data == "admin":
                flash("Error: This user cannot be removed from the database")
                return render_template("admin-edit.html", form=form)
            elif current_user.username == old_user:
                flash("Error: Cannot delete the user currently signed in.")
                return render_template("admin-edit.html", form=form)
            else:
                User.query.filter_by(username=form.old_username.data).delete()
        #begin editing record
        if old_user:
            user=User.query.filter_by(username=form.old_username.data).first()
        else:
            flash("Error: No user selected for editing")
            return render_template("admin-edit.html", form=form)
        if old_user == "admin":
            flash("Error: Cannot modify admin!")
            return render_template("admin-edit.html", form=form)
        new_user = form.new_username.data
        if new_user:
            user.username = form.new_username.data
        new_password = form.password_confirm.data
        if new_password:
            user.set_password(form.password.data)
        email =  form.email.data
        if email:
            user.email=form.email.data
        admin=form.admin.data
        if admin:
            user.admin=form.admin.data  
        db.session.commit()
        flash("User succesfully modified")
        return redirect(url_for('admin'))
    return(render_template('admin-edit.html', form=form))
예제 #25
0
 def get(self, request, *args, **kwargs):
     user = User.objects.filter(username=self.kwargs['username']).first()
     profile = Profile.objects.filter(user=user).first()
     user_form = EditUserForm(instance=user)
     profile_form = EditProfileForm(instance=profile)
     args = {}
     args['user_form'] = user_form
     args['profile_form'] = profile_form
     return render(request, self.template_name, args)
예제 #26
0
def delete_user(user_id):
    if g.user.role != 0:
        return abort(403)
    if user_id != 1:
        user = User.query.filter_by(id=user_id).first()
        form = EditUserForm(user.username,user.name,user.password,user.role)
        if form.validate_on_submit():
            rows = User.query.filter_by(id=user_id).delete()
            db.session.commit()
            return redirect(url_for('index'))
        elif request.method != "POST":
            form.name.data = user.name
            form.username.data = user.username
            form.password.data = user.password
            form.role.data = user.role
        return render_template('delete_user.html', form=form)
    else:
        return abort(403)
예제 #27
0
def delete_user(user_id):
    if g.user.role != 0:
        return abort(403)
    if user_id != 1:
        user = User.query.filter_by(id=user_id).first()
        form = EditUserForm(user.username, user.name, user.password, user.role)
        if form.validate_on_submit():
            rows = User.query.filter_by(id=user_id).delete()
            db.session.commit()
            return redirect(url_for('index'))
        elif request.method != "POST":
            form.name.data = user.name
            form.username.data = user.username
            form.password.data = user.password
            form.role.data = user.role
        return render_template('delete_user.html', form=form)
    else:
        return abort(403)
예제 #28
0
def edit_user():
    """edit user information"""

    form = EditUserForm(obj=g.user)

    if form.validate_on_submit():

        user = User.authenticate(g.user.email, form.current_password.data)

        if user:

            try:
                user.first_name = form.first_name.data
                user.last_name = form.last_name.data
                user.email = form.email.data
                user.department = form.department.data
                user.image_url = form.image_url.data
                user.current_role_id = form.current_role_id.data
                db.session.commit()

                if user.current_role.role == "stocker":
                    if user.get_stocker is None:
                        stocker = Stocker(user_id=user.id)
                        db.session.add(stocker)
                        db.session.commit()

                elif user.current_role.role == "forklift_driver":
                    if user.get_driver is None:
                        forklift_driver = ForkliftDriver(user_id=user.id)
                        db.session.add(forklift_driver)
                        db.session.commit()

                flash("Profile successfully updated", "success")
                return redirect(f"/users/{user.id}")
            except IntegrityError:
                flash("Email is already in use", "danger")
                return redirect("/users/settings")
        else:
            flash("invalid password", "danger")
            return redirect("/users/settings")

    return render_template("/edit.html", form=form)
예제 #29
0
def user():
    form = EditUserForm()
    if current_user.is_authenticated:

        if request.method == 'POST':
            print('POST')
            if form.validate_on_submit():
                user = User.query.filter_by(_id=current_user._id).first()
                if form.email.data:
                    user.email = form.email.data
                if form.username.data:
                    user.username = form.username.data
                db.session.commit()
                login_user(user, remember=True)
            return redirect(url_for('user'))

        form.email.data = current_user.email
        form.username.data = current_user.username
        return render_template('user.html', form=form)
    return redirect(url_for('login'))
예제 #30
0
def edit_user():
    form = EditUserForm()
    if form.validate_on_submit():
        current_user.user_email = form.user_email.data
        current_user.user_name = form.user_name.data

        try:
            with dbHelper.get_session() as session:
                session.commit()

        except Exception as e:
            abort(500)

        flash('Your changes have been saved.')
        return redirect(url_for('user'))

    form.user_email.data = current_user.user_email or ''
    form.user_name.data = current_user.user_name

    return render_template('editUser.html', form=form)
예제 #31
0
def edit_user(user):
    u = User.query.filter_by(username=user).first()
    adm = User.query.filter_by(username=current_user.username)
    form = EditUserForm(u.username, u.email)
    if form.validate_on_submit() and adm[0].permissions == 'admin':
        u.username = unidecode.unidecode(form.username.data)
        u.email = form.email.data
        if form.permis.data != 'selecione':
            u.permissions = form.permis.data
        if form.status.data != 'selecione':
            u.status = form.status.data
        db.session.commit()
        flash('Alterações realizadas com sucesso.')
        return redirect(url_for('admin'))
    elif request.method == 'GET':
        form.username.data = u.username
        form.email.data = u.email
        form.status.data = u.status
        form.permis.data = u.permissions
    return render_template('edit_users.html', user=u, form=form)
예제 #32
0
def edit_user_view(request, user_id):
    user = User.objects.get(id=user_id)
    form = EditUserForm(user, request.POST or None)
    if form.is_valid():
        full_name = form.cleaned_data['full_name']
        birth_day = form.cleaned_data['birth_day']
        phone = form.cleaned_data['phone']
        middle_name = form.cleaned_data['middle_name']
        email = form.cleaned_data['email']
        user.full_name = full_name
        user.birth_day = birth_day
        user.phone = phone
        user.middle_name = middle_name
        user.email = email
        user.save()
        return HttpResponseRedirect('/edit_user/'+str(user.id)+'/')

    context = {
        'user': user,
        'form': form
    }
    return render(request, 'edit_user.html', context)
예제 #33
0
def edit(request):
    user = request.user
    if request.method == 'GET':
        return render(request, 'profile/edit.html', {
            'form': EditUserForm(instance=user)
        })

    elif request.method == 'POST':
        form = EditUserForm(request.POST, instance=user)
        if form.is_valid():
            user = form.save(commit=False)
            errors = []
            if user.passport_date > today():
                errors.append('Дата выдачи паспорта из будущего')
            if user.get_age() < 18:
                errors.append('Пользователю не исполнилось 18')
            if user.get_age() > 150:
                errors.append('Пользователь слишком стар')
            if user.passport_date < user.birthday:
                errors.append('Паспорт выдан до рождения')
            if errors:
                for error in errors:
                    request.user.alert(error)
                return render(request, 'profile/edit.html', {
                    'form': EditUserForm(request.POST)
                })
            else:
                form.save()
                request.user.alert('Данные сохранены.')
                return redirect('profile:info')
        else:
            err = str(form.errors) + ""
            if err.find('phone') >= 0:
                request.user.alert('Пользователь с таким номером телефона уже зарегестрирован')
            if err.find('passport_id') >= 0:
                request.user.alert('Пользователь с таким номером паспорта уже зарегестрирован')
            if err.find('passport_ser') >= 0:
                request.user.alert('Пользователь с такой серией паспорта уже зарегестрирован')
            if err.find('username') >= 0:
                request.user.alert('Пользователь с таким логином уже зарегестрирован')
            return render(request, 'profile/edit.html', {
                'form': EditUserForm(request.POST)
            })
예제 #34
0
def admin():
    if not current_user.isAdmin == 1:
        return redirect(url_for('index'))
    else:
        add_user_form = AddUser()
        edit_user_form = EditUserForm()
        delete_user_form = DeleteUserForm()
        if add_user_form.add_user_submit.data and add_user_form.validate():
            user = User(username=add_user_form.username.data,
                        name=add_user_form.name.data,
                        isAdmin=False)
            db.session.add(user)
            db.session.commit()
            flash("User added.", "success")
            return redirect(url_for('admin'))

        edit_user_form.update_choices()
        if edit_user_form.edit_submit.data and edit_user_form.validate():
            user = User.query.filter_by(
                username=edit_user_form.username.data).first()
            if user is None:
                flash("Unable to find username in database", "danger")
                return redirect(url_for("admin"))
            if edit_user_form.name.data != "":
                user.name = edit_user_form.name.data
                db.session.commit()
                edit_user_form.update_choices()
                flash("User details updated.", "success")
                return redirect(url_for("admin"))
            if edit_user_form.password.data != "":
                if edit_user_form.password.data == edit_user_form.password2.data:
                    print(edit_user_form.password.data)
                    user.set_password(edit_user_form.password.data)
                    db.session.commit()
                    flash("User details updated.", 'success')
                    return redirect(url_for('admin'))
                else:  #password field not empty but password wrong
                    flash("Password does not match!", "danger")
                    return redirect(url_for('admin'))

        delete_user_form.update_choices()
        if delete_user_form.delete_submit.data and delete_user_form.validate():
            user = User.query.filter_by(
                username=delete_user_form.username.data).first()
            db.session.delete(user)
            db.session.commit()
            flash("User deleted", "success")
            return redirect(url_for("admin"))
        return render_template('admin.html',
                               add_user_form=add_user_form,
                               edit_user_form=edit_user_form,
                               delete_user_form=delete_user_form)
예제 #35
0
def info(request):
    return render(request, 'profile/info.html', {
        'form': EditUserForm(instance=request.user)
    })