Beispiel #1
0
def updateUser(email):
    updateUserForm = UpdateUserForm(request.form)

    if request.method == 'POST' and updateUserForm.validate():

        userDict = {}
        db = shelve.open('storage.db', 'w')
        try:
            userDict = db['Users']
        except:
            print("Error in retrieving User from storage.db")
        user = userDict.get(email)
        user.set_firstName(updateUserForm.firstName.data)
        user.set_lastName(updateUserForm.lastName.data)
        user.set_gender(updateUserForm.gender.data)
        user.set_email(updateUserForm.email.data)
        userDict[email] = user
        db['Users'] = userDict

        db.close()

        return redirect(url_for('retrieveUsers'))
    else:
        userDict = {}
        db = shelve.open('storage.db', 'r')
        userDict = db['Users']
        db.close()
        user = userDict.get(email)
        updateUserForm.firstName.data = user.get_firstName()
        updateUserForm.lastName.data = user.get_lastName()
        updateUserForm.gender.data = user.get_gender()
        updateUserForm.email.data = user.get_email()

        return render_template('updateUser.html', form=updateUserForm)
Beispiel #2
0
def update_user(user_id):
    curr_user = User.query.get_or_404(user_id)
    if current_user.id != curr_user.id:
        flash("Access unauthorized.", "danger")
        return redirect("/login")
    form = UpdateUserForm()
    if form.validate_on_submit():
        user = User.authenticate(form.username.data, form.password.data)
        if user:
            try:
                curr_user.avatar_url = form.avatar_url.data or curr_user.avatar_url
                curr_user.email = form.email.data or curr_user.email
                if form.new_password.data:
                    hashed_pass = bcrypt.generate_password_hash(
                        form.new_password.data).decode('UTF-8')
                    curr_user.password = hashed_pass or curr_user.password
                db.session.add(curr_user)
                db.session.commit()
                flash("Your account was updated successfully!", "success")
                return redirect(f'/my-lists/{curr_user.id}')
            except IntegrityError:
                db.session.rollback()
                flash("Email is associated with another account", 'danger')
        else:
            flash("Invalid credentials.", 'danger')
    return render_template('update-user.html', form=form)
def change_user(user_id):
    changed_user = User.query.get_or_404(user_id)
    form = UpdateUserForm()
    if form.validate_on_submit():
        changed_user.username = form.username.data
        changed_user.group_id = form.group.data.id
        changed_user.group = form.group.data.name
        db.session.commit()
        flash('User updated successfully', 'success')
        return redirect(url_for('users.user_page'))
    elif request.method == "GET":
        form.username.data = changed_user.username
        form.group.data = changed_user.group_id
    return render_template('chage_user.html', form=form, title=title)
Beispiel #4
0
def edit_profile(request):
    user_profile =  request.user
    #form = UpdateProfileForm(instance=user_profile)
    if request.POST:
        form = UpdateUserForm(request.POST,instance=user_profile)
        if form.is_valid():

            form.save()
            return HttpResponseRedirect('/account/edit')
        else:
            return HttpResponseRedirect('/')

    form = UpdateUserForm(instance=user_profile)

    return render(request, 'accounts/edit.html', {'form': form})
Beispiel #5
0
def update_user():
    username = current_user.get_id()
    user = User.query.filter_by(username=username)

    form = UpdateUserForm(obj=user.first())
    if form.validate_on_submit():
        existing_user = User.query.filter_by(email=form.email.data).first()
        if form.email.data != user.first().email and existing_user:
            return abort(401, description="Email already registered")
        else:
            data = {
                "first_name": form.first_name.data,
                "last_name": form.last_name.data,
                "dob": form.dob.data,
                "mobile": form.mobile.data,
                "city": form.city.data,
                "country": form.country.data
            }
            fields = user_schema.load(data, partial=True)
            user.update(fields)
            db.session.commit()
            flash("Account updated!")
            return redirect(url_for("web_users.get_user"))
    return render_template("user_update.html", form=form, user=user)


# @web_users.route("/account/delete", methods=["POST"])
# @login_required
# def delete_user():
#     form = DeleteButton()
#     if form.submit.data:
#         username = current_user.get_id()
#         user = User.query.filter_by(username=username)

#         profiles = Profile.query.filter_by(user_id=user.user_id)
#         for profile in profiles:
#             while len(profile.unrecommend) > 0:
#                 for item in profile.unrecommend:
#                     profile.unrecommend.remove(item)
#                 db.session.commit()

#         db.session.delete(user)
#         db.session.commit()
#         logout_user()
#         flash("Account deleted")
#         return redirect(url_for("web_users.web_users_login"))
#     return redirect(url_for("web_users.get_user"))
Beispiel #6
0
def update_user_route():
    before_route_load()

    if not sesh.confirm_logged_in():
        return redirect(url_for('login_route'))

    found_user = user.find_by_id(ObjectId(sesh.get_user_id()))

    if not found_user:
        return redirect(url_for('login_route'))

    form = UpdateUserForm()

    if request.method == 'GET':
        form.email.data = found_user.get('email', '')

    if request.method == 'POST':
        if form.validate():

            email = form.email.data

            ## additional validation
            ## validate unique email
            email_found = user.find_by_email(email)
            email_in_use = False
            if email_found and email_found.get("_id") != ObjectId(
                    sesh.get_user_id()):
                email_in_use = True
                flash("That email is already being used.", 'error')

            ## if no addtional validation errors:
            if not email_in_use:

                # update the user's email
                if user.update_user(_id=ObjectId(sesh.get_user_id()),
                                    email=email):
                    flash("User updated!", 'message')
                    return redirect(url_for('dashboard_route'))
                else:
                    flash("Nothing changed.", 'message')

    return render_template('update_user.html',
                           sesh=sesh,
                           user=found_user,
                           form=form,
                           page_title='Update User')
Beispiel #7
0
def profile():
    """Update profile for current user."""

    user = g.user
    form = UpdateUserForm(username=user.username,
                          email=user.email,
                          bio=user.bio)

    if form.validate_on_submit():

        if User.authenticate(user.username, form.password.data):
            update_user_with_form_data(user, form)
            db.session.commit()
        else:
            flash('Could not authenticate - please try again.', 'danger')

        return redirect(f'users/{user.id}')

    return render_template('users/edit.html', form=form, user=user)
Beispiel #8
0
def change_user(user_id):
    changed_user = get_filtered_by_id_users(user_id)[0]
    changed_name = changed_user[1]
    form = UpdateUserForm()
    if form.validate_on_submit():
        changed_user.name = changed_name
        changed_user.email = form.email.data
        changed_user.phone = form.phone.data
        changed_user.mobile_phone = form.mobile_phone.data
        changed_user.status = form.status.data
        flash('User updated successfully', 'success')
    elif request.method == "GET":
        form.name.data = changed_user[1]
        form.email.data = changed_user[2]
        form.phone.data = changed_user[3]
        form.mobile_phone.data = changed_user[4]
        form.status.data = changed_user[5]
        form.courses.choices = [(course[0], course[1]) for course in get_all_courses()]
    return render_template('chage_user.html', form=form, title=title)
Beispiel #9
0
def profile():
    """Update profile for current user."""
    if not g.user:
        flash("Must be logged in to do that", "danger")
        return redirect("/login")
    user = g.user
    form = UpdateUserForm(obj=user)
    if form.validate_on_submit():
        if User.authenticate(user.username, form.password.data):
            user.username = form.username.data
            user.email = form.email.data
            user.image_url = form.image_url.data
            user.header_image_url = form.header_image_url.data
            user.bio = form.bio.data
            db.session.commit()
            return redirect(f"/users/{user.id}")
        flash("Incorrect Password", "danger")
        return render_template("users/edit.html", form=form, user=user)
    else:
        return render_template("users/edit.html", form=form, user=user)
Beispiel #10
0
def update_user():
    user_id = current_user.get_id()
    user = User.query.filter_by(user_id=user_id)

    form = UpdateUserForm(obj=user.first())
    if form.validate_on_submit():
        existing_user = User.query.filter_by(email=form.email.data).first()
        if form.email.data != user.first().email and existing_user:
            return abort(401, description="Email already registered")
        else:
            data = {
                "email": form.email.data,
                "subscription_status": form.subscription_status.data
            }
            fields = user_schema.load(data, partial=True)
            user.update(fields)
            db.session.commit()
            flash("Account updated!")
            return redirect(url_for("web_users.get_user"))
    return render_template("user_update.html", form=form, user=user)
Beispiel #11
0
def edit_profile(id):
    """Update profile for current user."""

    user = User.query.get_or_404(g.user.id)
    form = UpdateUserForm(obj=user)

    if not g.user:
        flash("Access unauthorized.", "danger")
        return redirect("/")

    if form.validate_on_submit():
        user.username = form.username.data
        user.email = form.email.data
        user.image_url = form.image_url.data
        user.header_image_url = form.header_image_url.data
        user.location = form.location.data
        user.bio = form.bio.data
        db.session.commit()
        return redirect(f"/users/{id}")
    else:
        return render_template("users/edit.html", user=user, form=form)
Beispiel #12
0
def profile():
    """Update profile for current user."""

    user = g.user
    form = UpdateUserForm(obj=user)

    if form.validate_on_submit():
        if User.authenticate(user.username, form.password.data):
            user.username = form.username.data
            user.email = form.email.data
            user.image_url = form.image_url.data or "/static/images/default-pic.png"
            user.header_image_url = form.header_image_url.data or "/static/images/warbler-hero.jpg"
            user.bio = form.bio.data
            user.location = form.location.data

            db.session.commit()
            return redirect(f"/users/{user.id}")

        flash("Incorrect password. Try again", 'danger')

    return render_template('users/edit.html', form=form)
Beispiel #13
0
def update():
    if 'logged_in' in session:
        form = UpdateUserForm()
        current_user = getUser()
        if request.method == 'GET':  # fill in form with information in database
            form.first_name.data = current_user.firstName
            form.last_name.data = current_user.lastName
            form.username.data = current_user.username
            form.email.data = current_user.email
            form.addr_street.data = current_user.addr_street
            form.addr_city.data = current_user.addr_city
            form.addr_state.data = current_user.addr_state
            form.addr_zip.data = current_user.addr_zip
        elif request.method == 'POST':
            if form.validate_on_submit():
                currentUsername = session['username']
                firstName = form.first_name.data
                lastName = form.last_name.data
                username = form.username.data
                email = form.email.data
                addr_street = form.addr_street.data
                addr_city = form.addr_city.data
                addr_state = form.addr_state.data
                addr_zip = form.addr_zip.data
                cursor = conn.cursor()
                update = 'UPDATE user SET fName=%s, lName=%s, username=%s, email=%s, \
                    addr_street=%s, addr_city=%s, addr_state=%s, addr_zip=%s WHERE username=%s'
                cursor.execute(update, (firstName, lastName, username, email, addr_street,
                    addr_city, addr_state, addr_zip, currentUsername))
                session['username'] = username
                conn.commit()
                cursor.close()
                flash('Your account has been successfully updated!', 'success')  
                return redirect(url_for('update'))
            else:
                flash('Please check the errors below.', 'danger')

        return render_template('edit.html', title='Edit Account', form=form, current_user=current_user, isLoggedin=True)
    else:
        return redirect(url_for('home'))
Beispiel #14
0
def update(request):
	userip = request.POST['userip']
	if request.method == 'POST':
	    	uf = UpdateUserForm(request.POST)
	    	if uf.is_valid():
			username = request.POST['username']
			password = request.POST['password']
			userauth = request.POST['userauth']
			user = User.objects.get(userip=userip)
			if user:
				user.username = username
				user.password = password
				user.userauth = userauth
				user.save()
				addlog(request.session.get('userip',''),'用户更新')
				return HttpResponseRedirect(reverse('usermanage'))
			else:
				addlog(request.session.get('userip',''),'数据库没有该用户')
				return render_to_response('update.html',{'uf':uf,'userip':ip,'username':username})
	else:
        	uf = UpdateUserForm()
        	addlog(request.session.get('userip',''),'用户更新失败')
        	return HttpResponseRedirect(reverse('usermanage'))
    	return render_to_response('update.html',{'uf':uf})
Beispiel #15
0
def admin():
    form = AddUserForm(prefix="form")
    formUpdate = UpdateUserForm(prefix="formUpdate", idUser='******')
    u = Users.query.order_by(Users.id).all()
    formDelete = DeleteUserForm(prefix="formDelete")
    if form.validate_on_submit() and form.submit.data:
        a.createUser(session['author_id'], session['session_id'], form.login.data, form.email.data, form.password.data, form.admin.data)
    elif request.method == 'POST' and form.validate() == False and not formUpdate.submit.data and not formDelete.submit.data:
        flash("Error during the user creation!")
    if formUpdate.validate_on_submit() and formUpdate.submit.data:
        if formUpdate.idUser.data == '0':
            formUpdate.idUser.data = session['author_id']
        a.updatePassword(session['author_id'], session['session_id'], int(formUpdate.idUser.data), formUpdate.oldPassword.data, formUpdate.password.data)
    if formDelete.validate_on_submit() and formDelete.submit.data:
        a.getUserByName(session['author_id'], session['session_id'], formDelete.name.data)
        time.sleep(1)
        u = Users.query.filter_by(name = formDelete.name.data).all()
        if not u:
            flash("User not found or the server don't send the user information!")
        else:
            u = u[0]
            print formDelete.password.data
            a.delUser(session['author_id'], session['session_id'], u.id, formDelete.password.data)
    return render_template('admin.html', form=form, formUpdate=formUpdate,u = u, formDelete=formDelete)
Beispiel #16
0
    def edit_user(user_id):
        u = User.query.get(user_id)

        if u is None:
            flash('User not found!')
            return redirect(url_for('index'))

        form = UpdateUserForm()

        if request.method == 'POST':
            if u.name != form.username.data:
                u.name = form.username.data
            if len(form.passw.data) > 0:
                u.set_password(form.passw.data)
            db.session.commit()
            return redirect(url_for('edit_user', user_id=user_id))
        else:
            form.username.data = u.name
            return render_template('login/edit.html', form=form, u=u)
Beispiel #17
0
def change_user_details():
    form = UpdateUserForm(request.form)
    if request.method == "POST":
        try:
            print(f"User {form} \n")
            current_user.update(email=request.form['email'],
                                first_name=request.form['first_name'],
                                last_name=request.form['last_name'])
            if isinstance(current_user, CompanyUser):
                current_user.update(company_name=request.form['company_name'])
            current_user.save()
            response = jsonify(url_for('account'))
            response.status_code = 200
            print(f"changed details response {response}\n")
            return response
        except Exception as e:
            raise Exception(
                f"Error {e}. \n Couldn't change the details of the user,\n with following form: {form}"
            )
Beispiel #18
0
def admin_user():

    create_form = CreateUserForm()
    create_form.roles.query = Role.query.all()

    delete_form = DeleteUserForm()
    delete_form.users.query = User.query.all()

    update_form = UpdateUserForm()
    update_form.users.query = User.query.all()
    update_form.roles.query = Role.query.all()

    if request.method == 'POST':
        if create_form.data['create'] and create_form.validate():
            form = create_form
            user = User.query.filter_by(user_id=form.create_id.data).first()
            role = form.roles.data

            if user == None:
                user = User(user_id=form.create_id.data,
                            user_name=form.create_name.data)
                user.password = '******'
                user.role = role

            db.session.add(user)
            db.session.commit()

            session['status'] = u'success'
            flash(u'成功添加登录用户信息!')
            return redirect(url_for('admin_user'))
        elif delete_form.data['delete'] and delete_form.validate():
            form = delete_form
            user = form.users.data

            db.session.delete(user)
            db.session.commit()

            session['status'] = u'warning'
            flash(u'成功删除登录用户信息!')
            return redirect(url_for('admin_user'))
        elif update_form.data['update'] and update_form.validate():
            form = update_form
            user = form.users.data
            role = form.roles.data
            name = form.update_name.data
            password = form.update_passwd.data
            user.role = role

            if password != '':
                user.password = password
            elif name != '':
                user.user_name = name

            db.session.add(user)
            db.session.commit()

            session['status'] = u'info'
            flash(u'成功修改登录用户信息!')
            return redirect(url_for('admin_user'))

    return render_template('admin-user.html',
                           create_form=create_form,
                           delete_form=delete_form,
                           update_form=update_form)
Beispiel #19
0
def admin_user():

    create_form = CreateUserForm()
    create_form.roles.query = Role.query.all()

    delete_form = DeleteUserForm()
    delete_form.users.query = User.query.all()

    update_form = UpdateUserForm()
    update_form.users.query = User.query.all()
    update_form.roles.query = Role.query.all()

    if request.method == 'POST':
        if create_form.data['create'] and create_form.validate():
            form = create_form
            user = User.query.filter_by(user_id=form.create_id.data).first()
            role = form.roles.data
            
            if user == None:
                user = User(
                    user_id=form.create_id.data,
                    user_name=form.create_name.data)
                user.password = '******'
                user.role = role

            db.session.add(user)
            db.session.commit()
            
            status = u'success'
            message = u'成功添加登录用户'
            session['message']=messages(status, message)
            return redirect(url_for('admin'))
        elif delete_form.data['delete'] and delete_form.validate():
            form = delete_form
            user = form.users.data
            
            db.session.delete(user)
            db.session.commit()
            
            status = u'warning'
            message = u'成功删除登录用户'
            session['message']=messages(status, message)
            return redirect(url_for('admin'))
        elif update_form.data['update'] and update_form.validate():
            form = update_form
            user = form.users.data
            role = form.roles.data
            name = form.update_name.data
            password = form.update_passwd.data
            user.role = role
            
            if password != '':
                user.password = password
            elif name != '':
                user.user_name = name
            
            db.session.add(user)
            db.session.commit()
            
            status = u'info'
            message = u'成功修改登录用户信息'
            session['message']=messages(status, message)
            return redirect(url_for('admin'))

    return render_template('admin-user.html', create_form=create_form, delete_form=delete_form, update_form=update_form)
Beispiel #20
0
def profile():
    form = UpdateUserForm()

    if form.validate_on_submit():
        username = request.form['username']

        email = request.form['email']
        firstname = request.form['firstname']

        lastname = request.form['lastname']

        about = request.form['about']

        telephone = request.form['telephone']

        street = request.form['street']

        city = request.form['city']

        country = request.form['country']

        cur = mysql.connection.cursor()
        cur.execute(
            "Update User set username=%s, email=%s, firstname=%s,lastname=%s, about=%s, telephone=%s,street=%s,city=%s,country=%s where username=%s ",
            (
                username,
                email,
                firstname,
                lastname,
                about,
                telephone,
                street,
                city,
                country,
                session['username'],
            ))
        mysql.connection.commit()
        cur.close()
        session['loggedin'] = True
        session['username'] = request.form['username']
        session['email'] = request.form['email']
        flash(f' {username} Account successfully updated', 'success')
        return redirect(url_for('profile'))
    elif request.method == 'GET':
        pass
    curl = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
    curl.execute("SELECT * FROM User WHERE username=%s",
                 (session['username'], ))
    data = curl.fetchone()
    curl.close()
    default_image = os.path.join(app.config['UPLOAD_FOLDER'],
                                 'default-picture.png')

    cur = mysql.connection.cursor()
    cur.callproc("GETPROFILE_PICTURE_BY_USERNAME", [session['username']])
    user_profile_pic = cur.fetchone()
    cur.close()
    print(user_profile_pic)
    return render_template("profile.html",
                           title='Profile',
                           default=default_image,
                           form=form,
                           pro_info=data,
                           user_profile_pic=user_profile_pic)
Beispiel #21
0
def account():
    if not current_user.is_authenticated:
        return redirect(url_for("index"))

    context_dict = {
        "title": "Account",
        "user": current_user,
        "edit_user_form": UpdateUserForm(),
        "edit_password_form": UpdatePasswordForm()
    }

    if hasattr(current_user, 'company_name'):
        all_snack_brands = list({snack.snack_brand for snack in Snack.objects})

        # Remove duplicates
        company_brands = current_user.company_snackbrands
        # TODO: I'm not sure if the next line is working as it should - ADAM.
        all_snack_brands = list(
            filter(lambda a: a not in company_brands, all_snack_brands))

        all_snack_brands_temp = [(snack, snack) for snack in all_snack_brands]
        search_company_brands = [(snack, snack) for snack in company_brands]

        all_snack_brands = all_snack_brands_temp
        all_snack_brands.sort()
        search_company_brands.sort()

        default = [("Can't find my brand, create a new brand!",
                    "Can't find my brand, create a new brand!")]
        search_company_brands = default + search_company_brands
        all_snack_brands = default + all_snack_brands

        search_form = CompanySearchBrandForm()
        search_form.search_snack_brand.choices = search_company_brands

        add_form = CompanyAddBrandForm()
        add_form.add_snack_brand.choices = all_snack_brands

        if request.method == "POST" and add_form.validate_on_submit():
            add_snack_brand = add_form.add_snack_brand.data

            if add_snack_brand != "Can't find my brand, create a new brand!":
                try:
                    current_user.update(
                        add_to_set__company_snackbrands=add_snack_brand)
                except Exception as e:
                    raise Exception(
                        f"Error {e}. \n Couldn't add {add_snack_brand},\n with following creation form: {add_form}"
                    )
                print(f"A new snack_brand added to company user",
                      file=sys.stdout)

                return redirect(url_for('account'))
            else:
                return redirect(url_for("create_brand"))
        # TODO: Somebody called it query_set - but actually implemented it as a list - what should be the correct one?
        query_set = []
        if request.method == "POST" and search_form.validate_on_submit():

            search_snack_brand = search_form.search_snack_brand.data

            if search_snack_brand != "Nothing Selected":
                query_set = [
                    snack for snack in Snack.objects
                    if snack.snack_brand == search_snack_brand
                ]

        context_dict.update({
            "company_brands": company_brands,
            "search_form": search_form,
            "add_form": add_form,
            "query_set": query_set
        })

        return render_template('account.html', **context_dict)

    else:
        print("User is not a company user")

        return render_template('account.html', **context_dict)