Example #1
0
def user(username):
    """
    user <username> edit

    """
    if "username" in session:
        form = EditUserForm(request.form)
        user = User.query.filter_by(username=username).first()
        if user == None:
            return redirect(url_for("index"))
        else:
            if user.username == escape(session["username"]):
                if form.validate_on_submit():
                    user.username = form.username.data
                    user.email = form.email.data
                    user.password = generate_password_hash(form.password.data)
                    db.session.add(user)
                    db.session.commit()

                    session["username"] = user.username
                    # flash will display a message to the user
                    flash("Update Successful!")
                    # redirect user to the 'home' method of the user module.
                    return redirect(url_for("index"))
                else:
                    form.username.data = user.username
                    form.email.data = user.email
                return render_template("user.html", title="Edit User", user=user, form=form)
            else:
                return redirect(url_for("index"))
    else:
        return redirect(url_for("index"))
Example #2
0
def profile(id):
    """Update profile for current user."""

    # IMPLEMENT THIS
    if not g.user:
        flash("Access unauthorized.", "danger")
        return redirect("/")
    user = User.query.get_or_404(id)
    form = EditUserForm(obj=user)

    if form.validate_on_submit():
        """handles password submission"""
        password = User.authenticate(user.username, form.password.data)
        if password or g.user.is_admin:
            """updates the user profile"""
            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
            user.is_admin = form.is_admin.data
            db.session.add(user)
            db.session.commit()
            flash("Updated Profile", "success")
            return redirect(f"/users/{user.id}")
        else:
            """shows for invalid password"""
            flash("Invalid Password", "danger")
            return redirect(f"/users/{user.id}/profile")
    else:
        return render_template("users/edit.html", user=user, form=form)
Example #3
0
def profile():
    """Update profile for current user."""

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

    form = EditUserForm(obj=g.user)

    user = User.query.filter_by(id=g.user.id).first()

    if form.validate_on_submit():
        valid_user = User.authenticate(user.username, form.password.data)
        if valid_user:
            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
            user.location = form.location.data

            db.session.commit()

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

        else:
            flash("Invalid credentials.", 'danger')
            return redirect(f'/users/{g.user.id}')
    else:
        return render_template('users/edit_profile.html', form=form)
Example #4
0
def edit_user():
    """Edit profile for user."""

    if not g.user:
        flash(NOT_LOGGED_IN_MSG, "danger")
        return redirect("/login")

    user = g.user

    # Do not display the static value of the default image
    # This will throw an error with the URL validator in wtforms
    if user.image_url == User._default_img:
        user.image_url = ''

    form = EditUserForm(obj=user)

    if form.validate_on_submit():
        form.populate_obj(user)

        # if the image_url is empty, then set the default again
        if not user.image_url:
            user.image_url = User._default_img

        db.session.commit()

        flash("Profile edited.", "success")
        return redirect("/profile")

    else:
        return render_template("profile/edit-form.html", form=form)
Example #5
0
def user_edit_page(user_id):

    if not current_user.key.id() == user_id:
        if not current_user.is_admin():
            return render_template('not_found_page.html'), 404

    user = User.get_by_id(str(user_id).lower())

    if user:

        form = EditUserForm()
        checked_status = 'checked' if user.is_admin() else ''

        if form.validate_on_submit():

            user.name = form.name.data

            if current_user.is_admin():
                user.isAdmin = form.isAdmin.data

            user.put()

            return redirect(url_for('web_app.user_edit_page', user_id=user_id))

        return render_template('edit_user_page.html',
                               form=form,
                               checked_status=checked_status,
                               user=user)

    else:
        return render_template('not_found_page.html'), 404
Example #6
0
def profile():
    """Update profile for current user."""

    # IMPLEMENT THIS

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

    form = EditUserForm(obj=g.user)

    if form.validate_on_submit():
        user = User.authenticate(g.user.username, form.password.data)
        if user:
            user.username = form.username.data
            user.email = form.email.data
            user.image_url = form.image_url.data
            user.header_image = form.header_image_url.data
            user.bio = form.bio.data

            db.session.commit()
            return redirect(f"/users/{user.id}")
        else:
            flash("Invalid credentials.", 'danger')
            return redirect('/')
    return render_template(
        "users/edit.html",
        form=form,
    )
Example #7
0
def edit_user():
    #check if the id is a digit
    if request.args.get('id').isdigit():
        form = EditUserForm(request.form)
        #convert to digit
        user_id = request.args.get('id').encode('ascii', 'ignore')
        #get user and the number of submitted documents
        result = db.session.query(User, func.count(
            Submit.uid)).outerjoin(Submit).filter(User.id == user_id).group_by(
                Submit.uid).first()
        if result:
            user = result[0]
            docs = result[1]
            if request.method == 'GET':
                form = EditUserForm(request.form,
                                    first=user.first,
                                    last=user.last,
                                    phone=user.phone,
                                    email=user.email)
            #update db on form submit
            elif form.validate_on_submit():
                user.first = form.first.data
                user.last = form.last.data
                user.phone = form.phone.data
                user.email = form.email.data
                db.session.commit()
                return redirect(url_for('users'))
            return render_template('edit_user.html',
                                   form=form,
                                   user=user,
                                   docs=docs,
                                   current_user=current_user)
    abort(404)
Example #8
0
def profile():
    """Update profile for current user."""

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

    form = EditUserForm()

    if form.validate_on_submit():
        if User.check_entered_pwd(g.user.password, form.password.data):
            user = User.query.get(g.user.id)

            user.username = form.username.data
            user.email = form.email.data
            user.password = form.password.data
            user.image_url = form.image_url.data
            user.header_image_url = form.header_url.data
            user.bio = form.bio.data
            user.location = form.location.data

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

            flash("Info Edited", "success")
            return redirect(f"{g.user.id}")
        else:
            flash("Wrong Password", "danger")
            return redirect("/")

    return render_template("users/edit.html", form=form)
Example #9
0
    def post(self):
        form = EditUserForm()
        if form.validate_on_submit():
            new_user = get_dict(request.form,
                    'account',
                    'pwd',
                    'name',
                    'skills',
                    'email')

            folder = '{}/{}'.format(app.config["UPLOAD_FOLDER"], new_user["account"])
            logo = request.files['logo']
            filename = secure_filename(logo.filename)
            new_user['logo']=logo.filename
            if isdir(folder) == False:
                try:
                    makedirs(folder)
                except OSError as exc:
                    if exc.errorno == errno.EXIST and path.isdir(folder):
                        pass
                    else:
                        raise
            logo.save(join(folder, filename))
            try:
                User(**new_user).save()
            except:
                ValidationError(message='DB insert Error')
                return render_template('users/create.html',
                    form=form)
            return redirect(url_for('users.login'))
        return render_template('users/create.html', form=form)
Example #10
0
def profile():
    """Update profile for current user."""

    form = EditUserForm()

    if form.validate_on_submit():
        if User.authenticate(g.user.username, form.password.data):
            try:
                g.user.username = form.username.data
                g.user.email = form.email.data
                g.user.image_url = form.image_url.data
                g.user.header_image_url = form.header_image_url.data or "/static/images/warbler-hero.jpg"
                g.user.bio = form.bio.data
                db.session.add(g.user)
                db.session.commit()

            except IntegrityError:
                flash("Username already taken", 'danger')
                return redirect(url_for('profile'))

            flash("Changes Successful!", "success")
            return redirect(f"{g.user.id}")

        flash("Incorrect Password", "danger")
        return redirect(url_for('profile'))

    return render_template('users/edit.html', form=form)
Example #11
0
def profile():
    """Update profile for current user."""

    if not g.user:
        flash("Access unauthorized.", "danger")
        return redirect("/")
    user = User.query.get_or_404(session[CURR_USER_KEY])
    form = EditUserForm(obj = user)

    if form.validate_on_submit():
       
        is_user = User.authenticate(user.username, form.password.data)

        if is_user:
            
            user.username = form.username.data
            user.email = form.email.data
            user.image_url = form.image_url.data or User.image_url.default.arg
            user.header_image_url = form.header_image_url.data or User.header_image_url.default.arg
            user.bio = form.bio.data
            db.session.commit()
            flash('Updated user successfully!', 'success')
            return redirect(f'/users/{user.id}')

        else:
            flash('Incorrect Password! Cannot edit user!', 'danger')
            return redirect('/')


    return render_template('users/edit.html', form=form, user = user)
Example #12
0
def update_profile():

    if 'id' not in session:
        flash("Access unauthorized", "danger")
        return redirect('/users/login')

    user = User.query.get_or_404(session['id'])
    
    username = user.username
    img = user.img

    form = EditUserForm(obj=user)
    
    if form.validate_on_submit():

        if len(form.username.data) == 0:
            user.username= user.username
        else:
            user.username=form.username.data

        if len(form.img.data) == 0:
            user.img = user.img
        else:
            user.img=form.img.data

        db.session.commit()
        flash('update sucessful')

        return redirect("/")
    else:
        return render_template("users/edit.html", form=form, user=user)
Example #13
0
def edit_profile():
    """Update profile for current user."""

    # IMPLEMENT THIS

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

    user = g.user
    form = EditUserForm(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

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

        flash(f"{user.username}, password doesn't match! please try again.",
              'danger')

    return render_template('users/edit.html', form=form, user_id=user.id)
Example #14
0
def edit_user(username):

    form = EditUserForm(obj=g.user)
    form.location.choices = country_choices
    if form.validate_on_submit():
        first_name = form.first_name.data
        last_name = form.last_name.data
        email = form.email.data
        image = form.image.data
        username = form.username.data
        location = form.location.data
        bio = form.bio.data
        if type(image) is str:
            user = g.user.edit_user(first_name, last_name, username, location,
                                    bio)
        else:
            url = add_profile_picture(username, image)
            user = g.user.edit_user(first_name, last_name, username, location,
                                    bio, url)

        if user:
            db.session.add(user)
            db.session.commit()
            return redirect(url_for('show_user', username=username))
        else:
            form.username.errors.append('Username has already been taken')
            return render_template('form.html', form=form)

    return render_template('form.html', form=form)
Example #15
0
def profile():
    """Update profile for current user."""

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

    user = g.user

    form = EditUserForm(obj=user)

    if form.validate_on_submit():
        user = User.authenticate(user.username, form.password.data)

        if user:
            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()
            flash("User information updated!", "success")
            return redirect(f"/users/{g.user.id}")

        flash("Invalid credentials.", 'danger')
        return redirect(f"/users/{g.user.id}")

    return render_template('/users/edit.html', form=form)
Example #16
0
def profile():
    if not g.user:
        flash("Access unauthorized.", "danger")
        return redirect("/")
    user = User.query.get_or_404(g.user.id)
    form = EditUserForm()
    if form.validate_on_submit():
        if not User.authenticate(username=user.username,
                                 password=form.password.data):
            flash('Password incorrect!', category='danger')
            return redirect('/')
        user.username = form.username.data
        user.email = form.email.data
        if form.image_url.data:
            user.image_url = form.image_url.data
        if form.header_image_url.data:
            user.header_image_url = form.header_image_url.data
        user.bio = form.bio.data
        db.session.add(user)
        db.session.commit()
        return redirect(f'/users/{user.id}')

    else:
        form.username.data = user.username
        form.email.data = user.email
        form.image_url.data = user.image_url
        form.header_image_url.data = user.header_image_url
        form.bio.data = user.bio
    return render_template('/users/edit.html', form=form)
Example #17
0
def edit_user_form(id):
    """Edit existing user data"""
    user = User.query.get_or_404(id)
    form = EditUserForm(obj=user)
    # delete username and password from the edit form
    del form.username
    del form.password
    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.last_updated = datetime.datetime.utcnow()
        try:
            db.session.commit()
            flash("User account info saved", "success")
            if form.image.data:
                try:
                    img = Image.open(request.files[form.image.name])
                    width, height = img.size
                    img = img.crop((0, 0, min(width,
                                              height), min(width, height)))
                    upload_img(img, user)
                    user.has_img = True
                    user.last_updated = datetime.datetime.utcnow()
                    db.session.commit()
                except:
                    db.session.rollback()
                    flash("Image Error", 'error')
        except:
            db.session.rollback()
            flash("Changes could not be saved", 'error')
        return redirect(f'/users/{user.id}')
    return render_template('edit-user.html', user=user, form=form)
Example #18
0
def edit_user(user_id):
    """Edit user profile if POST request, show edit user form if GET request"""
    user = User.query.get_or_404(user_id)

    form = EditUserForm(obj=user)

    if form.validate_on_submit():
        if User.authenticate(user.username, form.password.data):
            if form.username.data:
                user.username = form.username.data

            if form.email.data:
                user.email = form.email.data

            if form.image_url.data:
                user.image_url = form.image_url.data

            if form.header_image_url.data:
                user.header_image_url = form.header_image_url.data

            if form.bio.data:
                user.bio = form.bio.data

            db.session.commit()

            flash('Successfully saved changes!', 'success')
            return redirect(f'/users/{user.id}')
        else:
            flash(
                "Sorry, that's not the correct password for your account.  Please type in another password.",
                "danger")
            return redirect(f'/users/{user.id}/edit')
    else:
        return render_template('users/edit.html', user=user, form=form)
Example #19
0
def edit_profile(username):
	""" Show Edit User Profile Form """

	if current_user.username != username:
		flash('Access unathorized', 'danger')
		return redirect(url_for('index'))

	user = current_user

	form = EditUserForm(obj=user)

	if form.validate_on_submit():
		user = User.authenticate(current_user.username, form.password.data)

		if user:
			try:
				user.username = form.username.data
				user.email = form.email.data
				db.session.commit()
				flash('User information updated', 'success')
				return redirect(url_for('index'))

			except:
				db.session.rollback()
				flash('Username taken.', 'danger')
		else:
			flash('Invalid credentials.', 'danger')
  
	return render_template('profile.html', 
		form=form, 
		btnText='Submit', 
		cancel='index', 
		color="#ACDAAA"
	)
Example #20
0
def profile():
    """Update profile for current user."""

    # Check if a User is logged in
    if not g.user:
        flash("Access unauthorized.", "danger")
        return redirect("/")

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

    if form.validate_on_submit():
        username = form.username.data
        email = form.email.data
        image_url = form.image_url.data
        header_image_url = form.header_image_url.data
        bio = form.bio.data
        password = form.password.data

        if User.authenticate(user.username, password):
            user.username = username
            user.email = email
            user.image_url = image_url
            user.header_image_url = header_image_url
            user.bio = bio

            db.session.commit()

            return redirect(f'/users/{user.id}')
        else:
            flash("Password Incorrect, you can't edit", "danger")
            return redirect('/')

    return render_template('users/edit.html', form=form)
Example #21
0
def profile():
    """Update profile for current user."""

    ## if user not logged in, redirect
    if not g.user:
        return redirect('/')

    form = EditUserForm(obj=g.user)

    if form.validate_on_submit():
        pw = form.password.data
        user = User.authenticate(g.user.username, pw)  # returns user or false

        if user:

            for k, v in form.data.items():

                if k != 'csrf_token' and k != 'password':
                    setattr(user, k, v)
            db.session.commit()
            return redirect(f'/users/{g.user.id}')
        else:
            form.password.errors = ["invalid password"]

    return render_template('/users/edit.html', form=form)
Example #22
0
    def put(self, id):
        user = User.get_by_id(id)

        if user is None or not user.can_edit():
            flash(gettext('The user was not found'), 'error')
            return redirect(url_for('UsersView:index'))

        if request.method in ['POST']:
            form = EditUserForm()
            if form.validate_on_submit():
                if form.password.data:
                    user.set_password(form.password.data)
                del form.password
                form.populate_obj(user)
                user.save()
                refresh()
                return resp(url_for('UsersView:get', id=user.id), redirect=True,
                            message=gettext('User was succesfully updated'))
            else:
                return resp('admin/users/edit.html', form=form, user=user,
                            message=gettext('Invalid submission, please check the messages below'))
        else:
            form = EditUserForm(user=user)

        return resp('admin/users/edit.html', form=form, user=user)
Example #23
0
def profile():
    """Update profile for current user."""

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

    form = EditUserForm(obj=g.user)

    if form.validate_on_submit():

        # check if password is incorrect
        if not User.authenticate(g.user.username, form.password.data):
            form.password.errors = ['Password is incorrect. Try again.']
            return render_template('users/edit.html', form=form)

        g.user.username = form.username.data
        g.user.image_url = form.image_url.data or '/static/images/default-pic.png',
        g.user.header_image_url = form.header_image_url.data or '/static/images/warbler-hero.jpg',
        g.user.bio = form.bio.data

        db.session.commit()

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

    else:
        return render_template('users/edit.html', form=form)
Example #24
0
def profile():
    """Update profile for current user."""

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

    # username, password
    # print('***********g.user.id', g.user.id)
    user = User.query.get_or_404(g.user.id)

    form = EditUserForm(obj=user)

    user = User.authenticate(user.username, form.password.data)

    if user and 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.bio = form.bio.data

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

    else:
        return render_template('users/edit.html', form=form)
Example #25
0
def profile():
    """Update profile for current user."""

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

    user = User.query.get(g.user.id)
    form = EditUserForm(obj=user)

    if form.validate_on_submit() and User.authenticate(form.username.data,
                                                       form.password.data):
        user.image_url = form.image_url.data
        user.header_image_url = form.header_image_url.data
        user.bio = form.bio.data
        user.location = form.location.data
        user.username = form.username.data
        user.email = form.email.data

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

        flash("Profile Updated Successfully", "success")
        return redirect(f"/users/{g.user.id}")
    else:
        flash("Password did not match. Please try again.", "danger")
        return render_template("/users/edit.html", form=form)

    return render_template("/users/edit.html", form=form)
Example #26
0
def edit_user():

    if not g.user:
        flash("Please sign up to access user functionality")
        return redirect("/signup")

    form = EditUserForm(obj=g.user)
    form.address.id = "search-input"
    form.address.type = "search"

    if form.validate_on_submit():
        first_name = form.first_name.data
        last_name = form.last_name.data
        email = form.email.data
        address = form.address.data

        user = User.query.get_or_404(g.user.id)

        user.edit_user(first_name=first_name,
                       last_name=last_name,
                       email=email,
                       address=address)
        flash("Your persomal information has been successfully edited")
        return redirect("/user")

    return render_template("edit-user.html", form=form, user=g.user)
Example #27
0
def profile():
    """Update profile for current user."""

    # IMPLEMENT THIS
    if not g.user:
        flash("Access unauthorized.", "danger")
        return redirect("/")
    form = EditUserForm(obj=g.user)

    if form.validate_on_submit():
        user = User.authenticate(g.user.username, form.password.data)

        if user:
            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
            # form.populate_obj(user)
            db.session.commit()
            flash('Profile Edited', "success")
            return redirect(f'/users/{user.id}')

        flash("Error Wrong Password.", 'danger')
        return redirect('/')

    return render_template('users/edit.html', form=form)
Example #28
0
def edit_profile(user_id):
    """On submit update user information.
    
    If form not validated show edit user form.

    If password incorrect flash message.
    """
    form = EditUserForm()
    curr_user = User.query.get_or_404(user_id)
    if curr_user.id != g.user.id:
        flash('You can only edit your own profile.', 'danger')
        return redirect('/leagues')
    if form.validate_on_submit():
        user = User.authenticate(form.username.data, form.password.data)
        if user:
            curr_user.username = form.username.data
            curr_user.image_url = form.image_url.data
            db.session.commit()
        else:
            flash('Incorrect username or password', 'danger')
            return render_template('edit_user.html', form=form, user=curr_user)
        flash(f"Successfully Edited {curr_user.username}'s Profile", "success")
        return redirect('/leagues')
    else:
        return render_template('edit_user.html', form=form, user=curr_user)
Example #29
0
def post_user():
    # create a new user
    db_roles = db.session.query(Roles).all()
    radio_roles = [(role.id, role.name) for role in db_roles]
    form = EditUserForm()
    form.role.choices = radio_roles
    if form.validate_on_submit():
        user = User(form.login.data.strip(), form.password.data.strip())
        if db.session.query(Users).filter(
                Users.login == user.login).count() > 0:
            return render_template(
                'user/edit.html',
                errors=[
                    u'Пользователь с логином <b>%s</b> уже существует' %
                    user.login
                ],
                form=form)
        db_user = Users(user.login, user.pw_hash)
        db_role = db.session.query(Roles).get(form.role.data)
        db_user.roles.append(db_role)
        db.session.add(db_user)
        db.session.commit()
        flash(u'Пользователь добавлен')
        return redirect(url_for('users'))
    return render_template('user/edit.html', form=form)
Example #30
0
def edit_profile(user_id):
    """Displays form for user to edit user details (GET) and submits form (POST)"""

    if current_user.id == user_id:
        user = User.query.get_or_404(user_id)
        form = EditUserForm(obj=user)

        if form.validate_on_submit():
            user.username = form.username.data
            user.bio = form.bio.data
            user.location = form.location.data
            if form.img_url.data == "":
                db.session.commit()
                flash("Profile changes saved!", "success")
                return redirect(f"/user/{user.id}")
            else:
                user.profile_pic = form.img_url.data

            db.session.commit()

            flash("Profile changes saved!", "success")
            return redirect(f"/user/{user.id}")

        else:
            return render_template("edituser.html", form=form)
    else:
        return ("", 403)
Example #31
0
def put_user(user_id):
    db_user = db.session.query(Users).get(user_id)
    if db_user is None:
        return render_template(
            'user/list.html',
            users=db.session.query(Users).order_by(Users.id).all(),
            errors=u'Пользователя с id=%s не существует' % user_id)
    db_roles = db.session.query(Roles).all()
    radio_roles = [(role.id, role.name) for role in db_roles]
    form = EditUserForm(login=db_user.login)
    form.role.choices = radio_roles
    if form.validate_on_submit():
        password = form.password.data.strip()
        if password:
            user = User(form.login.data.strip(), form.password.data.strip())
            db_user.password = user.pw_hash
        else:
            user = User(form.login.data.strip())

        if db_user.login != user.login and db.session.query(Users).filter(
                Users.login == user.login).count() > 0:
            return render_template(
                'user/edit.html',
                errors=[
                    u'Пользователь с логином <b>%s</b> уже существует' %
                    user.login
                ],
                form=form)
        db_user.login = user.login
        db_role = db.session.query(Roles).get(form.role.data)
        db_user.roles[0] = db_role
        db.session.commit()
        flash(u'Пользователь изменен')
        return redirect(url_for('users'))
    return render_template('user/edit.html', form=form, user=db_user)
Example #32
0
def edit_user(username):
    """Show form for editing user details (GET) or add user edits to db and go to user page (POST)
    
    User cannot change username or password for now"""

    # Check if logged in user is this user
    if is_correct_user(username):
        form = EditUserForm(first_name=current_user.first_name,
                            last_name=current_user.last_name,
                            state_code=current_user.state_code)

        if form.validate_on_submit():
            current_user.first_name = form.first_name.data
            current_user.last_name = form.last_name.data
            current_user.state_code = form.state_code.data

            db.session.commit()

            flash("User updated")
            # on successful edit, redirect to users page
            return redirect(f"/users/{ current_user.username }")

        return render_template("edit_user.html", form=form)

    flash("Not your profile")
    return redirect("/")
Example #33
0
def update_profile():
    """Update profile for current user."""

    form = EditUserForm(obj=g.user)

    # user = User.query.get(session[CURR_USER_KEY])
    # IMPLEMENT THIS
    if form.validate_on_submit():
        if User.authenticate(g.user.username, form.password.data):
            # we don't need line 230 because we've done it g.user
            # user = User.query.get(session[CURR_USER_KEY])
            user = g.user
            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.add(user)
            db.session.commit()

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

    else:
        return render_template("users/edit.html", form=form)
Example #34
0
def edit(id):
    user = User.query.filter_by(id=id).first_or_404()
    form = EditUserForm(obj=user)
    if form.validate_on_submit():
        form.populate_obj(user)
        user.update()
        flash('User %s edited' % user.username, 'success')
    return render_template('edit.html', form=form, user=user)
Example #35
0
def editUser(id=0):
    user = User.query.filter_by(id=id).first()
    form = EditUserForm(obj=user)
    customer_choices = [(a.id, a.name) for a in Customer.query.filter_by(customer_type=CUSTOMER_TYPES['TYPE_CUSTOMER']).all()]
    customer_choices = [(0, '')] + customer_choices
    maker_choices = [(a.id, a.name) for a in Maker.query.all()]
    maker_choices = [(0, '')] + maker_choices
    form.customer.choices = customer_choices
    form.maker.choices = maker_choices

    if form.validate_on_submit():
        if len(User.query.filter_by(nickname=form.nickname.data).all()) > 1:
            flash(gettext("Selected username already exists!"))
            return redirect(url_for('users'))

        new_email = form.email.data
        check_mail = User.query.filter_by(email=new_email).all()

        #user mail already exists
        if len(check_mail) > 0 and new_email != user.email:
            flash(gettext('Selected email is already in use!'))
            return redirect(url_for('users'))

        user.nickname = form.nickname.data
        user.email = form.email.data
        user.role = form.role.data

        if int(form.role.data) == USER_ROLES['ROLE_CUSTOMER']:
            if form.customer.data and form.customer.data != '' and form.customer.data != 0:
                user.customer_id = form.customer.data
                user.maker_id = None
            else:
                user.customer_id = None
        elif int(form.role.data) == USER_ROLES['ROLE_MAKER']:
            if form.maker.data and form.maker.data != '' and form.maker.data != 0:
                user.maker_id = form.maker.data
                user.customer_id = None
            else:
                user.maker_id = None
        else:
            user.customer_id = None
            user.maker_id = None

        user.language = form.language.data
        db.session.add(user)
        db.session.commit()
        flash(gettext("User details succesfully changed."))
        return redirect(url_for("users"))
    selected_customer = user.customer_id if user.customer_id else 0
    selected_maker = user.maker_id if user.maker_id else 0
    return render_template('settings/editUser.html',
                           title=gettext("Edit User"),
                           USER_ROLES=USER_ROLES,
                           selected_customer=selected_customer,
                           selected_maker=selected_maker,
                           form=form)
Example #36
0
def edit_user():
    form = EditUserForm()
    user = current_user  
    if form.validate_on_submit():
        user.name.first = re.sub('<[^>]*>', '', request.form['first_name'])
        user.name.last = re.sub('<[^>]*>', '', request.form['last_name'])
        user.name.full = titleize(user.name.first + ' ' + user.name.last)
        user.save()
        return redirect(url_for('user', user_id=user._id))
    return render_template('edit_user.html', user=user)
Example #37
0
def user_edit(user_id):
    user = User.query.filter_by(id=user_id).first()
    form = EditUserForm(obj=user)
    if form.validate_on_submit():
        form.populate_obj(user)
        db_session.add(user)
        db_session.commit()
        flash('Nutzerdaten erfolgreich aktualisiert!')
        return redirect(url_for('user_list'))
    return render_template('user_edit.jinja', form=form, user=user)
Example #38
0
def profile_edit():
    eForm = EditUserForm(g.user.nickname)
    if eForm.validate_on_submit():
        g.user.nickname = eForm.nickname.data
        g.user.about_me = eForm.about_me.data
        db.session.add(g.user)
        db.session.commit()
        flash('Your profile has been saved.', 'success')
    else:
        eForm.nickname.data = g.user.nickname
        eForm.about_me.data = g.user.about_me
    return redirect(request.args.get('next') or url_for('user', nickname=g.user.nickname))
Example #39
0
def update_user_info():
	user_id = int(request.args.get('user_id',0))
	if user_id :
		form = EditUserForm()
		if form.validate_on_submit():
			user_info = {}
			user_info["name"] = form.name.data
			user_info["age"] = form.age.data
			user_info["gender"] = form.gender.data
			user_info["occupation"] = form.occupation.data
			current_app.config['USERS_COLLECTION'].update_one({"id":user_id},{'$set':user_info},upsert = True)
			return redirect(url_for('.show_user_f_id',user_id = user_id))
		return render_template('edit_user_form.html',form=form)		
 	return redirect(url_for('.show_user_f_id',user_id = user_id))
Example #40
0
def editprofile():
    if cas.username is None:
        return redirect('/login')
    user = Player.query.filter(Player.netid==cas.username).first()
    if user is None:
        return redirect('/newuser')

    form = EditUserForm()
    if form.validate_on_submit():
        if not name_check(form.name.data,1):
            return render_template('editprofile.html',user=user,form=form,validname=0)
        user.name = form.name.data
        user.email = form.email.data
        db.session.commit()
        return redirect('/index')
    form.name.data = user.name
    form.email.data = user.email
    return render_template('editprofile.html',user=user,form=form,validname=1)
Example #41
0
def edit_profile():
    form = EditUserForm()

    if request.method == 'POST' and form.validate_on_submit():
        if current_user.id == int(form.userid.data):
            photo_file = form.photo.data

            if photo_file:
                file_ext = get_file_extension(photo_file.filename)
                generated_name = str(uuid.uuid1()) + '.' + file_ext

                current_user_id = str(current_user.id)
                folder_path = app.config['UPLOADS_FOLDER'] + '/user/' + current_user_id + '/'
                new_folder = os.path.dirname(folder_path)
                if not os.path.exists(new_folder):
                    os.makedirs(new_folder)

                filepath = os.path.join(folder_path, generated_name)

                photo_file.save(filepath)

                new_photo = Photo(owner=current_user, filename='user/' + current_user_id + '/' + generated_name)
                db.session.add(new_photo)
                db.session.commit()

                User.query.filter(User.id == current_user.id).\
                    update({User.photo: new_photo.filename})

            User.query.filter(User.id == current_user.id).\
                update({User.name: form.name.data,
                        User.email: form.email.data,
                        User.phone_number: form.phone_number.data,
                        User.about: form.about.data})
            db.session.commit()

            flash(u"Profil güncellendi.", current_user.id)

    form.fill_form(current_user)

    return render_template(
        'edit_profile.html',
        form=form,
        user=current_user
    )
Example #42
0
def edit_user():
    form = EditUserForm(g.user.handle)
    if form.validate_on_submit():
        g.user.handle = form.handle.data
        g.user.about_me = form.about_me.data
        g.user.email = form.email.data
        g.user.pic_url = form.pic_url.data
        db.session.add(g.user)
        db.session.commit()
        flash(choice(app.config['MSG']['confirm_post']))
        app.logger.info(g.user.handle, ' changed something.')
        return redirect(url_for('user', handle=g.user.handle, page=1))
    else:
        form.handle.data = g.user.handle
        form.about_me.data = g.user.about_me
        form.email.data = g.user.email
        form.pic_url.data = g.user.pic_url
        if form.handle.errors:
            flash(form.handle.errors[0])
    return render_template('edit_user.html', form=form, user=g.user)
Example #43
0
def edit_user():
    form = EditUserForm()
    
    if form.validate_on_submit():
        g.user.first_name = form.first_name.data
        g.user.last_name = form.last_name.data
        #if form.image is not None or form.image != "":
        if form.image:
            form.image.data.save(os.path.join(PROFILE_IMAGE_PATH, '%d.jpg' % g.user.id))
            g.user.image = "/uploads/profile_images/%d.jpg"% g.user.id
        db.session.merge(g.user)
        db.session.commit()
        flash('Your profile has been updated')
        return redirect(url_for('index'))

    else:
        form.first_name.data = g.user.first_name
        form.last_name.data = g.user.last_name
    
    return render_template('edit_user.html', title = 'Edit Profile', form = form, user = g.user, action = 'Update')
Example #44
0
def editProfile():
    error = None
    form = EditUserForm(request.form)
    username_before = request.args.get("usr")
    user = User.query.filter_by(userName=username_before).first()
    if request.method == "POST":
        if form.validate_on_submit():
            if bcrypt.check_password_hash(user.password, request.form["password"]):
                firstname = request.form["firstname"]
                lastname = request.form["lastname"]
                username = request.form["username"]
                email = request.form["email"]
                session["userName"] = username
                session["firstName"] = firstname
                session["lastName"] = lastname
                session["email"] = email

                # Update
                db.session.query(User).filter_by(userName=username_before).update({User.firstName: firstname})
                db.session.query(User).filter_by(userName=username_before).update({User.lastName: lastname})
                db.session.query(User).filter_by(userName=username_before).update({User.userName: username})
                db.session.query(Scores).filter_by(userName=username_before).update({Scores.userName: username})
                db.session.query(User).filter_by(userName=username_before).update({User.email: email})

                if request.form["newPassword"] != "":
                    newPassword = bcrypt.generate_password_hash(form.newPassword.data)
                    db.session.query(User).filter_by(userName=username_before).update({User.password: newPassword})

                db.session.commit()
                return redirect(url_for("appHome.profile"))

            else:
                error = "Invalid password"
                return render_template("editProfile.html", form=form, error=error, user=user)

        else:
            return render_template("editProfile.html", form=form, error=error, user=user)

    if request.method == "GET":
        return render_template("editProfile.html", form=form, user=user)
Example #45
0
def edit_user(id):
    user = User.query.get(id)
    if user == None:
        flash("User not found")
        abort(404)

    form = EditUserForm()
    form.property.choices = [(p.id, p.name) for p in Property.query.order_by('name')]
    form.property.choices.insert(0,(0,None))
    form.role.choices = [(ROLE_USER,"user"),(ROLE_LANDLORD,"landlord"),(ROLE_ADMIN,"admin")]

    if form.validate_on_submit():
        if form.property.data != 0:
            user.property_id = form.property.data
        else:
            user.property_id = None
        user.role = form.role.data
        db.session.add(user)
        db.session.commit()
        flash('Your changes have been saved.')
        return redirect(url_for('users'))
    return render_template('edit_user.html',
        user = user,
        form = form)
Example #46
0
def editUser(): 
    error = None      
    form = EditUserForm(request.form)
    username_before=request.args.get('usr')
    user=User.query.filter_by(userName=username_before).first()
    if request.method == 'POST':
        if form.validate_on_submit():
            firstname=request.form['firstname']
            lastname=request.form['lastname']
            username=request.form['username']
            email=request.form['email']
            validated=request.form['validated']
            activated=request.form['activated']
            activation_before=user.activated
           
            #Update           
            db.session.query(User).filter_by(userName=username_before)\
                .update({User.firstName: firstname})
            db.session.query(User).filter_by(userName=username_before)\
                .update({User.lastName: lastname})
            db.session.query(User).filter_by(userName=username_before)\
                .update({User.userName: username})
            db.session.query(User).filter_by(userName=username_before)\
                .update({User.email: email})
            import ast
            db.session.query(User).filter_by(userName=username_before)\
                .update({User.validated: ast.literal_eval(validated)})
            db.session.query(User).filter_by(userName=username_before)\
                .update({User.activated: ast.literal_eval(activated)})
            db.session.commit() 
                       
            if activation_before == False and activated == 'True':
                print "here"
                import smtplib
                from email.mime.multipart import MIMEMultipart
                from email.mime.text import MIMEText
                from email.MIMEImage import MIMEImage
                
                
                # Writing the message (this message will appear in the email)
                fromAddress='*****@*****.**'
                toAddress= user.email
                
                msg = MIMEMultipart()                
                msg['Subject'] = "Your bets EURO2016 account is activated"
                msg['From'] = fromAddress
                msg['To'] = user.email
                
                body =  """Hi {0},
                
Thanks again for being part of this kick ass EURO 2016 betting app! \n
Your bank transfer is completed and your account is therefore activated. 
             
http://bets-euro2016.herokuapp.com/home/ 
Go Crazy! 
              
Kind regards,

Senne & Louis 
                                          
""".format(user.userName)
                msg.attach(MIMEText(body, 'plain'))
                
                text = msg.as_string()
                                   
                # Gmail Login    
                usrname = '*****@*****.**'
                password = '******'
                
                # Sending the mail
                
                server = smtplib.SMTP('smtp.gmail.com:587')
                server.starttls()
                server.login(usrname,password)
                server.sendmail(fromAddress, toAddress, text)
                server.quit()
                #here comes the automatic mail code 
            return redirect(url_for('admin.checkDatabase'))        

        else:
            user.validated=str(user.validated)
            user.activated=str(user.activated)
            return render_template("editUser.html",form=form,error=error,user=user)
            
    if request.method == 'GET':
        user.validated=str(user.validated)
        user.activated=str(user.activated)
        return render_template('editUser.html', form=form,user=user)