Beispiel #1
0
def edit_profile_admin(id):
    edit_user = User.query.get_or_404(id)
    form = EditProfileAdminForm(user=edit_user)
    if form.validate_on_submit():
        edit_user.email = form.email.data
        edit_user.username = form.username.data
        edit_user.name = form.name.data
        edit_user.about_me = form.about_me.data
        edit_user.location = form.location.data
        # 下面的role必须赋值一个实体,如果直接赋值form.role.data会报错
        # int object has no attribute _sa_instance_state
        edit_user.role = Role.query.get(form.role.data)
        edit_user.confirm = form.confirmed.data

        db.session.add(edit_user)
        flash(u'修改用户信息成功')
        return redirect(url_for('.user', username=edit_user.username))

    form.email.data = edit_user.email
    form.username.data = edit_user.username
    form.name.data = edit_user.name
    form.location.data = edit_user.location
    form.about_me.data = edit_user.about_me
    form.role.data = edit_user.role
    form.confirmed.data = edit_user.confirm

    return render_template('main/edit_profile_admin.html', form=form)
Beispiel #2
0
def post_comment(id):
    post = Post.query.get_or_404(id)
    form = CommentForm()
    if form.validate_on_submit():
        comment = Comment(body=form.body.data,
                          post=post,
                          author=current_user._get_current_object())
        db.session.add(comment)
        db.session.commit()
        flash(u'你的评论已经发出')
        return redirect(url_for('main.post_comment', id=post.id, page=-1))
    page = request.args.get('page', 1, type=int)
    if page == -1:
        page = (post.comments.count() -
                1) // current_app.config['FLASKY_COMMENTS_PER_PAGE'] + 1
    pagination = post.comments.order_by(Comment.timestamp.asc()).paginate(
        page,
        per_page=current_app.config['FLASKY_COMMENTS_PER_PAGE'],
        error_out=False)
    comments = pagination.items
    return render_template('post_comment.html',
                           posts=[post],
                           form=form,
                           comments=comments,
                           pagination=pagination)
Beispiel #3
0
def upload_countersigned_agreement_file(supplier_id, framework_slug):
    agreements_bucket = s3.S3(current_app.config['DM_AGREEMENTS_BUCKET'])
    errors = {}

    if request.files.get('countersigned_agreement'):
        the_file = request.files['countersigned_agreement']
        if not file_is_pdf(the_file):
            errors['countersigned_agreement'] = 'not_pdf'

        if 'countersigned_agreement' not in errors.keys():
            filename = get_agreement_document_path(framework_slug, supplier_id, COUNTERSIGNED_AGREEMENT_FILENAME)
            agreements_bucket.save(filename, the_file)

            data_api_client.create_audit_event(
                audit_type=AuditTypes.upload_countersigned_agreement,
                user=current_user.email_address,
                object_type='suppliers',
                object_id=supplier_id,
                data={'upload_countersigned_agreement': filename})

            flash('countersigned_agreement', 'upload_countersigned_agreement')

    if len(errors) > 0:
        for category, message in errors.items():
            flash(category, message)

    return redirect(url_for(
        '.list_countersigned_agreement_file',
        supplier_id=supplier_id,
        framework_slug=framework_slug)
    )
Beispiel #4
0
def edit_profile():
    form = EditProfileForm()
    if form.validate_on_submit():
        current_user.name = form.name.data
        current_user.location = form.location.data
        current_user.about_me = form.about_me.data
        #########
        """"
        if request.method == 'POST':
            file = request.files['file']
            size = (40, 40)
            im = Image.open(file)
            im.thumbnail(size)
            if file and allowed_file(file.filename):
                filename = secure_filename(file.filename)
                im.save(os.path.join(current_app.Config["UPLOAD_FOLDER"],filename))
                current_user.avatar = url_for('static', filename='%s/%s' % ('avatar', filename))
                flash(u'头像修改成功')
        """
        #########
        db.session.add(current_user)
        flash(u"你的个人资料已经更新")
        return redirect(url_for("main.user", username=current_user.username))

    form.name.data = current_user.name
    form.location.data = current_user.location
    form.about_me.data = current_user.about_me
    return render_template("edit_profile.html", form=form)
Beispiel #5
0
def edit_profile_admin(id):
    user = User.query.get_or_404(id)
    form = EditProfileAdminForm(user=user)
    if form.validate_on_submit():
        user.email = form.email.data
        user.username = form.username.data
        user.confirmed = form.confirmed.data
        user.role = Role.query.get(form.role.data)
        user.name = form.name.data
        user.location = form.location.data
        user.about_me = form.about_me.data
        db.session.add(user)

        flash(u"你的个人资料已经更新")
        #print("###")
        return redirect(url_for("main.user", username=user.username))

    form.email.data = user.email
    form.username.data = user.username
    form.confirmed.data = user.confirmed
    form.role.data = user.role_id

    form.name.data = user.name

    form.location.data = user.location
    form.about_me.data = user.about_me
    #print("%%%%%")
    return render_template("edit_profile.html", form=form, user=user)
Beispiel #6
0
def login():
    # return redirect(request.args.get("next") or "/tasks")
    form = LoginForm()
    if form.validate_on_submit():
        # login and validate the user...
        account = unicode.encode(form.account.data.decode())
        pw = HmacPasswd(form.passwd.data).get_hmacpassed()
        r = requests.post(API_service+"/api/user/check/", data=json.dumps({"account": account, "password": pw}))
        if r.status_code /100 == 2:
            res = json.loads(r.text)
            if res["status"] == 1:
                user = User()
                user.account = account
                user.passwd_enc = pw
                user.role = res["user_flag"]
                if form.remember_me.data:
                    login_user(user, remember=True)
                else:
                    login_user(user)
                flash(u"Logged in successfully.")
                if user.role == 0:
                    return redirect(request.args.get("next") or "/marks")
                else:
                    return redirect(request.args.get("next") or "/tasks")
    return render_template(login_html, form=form)
Beispiel #7
0
def unfollow(username):
    u = User.query.filter_by(username=username).first()
    if u is None:
        flash(u'未找到指定用户')
    current_user.unfollow(u)
    flash(u'你已经取消关注他了')
    return redirect(url_for('.user', username=username))
Beispiel #8
0
def edit_post(id):
    single_post = Post.query.get_or_404(id)
    if current_user != single_post.author and \
            not current_user.can(Permission.ADMINSTER):
        abort(403)
    form = PostForm()
    if form.validate_on_submit():
        single_post.body = form.body.data
        db.session.add(single_post)
        flash(u'修改成功')
        return redirect(url_for('.post', id=id))
    form.body.data = single_post.body
    return render_template('main/edit_post.html', form=form)
Beispiel #9
0
def edit_profile():
    form = EditProfileForm()
    if form.validate_on_submit():
        current_user.name = form.name.data
        current_user.location = form.location.data
        current_user.about_me = form.about_me.data
        db.session.add(current_user)
        flash('Your profile has been updated.')
        return redirect(url_for('.user', username=current_user.username))
    form.name.data = current_user.name
    form.location.data = current_user.location
    form.about_me.data = current_user.about_me
    return render_template('edit_profile.html', form=form)
Beispiel #10
0
def edit(id):
    post = Post.query.get_or_404(id)
    if current_user != post.author and not current_user.can(
            Permission.ADMINISTER):
        abort(403)
    form = PostForm()
    if form.validate_on_submit():
        post.body = form.body.data
        db.session.add(post)
        flash(u"博文已经更新")
        return redirect(url_for("main.index", id=post.id))
    form.body.data = post.body
    return render_template("edit_post.html", form=form)
Beispiel #11
0
def edit(id):
    post = Post.query.get_or_404(id)
    if current_user != post.author and \
            not current_user.can(Permission.ADMINISTER):
        abort(403)
    form = PostForm()
    if form.validate_on_submit():
        post.body = form.body.data
        db.session.add(post)
        flash('The post has been updated.')
        return redirect(url_for('.post', id=post.id))
    form.body.data = post.body
    return render_template('edit_post.html', form=form)
Beispiel #12
0
def forbidden(err):
    code = 403
    if not current_user.is_authenticated():
        target = get_redirect_target()
        if not target:
            target = request.url
        flash('You do not have access to this resource, please login.', 'error')
        return redirect(url_for('user.login', next=target), code=code)
    else:

        title = 'Access denied'
        message = "Sorry, but you don't have access to this resource."
        return render_template('errors/show.html', code=code, title=title, message=message), code
 def set_profiles(self, ids, key, value, session=None):
     try:
         count = 0
         for profile in session.query(DcmpUserProfile).filter(
                 DcmpUserProfile.id.in_(ids)).all():
             count += 1
             setattr(profile, key, value)
         session.commit()
         flash("{count} profiles '{key}' were set to '{value}'".format(
             **locals()))
     except Exception as ex:
         if not self.handle_view_exception(ex):
             raise Exception("Ooops")
         flash('Failed to set {key}'.format(**locals()), 'error')
Beispiel #14
0
 def set_dags(self, ids, key, value, session=None):
     try:
         count = 0
         for dag_model in session.query(self.model).filter(
                 self.model.dag_id.in_(ids)).all():
             count += 1
             setattr(dag_model, key, value)
         session.commit()
         flash("{count} dag models '{key}' were set to '{value}'".format(
             **locals()))
     except Exception as ex:
         if not self.handle_view_exception(ex):
             raise Exception("Ooops")
         flash('Failed to set {key}'.format(**locals()), 'error')
Beispiel #15
0
def followed_by(username):
    user = User.query.filter_by(username=username).first()
    if user is None:
        flash(u'未找到用户')
        return redirect(url_for('.index'))
    page = request.args.get('page', 1, type=int)
    pagination = user.followed.paginate(
        page, per_page=current_app.config['FLASKY_FOLLOWERS_PER_PAGE'],
        error_out=False)
    followed = [{'user': item.followed, 'timestamp': item.timestamp}
                for item in pagination.items]
    return render_template('main/followed.html', user=user, title=u'关注的用户',
                           endpoint='.followed_by', pagination=pagination,
                           followed=followed)
Beispiel #16
0
def edit_profile():
    form = EditProfileForm()
    if form.validate_on_submit():
        current_user.name = form.name.data
        current_user.location = form.location.data
        current_user.about_me = form.about_me.data
        db.session.add(current_user)
        flash(u'修改资料成功')
        return redirect(url_for('.user', username=current_user.username))

    form.name.data = current_user.name
    form.about_me.data = current_user.about_me
    form.location.data = current_user.location
    return render_template('main/edit_profile.html', form=form)
Beispiel #17
0
def followed_by(username):
    user = User.query.filter_by(username=username).first()
    if user is None:
        flash('Invalid user.')
        return redirect(url_for('.index'))
    page = request.args.get('page', 1, type=int)
    pagination = user.followed.filter(Follow.followed_id != user.id).paginate(
        page, per_page=current_app.config['FLASKY_FOLLOWERS_PER_PAGE'],
        error_out=False)
    follows = [{'user': item.followed, 'timestamp': item.timestamp}
               for item in pagination.items]
    return render_template('followers.html', user=user, title="Followed by",
                           endpoint='.followed_by', pagination=pagination,
                           follows=follows)
def find_user_by_email_address():
    template = "view_users.html"
    users = None

    email_address = request.args.get("email_address", None)
    if email_address:
        users = data_api_client.get_user(
            email_address=request.args.get("email_address"))

    if users:
        return render_template(template,
                               users=[users['users']],
                               email_address=request.args.get("email_address"))
    else:
        flash('no_users', 'error')
        return render_template(template, users=list(), email_address=None), 404
Beispiel #19
0
def facebook_authorized(resp):
    next_url = flask_login.request.args.get('next') or url_for('root')
    if resp is None:
        # The user likely denied the request
        flask_login.flash(u'There was a problem logging in.')
        return flask_login.redirect(next_url)
    flask_login.session['oauth_token'] = (resp['access_token'], '')
    user_data = facebook.get('/me').data
    user = User.query.filter(User.email == user_data['email']).first()
    if user is None:
        new_user = User(email=user_data['email'],
                        first_name=user_data['first_name'],
                        last_name=user_data['last_name'])
        db_session.add(new_user)
        db_session.commit()
        flask_login.login_user(new_user)
    else:
        flask_login.login_user(user)
    return flask_login.redirect(next_url)
Beispiel #20
0
def login():
    form = LoginForm(request.form)
    error = None
    remember = False
    if request.method == 'POST' and form.validate_on_submit():
        user = User.query.filter(
            User.username == request.form['username']).first()
        if user:
            if bcrypt.check_password_hash(user.password, request.form['password']):
                if request.form.get('rememberme', ''):
                    remember = True
                login_user(user, remember=remember)
                flash("Logged in successfully.")
                return redirect(request.args.get("next") or url_for("index"))
            else:
                error = 'Invalid credentials'
        else:
            error = 'Invalid credentials'
    return render_template("login.html", form=form, error=error)
Beispiel #21
0
def followers(username):
    user = User.query.filter_by(username=username).first()
    if user is None:
        flash(u"用户不存在")
        return redirect(url_for('main.index'))
    #分页技术显示关注人
    page = request.args.get('page', 1, type=int)
    pagination = user.followers.paginate(
        page,
        per_page=current_app.config["FLASKY_FOLLOWERS_PER_PAGE"],
        error_out=False)
    follows = [{
        "user": item.follower,
        'timestamp': item.timestamp
    } for item in pagination.items]
    return render_template('followers.html',
                           user=user,
                           endpoint="main.followers",
                           pagination=pagination,
                           follows=follows)
def find_user_by_email_address():
    template = "view_users.html"
    users = None

    email_address = request.args.get("email_address", None)
    if email_address:
        users = data_api_client.get_user(email_address=request.args.get("email_address"))

    if users:
        return render_template(
            template,
            users=[users['users']],
            email_address=request.args.get("email_address"),
            **get_template_data())
    else:
        flash('no_users', 'error')
        return render_template(
            template,
            users=list(),
            email_address=None,
            **get_template_data()), 404
Beispiel #23
0
def move_user_to_new_supplier(supplier_id):
    move_user_form = MoveUserForm()

    try:
        suppliers = data_api_client.get_supplier(supplier_id)
        users = data_api_client.find_users(supplier_id)
    except HTTPError as e:
        current_app.logger.error(str(e), supplier_id)
        if e.status_code != 404:
            raise
        else:
            abort(404, "Supplier not found")

    if move_user_form.validate_on_submit():
        try:
            user = data_api_client.get_user(email_address=move_user_form.user_to_move_email_address.data)
        except HTTPError as e:
            current_app.logger.error(str(e), supplier_id)
            raise

        if user:
            data_api_client.update_user(
                user['users']['id'],
                role='supplier',
                supplier_id=supplier_id,
                active=True,
                updater=current_user.email_address
            )
            flash("user_moved", "success")
        else:
            flash("user_not_moved", "error")
        return redirect(url_for('.find_supplier_users', supplier_id=supplier_id))
    else:
        return render_template(
            "view_supplier_users.html",
            invite_form=EmailAddressForm(),
            move_user_form=move_user_form,
            users=users["users"],
            supplier=suppliers["suppliers"]
        ), 400
Beispiel #24
0
def remove_countersigned_agreement_file(supplier_id, framework_slug):
    agreements_bucket = s3.S3(current_app.config['DM_AGREEMENTS_BUCKET'])
    document = get_agreement_document_path(framework_slug, supplier_id, COUNTERSIGNED_AGREEMENT_FILENAME)

    if request.method == 'GET':
        flash('countersigned_agreement', 'remove_countersigned_agreement')

    if request.method == 'POST':
        agreements_bucket.delete_key(document)

        data_api_client.create_audit_event(
            audit_type=AuditTypes.delete_countersigned_agreement,
            user=current_user.email_address,
            object_type='suppliers',
            object_id=supplier_id,
            data={'upload_countersigned_agreement': document})

    return redirect(url_for(
        '.list_countersigned_agreement_file',
        supplier_id=supplier_id,
        framework_slug=framework_slug)
    )
Beispiel #25
0
def edit_profile_admin(id):
    user = User.query.get_or_404(id)
    form = EditProfileAdminForm(user=user)
    if form.validate_on_submit():
        user.email = form.email.data
        user.username = form.username.data
        user.confirmed = form.confirmed.data
        user.role = Role.query.get(form.role.data)
        user.name = form.name.data
        user.location = form.location.data
        user.about_me = form.about_me.data
        db.session.add(user)
        flash('The profile has been updated.')
        return redirect(url_for('.user', username=user.username))
    form.email.data = user.email
    form.username.data = user.username
    form.confirmed.data = user.confirmed
    form.role.data = user.role_id
    form.name.data = user.name
    form.location.data = user.location
    form.about_me.data = user.about_me
    return render_template('edit_profile.html', form=form, user=user)
Beispiel #26
0
def follow(username):
    user = User.query.filter_by(username=username).first()
    if user is None:
        flash('Invalid user.')
        return redirect(url_for('.index'))
    if current_user.is_following(user):
        flash('You are already following this user.')
        return redirect(url_for('.user', username=username))
    current_user.follow(user)
    flash('You are now following %s.' % username)
    return redirect(url_for('.user', username=username))
Beispiel #27
0
def unfollow(username):
    user = User.query.filter_by(username=username).first()
    if user is None:
        flash("Invalid user")
        return redirect(url_for('.index'))
    if not current_user.is_following(user):
        flash("You are already unfollowing this user")
        return redirect(url_for('.user', username=username))
    current_user.unfollow(user)
    flash("you are now unfolowing %s!" % username)
    return redirect(url_for('.user', username=username))
Beispiel #28
0
def follow(username):
    u = User.query.filter_by(username=username).first()
    if u is None:
        flash(u'未找到指定用户')
        return redirect(url_for('.index'))
    if current_user.is_following(u):
        flash(u'你已经关注他了')
        return redirect('.user', username=username)
    current_user.follow(u)
    flash(u'关注了{0}'.format(username))
    return redirect(url_for('.user', username=username))
Beispiel #29
0
def follow(username):
    user = User.query.filter_by(username=username).first()
    if user is None:
        flash(u"用户不存在")
        return redirect(url_for("main.index"))
    if current_user.is_following(user):
        flash(u"你已经关注了该用户")
        return redirect(url_for("main.user", username=username))
    current_user.follow(user)
    flash(u"你已经关注了%s" % username)
    return redirect(url_for("main.user", username=username))
Beispiel #30
0
def unfollow(username):
    user = User.query.filter_by(username=username).first()
    if user is None:
        flash('Invalid user.')
        return redirect(url_for('.index'))
    if not current_user.is_following(user):
        flash('You are not following this user.')
        return redirect(url_for('.user', username=username))
    current_user.unfollow(user)
    flash('You are not following %s anymore.' % username)
    return redirect(url_for('.user', username=username))
Beispiel #31
0
def unfollow(username):
    user = User.query.filter_by(username=username).first()
    if user is None:
        flash(u"用户不存在")
        return redirect(url_for('main.index'))
    if not current_user.is_following(user):
        flash(u'你并木有关注这个用户')
        return redirect(url_for('main.user', username=username))
    current_user.unfollow(user)
    db.session.commit()
    flash(u'你已经不再关注%s' % username)
    return redirect(url_for('main.user', username=username))
Beispiel #32
0
def invite_user(supplier_id):
    invite_form = EmailAddressForm()

    try:
        suppliers = data_api_client.get_supplier(supplier_id)
        users = data_api_client.find_users(supplier_id)
    except HTTPError as e:
        current_app.logger.error(str(e), supplier_id)
        if e.status_code != 404:
            raise
        else:
            abort(404, "Supplier not found")

    if invite_form.validate_on_submit():
        token = generate_token(
            {
                "supplier_id": supplier_id,
                "supplier_name": suppliers['suppliers']['name'],
                "email_address": invite_form.email_address.data
            },
            current_app.config['SHARED_EMAIL_KEY'],
            current_app.config['INVITE_EMAIL_SALT']
        )

        url = "{}{}/{}".format(
            request.url_root,
            current_app.config['CREATE_USER_PATH'],
            format(token)
        )

        email_body = render_template(
            "emails/invite_user_email.html",
            url=url,
            supplier=suppliers['suppliers']['name'])

        try:
            send_email(
                invite_form.email_address.data,
                email_body,
                current_app.config['DM_MANDRILL_API_KEY'],
                current_app.config['INVITE_EMAIL_SUBJECT'],
                current_app.config['INVITE_EMAIL_FROM'],
                current_app.config['INVITE_EMAIL_NAME'],
                ["user-invite"]
            )
        except MandrillException as e:
            current_app.logger.error(
                "Invitation email failed to send error {} to {} supplier {} supplier id {} ".format(
                    str(e),
                    invite_form.email_address.data,
                    current_user.supplier_name,
                    current_user.supplier_id)
            )
            abort(503, "Failed to send user invite reset")

        data_api_client.create_audit_event(
            audit_type=AuditTypes.invite_user,
            user=current_user.email_address,
            object_type='suppliers',
            object_id=supplier_id,
            data={'invitedEmail': invite_form.email_address.data})

        flash('user_invited', 'success')
        return redirect(url_for('.find_supplier_users', supplier_id=supplier_id))
    else:
        return render_template(
            "view_supplier_users.html",
            invite_form=invite_form,
            move_user_form=MoveUserForm(),
            users=users["users"],
            supplier=suppliers["suppliers"]
        ), 400