コード例 #1
0
ファイル: admin.py プロジェクト: loneshaana/WookieScanner
def new_blog():
    if not current_user.is_admin:
        return render_extensions('401.html')

    if request.method == 'POST':
        try:
            content = str(request.form['content'])
        except Exception:
            content = ''

        try:
            slug = str(request.form['slug'])
        except Exception:
            slug = ''

        try:
            title = str(request.form['title'])
        except Exception:
            title = ''

        post = Post(title=title, body=content, slug=slug)
        post.save()

        current_user.posts.append(post)
        current_user.save()

    return render_extensions('admin/new_blog.html')
コード例 #2
0
ファイル: views.py プロジェクト: jerkos/metabo-match
def register():
    """register a new software"""
    form = SoftwareForm()
    if form.validate_on_submit():
        form.save(request.form.getlist('selected_tags'))

        #update achivements
        c = db.session.query(Software.name).filter(Software.owner_id == current_user.id).count()
        goal = SoftwareAchievement.unlocked_level(c)
        if goal:
            flash('Achievement unlocked\n {} \n {}'.format(goal['name'], goal['description']), 'success')

        #update global score
        current_user.global_score += SCORE_SOFT
        current_user.save()

        #upload to s3
        if form.image.data:
            s3_upload(form.image, form.name.data.lower())
        else:
            s3_upload_from_server('static/img/placeholder.jpg', form.name.data.lower())

        return redirect(url_for('softwares.index'))

    last_soft_name = db.session.query(Software.name).order_by(desc(Software.insertion_date)).first()[0]
    tot_soft_count = db.session.query(Software.name).count()
    return render_template('softwares/register_software.html', form=form,
                           last_soft_name=last_soft_name, tot_soft_count=tot_soft_count)
コード例 #3
0
def profile_edit():
    # TODO: logging
    if request.method == "POST":
        if current_user.auth(request.values.get("password", None)) is True:
            try:
                if (request.form["new_password"] is not None
                        and len(request.form["new_password"]) > 0):
                    current_user.password = request.form["new_password"]
            except Exception as exc:
                if exc.args[0] == "too_short":
                    flash("Password too short, minimum length is 3", "warning")
                else:
                    app.logger.error(exc)
            else:
                current_user.display_name = request.form["display_name"]
                new_flags = request.form.getlist("flags")
                current_user.is_hidden = "hidden" in new_flags
                current_user.is_name_anonymous = "anonymous for public" in new_flags
                app.logger.info("flags: got {} set {:b}".format(
                    new_flags, current_user.flags))
                current_user.save()
                flash("Saved", "success")
        else:
            flash("Invalid password", "error")

    return render_template("profile.html",
                           user=current_user,
                           **common_vars_tpl)
コード例 #4
0
def account():
    form = UpdateAccountForm()

    if form.validate_on_submit():

        if form.picture.data:
            picture_file = save_picture(form.picture.data)
            current_user.image_file = picture_file

        current_user.username = form.username.data
        current_user.email = form.email.data

        try:
            current_user.save()
            flash(f'Account update.', 'success')
            return redirect(url_for('account'))
        except:
            flash(f'username and/or email is taken.', 'danger')

    elif request.method == 'GET':
        form.username.data = current_user.username
        form.email.data = current_user.email

    image_file = url_for('static',
                         filename='images/profile_pictures/' +
                         current_user.image_file,
                         _external=True)

    return render_template('account.html',
                           title='Account',
                           image_file=image_file,
                           form=form)
コード例 #5
0
def edit_profile():
    form1 = EditProfileForm(current_user.username)
    form2 = ChangeEmailForm(current_user.email)

    # Edit normal information
    if form1.submit_profile.data and form1.validate_on_submit():
        if current_user.username != form1.username.data:
            current_user.username = form1.username.data
        current_user.firstname = form1.firstname.data
        current_user.lastname = form1.lastname.data
        current_user.save()
        flash('Your changes have been saved.')
        return redirect(url_for('users.edit_profile'))

    # Edit sensitive fields (Require password)
    if form2.submit_email.data and form2.validate_on_submit():
        if not current_user.check_password(form2.password.data):
            flash('Invalid password.')
            return redirect(url_for('users.edit_profile'))
        if current_user.email != form2.email.data:
            current_user.email = form2.email.data
        current_user.save()
        flash('Your email address has been changed successfully.')
        return redirect(url_for('users.edit_profile'))

    form1.username.data = current_user.username
    form1.firstname.data = current_user.firstname
    form1.lastname.data = current_user.lastname
    form2.email.data = current_user.email
    return render_template('users/edit_profile.html',
                           title='Edit Profile',
                           form1=form1,
                           form2=form2)
コード例 #6
0
def account():
    username_form = UpdateUsernameForm()
    profile_pic_form = UpdateProfilePicForm()
    
    # We have to make sure the form was actually submitted before validating since we have 2 forms on one page
    if username_form.username.data is not None and username_form.submit.data and username_form.validate_on_submit():
        current_user.modify(username=username_form.username.data)
        current_user.save()
        login_user(current_user)

        return redirect(url_for('users.account'))

    if profile_pic_form.propic.data is not None and profile_pic_form.validate_on_submit():
        img = profile_pic_form.propic.data
        filename = secure_filename(img.filename)

        if current_user.profile_pic.get() is None:
            current_user.profile_pic.put(img.stream, content_type='images/png')
        else:
            current_user.profile_pic.replace(img.stream, content_type='images/png')
        current_user.save()

        return redirect(url_for('users.account'))

    image = images(current_user.username)

    return render_template("account.html", title="Account", username_form=username_form, profile_pic_form=profile_pic_form, image=image)
コード例 #7
0
ファイル: admin.py プロジェクト: loneshaana/WookieScanner
def edit_blog(blog_id):
    if not current_user.is_admin:
        return render_extensions('401.html')

    if request.method == 'POST':
        try:
            content = str(request.form['content'])
        except Exception:
            content = ''

        try:
            slug = str(request.form['slug'])
        except Exception:
            slug = ''

        try:
            title = str(request.form['title'])
        except Exception:
            title = ''

        post = Post(title=title, body=content, slug=slug)
        post.save()

        current_user.posts.append(post)
        current_user.save()

    post_obj = Post.query.filter_by(id=int(blog_id)).first()
    post_content = {
        'title': str(post_obj.title),
        'slug': str(post_obj.slug),
        'body': str(post_obj.body),
    }

    return render_extensions('admin/edit_blog.html', post=post_content)
コード例 #8
0
def get_my_status():
    try:
        status = current_user.get_my_status()
	current_user.status = status
        current_user.save()
        plat = current_user.get_platform_instance()
        if plat is not None:
            plat.status = status
            plat.save()
        return status
    except HTTPException as e:
	try:
            prod_error_instant_mail(
                error_num=22,
                object="{} get_my_status ".format(e),
                details="{}".format(sys.exc_info()),
                critical_level="ERROR")
	except:
	    print "error sending mail"
        raise e
    except:
        print "Unexpected error:", sys.exc_info()
        prod_error_instant_mail(
            error_num=23,
            object="500 get_my_status",
            details="{}".format(sys.exc_info()),
            critical_level="CRITICAL")
        abort(500)
コード例 #9
0
    def get(self):
        task_id = request.args.get('id')
        try:
            task = Task.objects.get(id=task_id)
        except ValidationError:
            return render_json({'type': 'error', 'message': u'Неверный таск'})
        if task in current_user.solved_tasks:
            return render_json({'type': 'error', 'message': u'Невозможно начать уже решенный таск'})
        if task in current_user.closed_tasks:
            return render_json({'type': 'error', 'message': u'Невозможно начать проваленный таск'})
        if task.solver:
            return render_json({'type': 'error', 'message': u'Таск уже решают'})
        if task.owner:
            cost = task.cost
        else:
            cost = task.base_cost
        if current_user.get_money() < cost:
            return render_json({'type': 'error', 'message': u'Денег нет?'})
        if len(Task.objects(solver=current_user.id)):
            return render_json({'type': 'error', 'message': u'Вы уже решаете таск, сначала завершите его.'})

        current_user.money -= cost
        current_user.task_started_at = datetime.datetime.now()
        current_user.save()
        print 'open task:', current_user.task_started_at, datetime.datetime.now()
        task.solver = current_user.to_dbref()
        task.save()

        return render_json({'type': 'success', 'message': u'Вы начали таск {}. Вы должны решить его за {} сек.'.format(task.name, task.base_time)})
コード例 #10
0
ファイル: forms.py プロジェクト: qitianchan/ash-bin
    def save_form(self):
        current_user.username = self.username.data
        current_user.telephone = self.telephone.data
        current_user.mobile_phone = self.mobile_phone.data
        current_user.address = self.address.data

        current_user.save()
コード例 #11
0
    def get(self):
        task_id = request.args.get('id', None)
        try:
            cost = abs(int(request.args.get('cost', None)))
        except ValueError:
            return render_json({'type': 'error', 'message': u'Неверная стоимость таска'})
        try:
            task = Task.objects.get(id=task_id)
        except DoesNotExist:
            return render_json({'type': 'error', 'message': u'Неверный таск id'})
        if task in current_user.solved_tasks:

            if current_user.get_money() < cost:
                return render_json({'type': 'error', 'message': u'Недостаточно денег!'})

            diff = (datetime.datetime.now() - task.last_solved_at)

            current_user.money += (diff.seconds // 60) * task.cost * 0.02
            current_user.money -= cost
            print('SetCoin: Current money - ' + current_user.money)

            current_user.save()

            task.last_solved_at = datetime.datetime.now()
            task.cost += cost
            task.save()
            return render_json({'type': 'success', 'message': u'Стоимость таска обновлена!'})
        else:
            return render_json({'type': 'error', 'message': u'Стоимость таска может менять только его хозяин.'})
コード例 #12
0
 def get(self):
     try:
         task = Task.objects.get(solver=current_user)
     except DoesNotExist:
         return render_json({'type': 'error', 'message': u'Для остановки времени нужно решать таск.'})
     try:
         duration = abs(int(request.args.get('duration', None)))
     except ValueError:
         return render_json({'type': 'error', 'message': u'Неверное время заморозки'})
     cost = duration * 10 / 60  # calculate cost from freeze duration
     if current_user.get_money() < cost:
         return render_json({'type': 'error', 'message': u'Недстаточно денег!'})
     else:
         if task.expired():
             return render_json({'type': 'error', 'message': u'Таск уже просрочен!'})
         freeze = Freeze.current(task)
         if freeze:
             # if we have mo then one added freeze in future append to end
             freezes = Freeze.objects(created_at__gt=freeze.created_at).order_by('-created_at')
             if len(freezes):
                 freeze = freezes[0]
             created = freeze.created_at + datetime.timedelta(seconds=freeze.duration)
         else:
             created = datetime.datetime.now()
         current_user.money -= cost
         current_user.save()
         freeze = Freeze(created_at=created, user=current_user.to_dbref(), task=task, duration=duration)
         freeze.save()
         return render_json({'type': 'success', 'message': u'Время таска заморожено!'})
コード例 #13
0
ファイル: forms.py プロジェクト: qitianchan/ash-bin
    def save_form(self):
        current_user.username = self.username.data
        current_user.telephone = self.telephone.data
        current_user.mobile_phone = self.mobile_phone.data
        current_user.address = self.address.data

        current_user.save()
コード例 #14
0
ファイル: admin.py プロジェクト: franc3000/investigator
def new_blog():
    if not current_user.is_admin:
        return render_extensions('401.html')

    if request.method == 'POST':
        try:
            content = str(request.form['content'])
        except Exception:
            content = ''

        try:
            slug = str(request.form['slug'])
        except Exception:
            slug = ''

        try:
            title = str(request.form['title'])
        except Exception:
            title = ''

        post = Post(title=title, body=content, slug=slug)
        post.save()

        current_user.posts.append(post)
        current_user.save()

    return render_extensions('admin/new_blog.html')
コード例 #15
0
ファイル: github_auth.py プロジェクト: weiqiangzheng/gitmark
def github_link_account_behavior():
    url = github_apis.auth_user()
    auth = OAuth2(client_id=client_id, token=session['oauth_user_token'])
    res = requests.get(url, auth=auth)
    if res.status_code != 200:
        msg = 'GitHub authorization failed'
        flash(msg, 'danger')
        return redirect(url_for('main.index'))

    github_user = res.json()
    username = github_user.get('login')
    email = github_user.get('email')
    github_url = github_user.get('html_url')
    github_avatar_url = github_user.get('avatar_url')

    if len(models.User.objects.filter(github_username=username)) > 0:
        msg = 'This GitHub account({0}) has been binded to another user'.format(
            username)
        flash(msg, 'danger')
        return redirect(url_for('main.index'))

    if not current_user.avatar_url:
        avatar_name = 'github_avatar_{0}.jpeg'.format(username)
        avatar_url = qiniu_fetch_img(github_avatar_url, avatar_name)
        current_user.avatar_url = avatar_url

    current_user.github_username = username
    current_user.github = github_url

    current_user.save()

    return redirect(url_for('main.index'))
コード例 #16
0
ファイル: blueprints.py プロジェクト: vanillaSlice/dawdle
def settings_update_email_POST():
    form = UpdateEmailForm(request.form, email=current_user.email)

    if not form.validate_on_submit():
        return render_template(
            'user/settings-update-email.html',
            form=form,
        ), 400

    if not form.update_needed():
        flash('No update needed.', 'info')
        return redirect(url_for('user.settings_update_email_POST'))

    current_user.active = False
    current_user.auth_id = ObjectId()
    current_user.email = form.email.data
    current_user.last_updated = datetime.utcnow()
    current_user.save()

    redirect_target = url_for('user.settings_update_email_POST')

    send_verification_email(current_user, redirect_target=redirect_target)

    return redirect(
        url_for(
            'auth.verify_resend_GET',
            email=form.email.data,
            next=redirect_target,
        ))
コード例 #17
0
ファイル: routes.py プロジェクト: engpetermwangi/NoticeBoard
def profile_edit():
    form = UpdateAccountForm()
    if request.method == 'POST' and form.validate_on_submit():
        try:
            picture_file = save_ppicture(form.pic.data)
            current_user.pic = picture_file
            bucket_name = 'profilepicsfornb'
            s3 = boto3.resource('s3')
            file = url_for('static', filename='profile_pics/' + picture_file)
            s3.Bucket(bucket_name).put_object(Key='profile_pics/' +
                                              picture_file,
                                              Body=file)
        except:
            pass
        print(current_user.pic)
        current_user.fullname = form.fullname.data
        current_user.telephone = form.telephone.data
        current_user.course = form.course.data
        current_user.year = form.year.data
        current_user.level = form.level.data
        current_user.save()
        flash('Your profile has been edited.', category='success')
        return redirect(url_for('profile'))
    elif request.method == 'GET':
        form.fullname.data = current_user.fullname
        form.telephone.data = current_user.telephone
        form.course.data = current_user.course
        form.level.data = current_user.level
        form.year.data = str(current_user.year)
    return render_template('profile_edit.html', form=form)
コード例 #18
0
def update_account():
    form = UpdateAccount()
    # checks the form and changes the data in the database
    if form.validate_on_submit():
        current_user.username = form.username.data
        current_user.email = form.email.data
        # if the user adds an image it calls the save user image
        # function from utils to upload image to cloudinary
        if form.user_image.data:
            image_url = save_user_image(form.user_image.data)
            current_user.user_image = image_url
        if form.bio.data:
            current_user.bio = form.bio.data
        current_user.save()
        return redirect(
            url_for("users.account", username=current_user.username))

    #  fills the form with the current data from the database
    elif request.method == "GET":
        form.username.data = current_user.username
        form.email.data = current_user.email
        if current_user.bio:
            form.bio.data = current_user.bio
    return render_template("users/update_account.html",
                           title="Update Account",
                           form=form)
コード例 #19
0
def account():
    username_form = UpdateUsernameForm()
    profile_pic_form = UpdateProfilePicForm()
    if username_form.validate_on_submit():
        # current_user.username = username_form.username.data
        current_user.modify(username=username_form.username.data)
        current_user.save()
        return redirect(url_for("users.account"))
    if profile_pic_form.validate_on_submit():
        img = profile_pic_form.propic.data
        filename = secure_filename(img.filename)

        if current_user.profile_pic.get() is None:
            current_user.profile_pic.put(img.stream, content_type='images/png')
        else:
            current_user.profile_pic.replace(img.stream, content_type='images/png')
        current_user.save()

        return redirect(url_for('users.account'))
    image = images(current_user.username)

    return render_template(
        "account.html",
        title="Account",
        username_form=username_form,
        profile_pic_form=profile_pic_form, image=image
    )
コード例 #20
0
ファイル: main.py プロジェクト: tomgrubbmath/lmfdb
def set_info():
    for k, v in request.form.items():
        if v:
            setattr(current_user, k, v)
    current_user.save()
    flask.flash(Markup("Thank you for updating your details!"))
    return flask.redirect(url_for(".info"))
コード例 #21
0
def apply():
    if not current_user.status in ['none', 'reject', 'applying']:
        abort(403)
    form = ApplyForm(request.form, current_user)
    if request.method == 'POST':
        if form.validate_on_submit():
            name = form['name'].data
            studentno = form['studentno'].data
            phone = form['phone'].data
            reason = form['reason'].data
            agree = form['agree'].data
            if not agree:
                flash('You must agree to the constitution', 'error')
            else:
                current_user.status = 'applying'
                current_user.name = name
                current_user.studentno = studentno
                current_user.phone = phone
                current_user.reason = reason
                current_user.applytime = datetime.datetime.now()
                current_user.save()
                html = 'Name: ' + name + \
                       '<br>Student/Staff No: ' + studentno + \
                       '<br>Phone: ' + phone + \
                       '<br>Reason: ' + reason
                send_mail('New VPN Application: ' + name, html, app.config['ADMIN_MAIL'])
                return redirect(url_for('index'))
    return render_template('apply.html', form=form)
コード例 #22
0
ファイル: admin.py プロジェクト: franc3000/investigator
def edit_blog(blog_id):
    if not current_user.is_admin:
        return render_extensions('401.html')

    if request.method == 'POST':
        try:
            content = str(request.form['content'])
        except Exception:
            content = ''

        try:
            slug = str(request.form['slug'])
        except Exception:
            slug = ''

        try:
            title = str(request.form['title'])
        except Exception:
            title = ''

        post = Post(title=title, body=content, slug=slug)
        post.save()

        current_user.posts.append(post)
        current_user.save()

    post_obj = Post.query.filter_by(id=int(blog_id)).first()
    post_content = {
        'title': str(post_obj.title),
        'slug': str(post_obj.slug),
        'body': str(post_obj.body),
    }

    return render_extensions('admin/edit_blog.html', post=post_content)
コード例 #23
0
def set_info():
    raw_data = request.form
    if raw_data.get("submit") == "cancel":
        return redirect(url_for(".info"), 301)
    errmsgs = []
    print("raw_data: %s" % dict(raw_data))
    prefs = [{} for i in range(len(current_user.classes) + 1)]
    sprefs = [{} for i in range(len(current_user.classes) + 1)]
    data = {"preferences": prefs[0], "strengths": sprefs[0]}
    data["hours"] = [[False for j in range(24)] for i in range(7)]
    for i in range(7):
        for j in range(24):
            if raw_data.get("check-hours-%d-%d" % (i, j), False):
                data["hours"][i][j] = True

    # Need to do data validation
    for col, val in raw_data.items():
        if col in db.students.col_type:
            try:
                typ = db.students.col_type[col]
                data[col] = process_user_input(val, col, typ)
            except Exception as err:
                errmsgs.append(format_input_errmsg(err, val, col))
        elif PREF_RE.match(col) and val.strip():
            t = col.split('-')
            if t[1] in preference_types:
                n = int(t[2])
                p = prefs[n] if col[0] == 'p' else sprefs[n]
                try:
                    typ = preference_types[t[1]] if col[0] == 'p' else "posint"
                    p[t[1]] = process_user_input(val, t[1], typ)
                except Exception as err:
                    errmsgs.append(format_input_errmsg(err, val, col))
        elif col.startswith("hours-"):
            try:
                i, j = (int(x) for x in col[6:].split("-"))
                data["hours"][i][j] = True
            except Exception as err:
                errmsgs.append(format_input_errmsg(err, val, col))
    # There should never be any errors coming from the form
    if errmsgs:
        return show_input_errors(errmsgs)
    for i in range(len(current_user.classes)):
        current_user.class_data[
            current_user.classes[i]]["preferences"] = prefs[i + 1]
        current_user.class_data[current_user.classes[i]]["strengths"] = sprefs[
            i + 1]
    data["classes"] = list_of_strings(raw_data.get("classes", []))
    print("data: %s" % data)
    for k, v in data.items():
        setattr(current_user, k, v)
    current_user.save()
    try:
        #current_user.save()
        flash_info("Changes saved.")
    except Exception as err:
        flash_error("Error saving changes: %s" % err)

    return redirect(url_for(".info"), 301)
コード例 #24
0
def account(username):
    if current_user.is_authenticated:
        print("user auth true")
        updateUsernameForm = UpdateUsernameForm()
        postItemForm = PostItemForm()
        updatePhotoForm = UpdateProfilePicForm()
        if request.method == "POST":
            print("hit post method")
            submitter = request.form['submit']
            if submitter == "Update Username":  #USERNAME UPDATE FORM
                if updateUsernameForm.submit.data:
                    if updateUsernameForm.validate_on_submit():
                        newUsername = updateUsernameForm.username.data
                        current_user.modify(username=newUsername)
                        current_user.save()
                        return redirect(url_for("bpUser  .logout"))
            if submitter == "Publish your listing":  #POSTING A PROPERTY FORM
                if postItemForm.submit.data:
                    if postItemForm.validate_on_submit():
                        item = Item(
                            poster=current_user._get_current_object(),
                            price=postItemForm.price.data,
                            rooms=postItemForm.rooms.data,
                            restrooms=postItemForm.restrooms.data,
                            propertyType=postItemForm.propertyType.data,
                            description=postItemForm.description.data,
                            date=current_time())
                        item.save()
                        return redirect(url_for("bpItem.index"))
            if submitter == 'Update profile picture':  # CHECKING FOR PRO-PIC UPDATE FORM
                print("submitter:", submitter)
                if updatePhotoForm.submit.data:
                    print("photo form data:", updatePhotoForm.submit.data)
                    if updatePhotoForm.validate_on_submit():
                        print("photo form validated")
                        img = updatePhotoForm.photo.data
                        print("img: ", img)
                        filename = secure_filename(img.filename)
                        print("filename:", filename)
                        contentType = f'images/{filename[-3:]}'
                        print("contentType: ", contentType, filename[-3:], img)
                        print(".get(): ", current_user.profilePic.get())
                        if current_user.profilePic.get() is None:
                            print("current_user.profilePic.get() is none")
                            current_user.profilePic.replace(
                                img.stream, contentType=contentType)
                            print("after ")
                        else:
                            print("current_user.profilePic.get() was not None")
                            current_user.profilePic.replace(
                                img.stream, contentType=contentType)
                        current_user.save()
        print("gonna hit final render")
        return render_template("account.html",
                               title="Account",
                               updateUsernameForm=updateUsernameForm,
                               updatePhotoForm=updatePhotoForm,
                               image=get_b64_img(current_user.username),
                               postItemForm=postItemForm)
コード例 #25
0
ファイル: setpassword.py プロジェクト: JunctionAt/JunctionWWW
def setpassword():
    form = SetPasswordForm(request.form)
    if request.method == "POST" and form.validate():
        current_user.hash = bcrypt.hashpw(form.password.data, bcrypt.gensalt())
        current_user.save()
        flash('Your password has been changed.', category="success")
        return redirect(current_user.get_profile_url()), 303
    return render_template("setpassword_settings_pane.html", form=form, user=current_user, settings_panels_structure=settings_panels_structure, title="Change Password - Account - Settings")
コード例 #26
0
ファイル: views.py プロジェクト: andriyor/soc-counter
def user_profile():
    form = LinksForm()
    if form.validate_on_submit():
        links = Links(form.youtube.data, form.twitter.data,
                      form.instagram.data, form.facebook.data)
        current_user.links = links
        current_user.save()
    return render_template('user_profile.html', form=form)
コード例 #27
0
ファイル: views.py プロジェクト: chazzy1/erks_ask
def delete_profile_img():
    if current_user.profile_imgf:
        current_user.profile_imgf.delete()
        current_user.profile_imgf = None
        current_user.save()
    return redirect(
        request.args.get('next') or request.referrer
        or url_for('portal.index'))
コード例 #28
0
ファイル: utils.py プロジェクト: elprice/terminal
def passwd(new_pass):
	""" Update the current logged in user password. """
	if not current_user.is_authenticated:
		return "Must be logged in to change password."

	current_user.password_hash = generate_password_hash(new_pass)
	current_user.save()
	return "Password changed."
コード例 #29
0
ファイル: views.py プロジェクト: PPPython/flaskbb
def change_password():
    form = ChangePasswordForm()
    if form.validate_on_submit():
        current_user.password = form.new_password.data
        current_user.save()

        flash(_("Password updated."), "success")
    return render_template("user/change_password.html", form=form)
コード例 #30
0
ファイル: views.py プロジェクト: rcharp/parser
def switch_mailboxes():

    mailbox_id = request.form.get('mailboxes')

    current_user.mailbox_id = mailbox_id
    current_user.save()

    return redirect(url_for('user.refresh'))
コード例 #31
0
ファイル: views.py プロジェクト: highsoul/dky
def kickout(user_id):
    user = User.query.get(user_id)
    if not user:
        abort(404)
    else:
        current_user.owned_group.members.remove(user)
        current_user.save()
        return redirect(url_for("president.member_manage"))
コード例 #32
0
ファイル: view.py プロジェクト: Rampaul770/fastotv_site_new
 def apply_channels(self):
     current_user.streams = []
     json_str = request.form['apply_channels_official_ids']
     if json_str:
         for sid in json.loads(json_str):
             current_user.streams.append(ObjectId(sid))
     current_user.save()
     return redirect(url_for('SubscriberView:channels'))
コード例 #33
0
    def post(self):
        form = self.form()
        if form.validate_on_submit():
            current_user.password = form.new_password.data
            current_user.save()

            flash(_("Password updated."), "success")
        return render_template("user/change_password.html", form=form)
コード例 #34
0
    def post(self):
        form = self.form(current_user)
        if form.validate_on_submit():
            current_user.email = form.new_email.data
            current_user.save()

            flash(_("Email address updated."), "success")
        return render_template("user/change_email.html", form=form)
コード例 #35
0
def delete_voeux():
    del_form = DeleteVoeuxForm()
    if del_form.validate_on_submit():
        current_user.voeu_1 = None
        current_user.voeu_2 = None
        current_user.voeux_annee = None
        current_user.save()
    return redirect(url_for("voeux"))
コード例 #36
0
ファイル: user.py プロジェクト: jsfuentes/Signal-OG
def reddit_auth():
    reddit_code = request.args["code"]
    #TODO: verify state
    reddit = Reddit(app.config)
    refresh_token = reddit.getRefreshToken(reddit_code)
    current_user.reddit_refresh_token = refresh_token
    current_user.save()
    return redirect(url_for('user.index'))
コード例 #37
0
ファイル: views.py プロジェクト: PPPython/flaskbb
def change_email():
    form = ChangeEmailForm(current_user)
    if form.validate_on_submit():
        current_user.email = form.new_email.data
        current_user.save()

        flash(_("E-Mail Address updated."), "success")
    return render_template("user/change_email.html", form=form)
コード例 #38
0
ファイル: views.py プロジェクト: marvinwu/flaskbb
def change_email():
    form = ChangeEmailForm(current_user)
    if form.validate_on_submit():
        current_user.email = form.new_email.data
        current_user.save()

        flash(_("E-Mail Address updated."), "success")
    return render_template("user/change_email.html", form=form)
コード例 #39
0
ファイル: profile.py プロジェクト: Michael-Jalloh/atom
	def post(self):
		form = self.get_context()
		
		if form.validate():
			form.populate_obj(current_user)
			current_user.save()
			
			return render_template('profile/user.html',user=current_user)
		return render_template('profile/detail.html')
コード例 #40
0
def define_first_phone_number():
    os = request.form['os']
    reg_id = request.form['reg_id']
    phone_number = request.form['phone_number']
    code = 'samplecode' 
    try:
	plat = current_user.get_platform_instance()
	other_plats = current_user.get_contact_from_num(phone_number)
	if plat is None:
	    if other_plats is not None:
		print other_plats
                print "phone number {} already taken...".format(phone_number)
                abort(406)
	else:
	    print plat.phone_num,plat.reg_id
	    if plat.phone_num != phone_number:
		if other_plats is not None and other_plats["user_id"] != str(current_user.id):
                    print "phone number {} already taken...".format(phone_number)
                    abort(406)
	    else:
		if plat.reg_id==reg_id:
		    print "no new platform created"
		    current_user.check_bottles()
                    current_user.save()
                    return ""
	print "new platform created"
        platform = models.PlatformInstance(
            is_verified=False,
            verification_code=code,
            phone_num=phone_number,
            user_id=current_user.id,
            reg_id=reg_id,
            os=os)
        platform.save()
        current_user.platform_instance = platform.id
	current_user.check_bottles()
        current_user.save()
        return ""
    except HTTPException as e:
	try:
            print "Unexpected error:", sys.exc_info()
            prod_error_instant_mail(
                error_num=15,
                object="{} define_first_phone_number ".format(e),
                details="{}".format(sys.exc_info()),
                critical_level="ERROR")
	except:
	    print "error sending mail"
        raise e
    except:
        print "Unexpected error:", sys.exc_info()
        prod_error_instant_mail(
            error_num=14,
            object="500 define_first_phone_number",
            details="{}".format(sys.exc_info()),
            critical_level="CRITICAL")
        abort(500)
コード例 #41
0
ファイル: cern.py プロジェクト: k3njiy/invenio
def account_setup(remote, token):
    """Perform additional setup after user have been logged in."""
    response = remote.get(REMOTE_APP_RESOURCE_API_URL)

    if response.status == requests.codes.ok:
        res = get_dict_from_response(response)
        current_user.info["group"] = fetch_groups(res["{0}/{1}".format(REMOTE_APP_RESOURCE_SCHEMA, "Group")])
        current_user.modified = True
        current_user.save()
コード例 #42
0
ファイル: BookController.py プロジェクト: Cirreth/orglib
def book_get(book_id):
    b = Book.get(book_id)
    if not b:
        abort(404)
    if not b.is_public:
        abort(403)
    if not current_user.has_book(b):
        current_user.books.append(b)
        current_user.save()
    return redirect(url_for("public"))
コード例 #43
0
ファイル: views.py プロジェクト: jerkos/metabo-match
def register_user(name):
    """
    add a user to software users slot
    :param name:
    :return:
    """
    soft = Software.query.filter(Software.name == name).first_or_404()
    current_user.softwares_used.append(soft)
    current_user.save()
    return redirect(url_for('softwares.info', name=name))
コード例 #44
0
ファイル: web.py プロジェクト: Leo137/tarea_taller_python_web
def index():
    form_delete = DeleteAccountForm(request.form,user_id=str(current_user.id))
    form = ChangeNameForm(request.form)
    if form.validate_on_submit():
        try:
            current_user.nombre = form.new_username.data
            current_user.save()
        except:
            None
    return render_template('hola.html',form=form,form_delete=form_delete)
コード例 #45
0
ファイル: forms.py プロジェクト: qitianchan/ash-bin
    def save_wechat_id(self):
        # 验证验证码是否存在
        redis = Redis()


        if redis_store.exists(self.auth_key.data):
            current_user.wechat_id = redis_store.get(self.auth_key.data)
            current_user.save()
        else:
            flash(u'验证码错误', 'danger')
コード例 #46
0
ファイル: main.py プロジェクト: damienSeffray/LostInNetwork
def settings():
    form = SettingsForm(request.form)
    if form.validate_on_submit():
        if form.newpassword.data and form.oldpassword.data and form.repeat.data:
            current_user.set_password(form.newpassword.data)
            current_user.save()
            flash("Successfully set new password")
        return redirect(url_for('settings'))
    else:
        return render_template("settings.html", form=form)
コード例 #47
0
ファイル: BookController.py プロジェクト: Cirreth/orglib
def book_remove(book_id):
    b = Book.get(book_id)
    if not b:
        abort(404)
    if not b.is_public:
        abort(403)
    if current_user.has_book(b):
        current_user.books.remove(b)
        current_user.save()
    return redirect(url_for("main"))
コード例 #48
0
ファイル: user.py プロジェクト: franc3000/investigator
def change_username():
    form = UsernameForm()
    if form.validate_on_submit():
        current_user.username = form.username.data
        current_user.save()
        return redirect(url_for('user.profile'))
    else:
        flash_errors(form)

    return render_extensions('users/change_username.html', resetform=form)
コード例 #49
0
ファイル: user.py プロジェクト: franc3000/investigator
def change_password():
    form = PasswordForm()
    if form.validate_on_submit():
        current_user.set_password(form.password.data)
        current_user.save()
        return redirect(url_for('user.profile'))
    else:
        flash_errors(form)

    return render_extensions('users/change_password.html', resetform=form)
コード例 #50
0
ファイル: views.py プロジェクト: xiaode-c/Question
def confirm(token):
    if current_user.confirmed:
        return redirect(url_for('main.index'))
    if current_user.confirm(token):
        current_user.confirmed = True
        current_user.save()
        flash('You confirmed your account.Thanks!')
    else:
        flash('The confirmation link is Invalid or has expried.')
    return redirect(url_for('main.index'))
コード例 #51
0
ファイル: views.py プロジェクト: PPPython/flaskbb
def change_user_details():
    form = ChangeUserDetailsForm(obj=current_user)

    if form.validate_on_submit():
        form.populate_obj(current_user)
        current_user.save()

        flash(_("Details updated."), "success")

    return render_template("user/change_user_details.html", form=form)
コード例 #52
0
ファイル: views.py プロジェクト: highsoul/dky
def password_setting():
    old_pwd = request.form["old_password"]
    new_pws = request.form["new_password"]
    if current_user.check_password(old_pwd):
        current_user.password = new_pws
        current_user.save()
        flash("密码修改成功", "success")
    else:
        flash("密码修改失败", "error")
    return redirect(url_for(request.args["next"]))
コード例 #53
0
def welcome():
    form = WelcomeForm()

    if form.validate_on_submit():
        current_user.username = request.form.get('username')
        current_user.save()

        flash(_('Sign up is complete, enjoy our services.'), 'success')
        return redirect(url_for('billing.pricing'))

    return render_template('user/welcome.jinja2', form=form)
コード例 #54
0
def update_locale():
    form = UpdateLocale(locale=current_user.locale)

    if form.validate_on_submit():
        form.populate_obj(current_user)
        current_user.save()

        flash(_('Your locale settings have been updated.'), 'success')
        return redirect(url_for('user.settings'))

    return render_template('user/update_locale.jinja2', form=form)
コード例 #55
0
ファイル: decorator.py プロジェクト: gongxiujin/rgcpis
 def decorated_function(*args, **kwargs):
     if current_user.is_authenticated:
         current_time = datetime.datetime.now()
         if current_user.update_date and (current_time - current_user.update_date).seconds > 30:
             if current_user.update_date and current_user.update_ip:
                 current_user.lastip = current_user.update_ip
                 current_user.lastseen = current_user.update_date
             current_user.update_date = current_time
             current_user.update_ip = get_remote_addr(request)
             current_user.save()
     return func(*args, **kwargs)
コード例 #56
0
ファイル: views.py プロジェクト: XiongZhijun/simple-flask
def change_password():
    form = ChangePasswordForm()
    if form.validate_on_submit():
        if current_user.check_password(form.old_password.data):
            current_user.password = form.password.data
            current_user.save()
            flash('Your password has been updated.')
            return redirect(url_for('main.index'))
        else:
            flash('Invalid password.')
    return render_template("auth/change_password.html", form=form)
コード例 #57
0
ファイル: api.py プロジェクト: tiramiseb/awesomeshop
 def put(self):
     language = request.get_json().get('lang')
     if language:
         if current_user.is_authenticated:
             # Save language in the user's preferences
             current_user.locale = language
             current_user.save()
             return {'status': 'ok'}
         else:
             # Store language in a cookie
             session['locale'] = language
             return {'status': 'ok'}
コード例 #58
0
ファイル: views.py プロジェクト: OPWEN/opwen-webapp
def register_complete() -> Response:
    send_welcome_email = SendWelcomeEmail(
        time=datetime.utcnow(),
        to=current_user.email,
        email_store=app.ioc.email_store)

    send_welcome_email()

    current_user.language = Session.get_current_language()
    current_user.save()

    flash(i8n.ACCOUNT_CREATED, category='success')
    return redirect(url_for('email_inbox'))
コード例 #59
0
ファイル: views.py プロジェクト: knarfeh/HiaBlog
    def post(self):
        form = forms.PasswordForm(obj=request.form)
        if form.validate():
            # if not current_user.verify_password(form.current_password.data):
            #     return 'current password error', 403
            current_user.password = form.new_password.data
            current_user.save()
            # return 'waiting to code'
            msg = 'Succeed to update password'
            flash(msg, 'success')

            return redirect(url_for('auth.password'))

        return self.get(form)