コード例 #1
0
ファイル: deathmap.py プロジェクト: ilushka/deathmap
def user():
  dbuser = db.session.query(User).filter_by(username=current_user.id).first()
  if dbuser is None:
    abort(401)

  if request.method == "POST":
    # update user info
    new_user = UserDecoder().decode(request.json)
    if new_user is None:
      print "Failed to decode request.json"
      abort(400)
    dbuser.update_with_user(new_user)

    # change password
    if len(request.json.get("oldpassword", "")) > 0 \
        and len(request.json.get("newpassword", "")) > 0:
      # check old password
      if current_user.check_password(request.json["oldpassword"]):
        current_user.set_password(request.json["newpassword"])
        dbuser.password_hash = current_user.pw_hash

    db.session.commit()
    return jsonify({})

  return render_template("user.html", current_dbuser=dbuser)
コード例 #2
0
ファイル: deathmap.py プロジェクト: ilushka/deathmap
def user():
  dbuser = db.session.query(User).filter_by(username=current_user.id).first()
  if dbuser is None:
    abort(401)

  if request.method == "POST":
    # update user info
    new_user = UserDecoder().decode(request.json)
    if new_user is None:
      print "Failed to decode request.json"
      abort(400)
    dbuser.update_with_user(new_user)

    # change password
    if len(request.json.get("oldpassword", "")) > 0 \
        and len(request.json.get("newpassword", "")) > 0:
      # check old password
      if current_user.check_password(request.json["oldpassword"]):
        current_user.set_password(request.json["newpassword"])
        dbuser.password_hash = current_user.pw_hash

    db.session.commit()
    return jsonify({})

  return render_template("user.html", current_dbuser=dbuser)
コード例 #3
0
ファイル: __init__.py プロジェクト: sileht/flask-userbrowser
def settings():
    class SettingsForm(Form):
        password = PasswordField("Mot de passe")
        password_bis = PasswordField("Mot de passe (Bis)")

        def validate(self):
            rv = Form.validate(self)
            if not rv:
                return False

            if form.password.data != form.password_bis.data:
                self.password_bis.errors.append(
                    'Les mot de passe ne correspondent pas')
                return False

            return True

    form = SettingsForm()
    if form.validate_on_submit():
        current_user.set_password(form.password.data)
        flash("Mot de passe changé")
        return redirect('/browser')
    else:
        flash("Les mot de passe ne corresponds pas")

    return render_template("settings.html",
                           form=form)
コード例 #4
0
ファイル: views.py プロジェクト: samadmoiz/stacksites
def change_password():
    form = ChangePasswordForm()
    if form.validate_on_submit():
        current_user.set_password(form.new_password.data)
        current_user.save()
        flash('Your password has been changed.', 'success')
        return redirect(url_for('users.settings'))
    return settings(passwordForm=form)
コード例 #5
0
ファイル: views.py プロジェクト: jasonvfang/StackSites
def change_password():
    form = ChangePasswordForm()
    if form.validate_on_submit():
        current_user.set_password(form.new_password.data)
        current_user.save()
        flash('Your password has been changed.', 'success')
        return redirect(url_for('users.settings'))
    return settings(passwordForm=form)
コード例 #6
0
def account_settings():
    form = ChangePasswordForm(user=current_user)
    if form.validate_on_submit():
        current_user.set_password(form.new_password.data)
        db.session.commit()
        flash("Your password is successfully changed.", 'success')
        return redirect(url_for('home'))
    return render_template('users/settings.html', form=form)
コード例 #7
0
ファイル: views.py プロジェクト: ErwanTremiot/notejam
def account_settings():
    form = ChangePasswordForm(user=current_user)
    if form.validate_on_submit():
        current_user.set_password(form.new_password.data)
        db.session.commit()
        flash("Your password is successfully changed.", 'success')
        return redirect(url_for('home'))
    return render_template('users/settings.html', form=form)
コード例 #8
0
ファイル: views.py プロジェクト: codeforamerica/recordtrac
def update_password(password=None):
	if request.method == 'POST':
		current_user.set_password(request.form['password'])
		db.session.add(current_user)
		db.session.commit()
		app.logger.info("\n\nSuccessfully updated password for user %s" % current_user.id)
		return index()
	else:
		return render_template('update_password.html')
コード例 #9
0
def reset_password():
    form = ResetPasswordForm()
    if form.validate_on_submit():
        current_user.set_password(form.password.data)
        db.session.add(current_user)
        db.session.commit()
        flash('Your password changed successfully.')
        return redirect(url_for('main.index'))
    return render_template('auth/reset_password.html', form=form)
コード例 #10
0
ファイル: auth.py プロジェクト: ogurtsov/funicular
def profile():
    form = ProfileForm()
    if request.method == 'POST':
        form = ProfileForm(request.form)
        if form.validate():
            current_user.set_password(form.new_password.data)
            current_user.save()
            flash({'type':'success', 'text':'Password updated'})
            return redirect('/')
    return render_template("/auth/profile.html", **locals())
コード例 #11
0
ファイル: views.py プロジェクト: iverasp/flask-recipes
def update_password():
    update_password_form = UpdatePasswordForm()
    if update_password_form.validate_on_submit():
        current_user.set_password(update_password_form.password.data)
        db.session.commit()
        flash('Password updated', 'info')
        return redirect(url_for('account'))
    else:
        #flash(update_password_form.messages)
        return redirect(url_for('account'))
コード例 #12
0
def update_password(password=None):
    if request.method == 'POST':
        current_user.set_password(request.form['password'])
        db.session.add(current_user)
        db.session.commit()
        app.logger.info("\n\nSuccessfully updated password for user %s" %
                        current_user.id)
        return index()
    else:
        return render_template('update_password.html')
コード例 #13
0
ファイル: users.py プロジェクト: uppfinnarn/storybox
def me_edit_login():
	form = UserEditLoginForm(obj=current_user)
	if form.validate_on_submit():
		if not current_user.check_password(form.old_password.data):
			form.old_password.errors.append('Incorrect Password')
		else:
			current_user.username = form.username.data
			current_user.set_password(form.password.data)
			db.session.commit()
			return redirect('.me')
	return render_template('users/me_edit_login.html', user=current_user, form=form)
コード例 #14
0
def change_password():
    """
    Change logged in user's password.
    """
    form = ChangePasswordForm(request.json_multidict)
    if not form.validate_on_submit():
        return api_error(form.errors)
    if not current_user.check_password(form.current.data):
        return api_error(dict(form=['Current password is incorrect.']))
    current_user.set_password(form.new_password.data)
    current_user.save()
    return '', 200
コード例 #15
0
def profile():
    form = ChangePass()
    if form.validate_on_submit():
        current_user.set_password(form.new_password.data)
        current_user.save()
        return redirect(url_for(resolve_confirm_status(current_user)))
    return set_template('panelbuilder.html',
                        form,
                        '.profile',
                        panel_args=dict(
                            patex=current_app.config['PAHDS']['profile'],
                            tadata=current_app.config['TADATA']['profile']))
コード例 #16
0
ファイル: session.py プロジェクト: thomasDOTde/ffbackbone
def change_password():
    form = ChangePasswordForm()
    if form.validate_on_submit():
        if current_user.verify_password(form.old_password.data):
            current_user.set_password(form.password.data)
            db.session.add(current_user)
            db.session.commit()
            flash('Your password has been updated.')
            return redirect(url_for('index'))
        else:
            flash('Invalid password.')
    return render_template("auth/change_password.html", form=form)
コード例 #17
0
ファイル: views.py プロジェクト: hreeder/ignition
def change_password():
    form = NewPasswordForm()
    if form.validate_on_submit():
        current_user.set_password(form.password.data)
        db.session.add(current_user)
        db.session.commit()

        flash("Password changed successfully!", "success")
        return redirect(url_for("core.profile"))
    else:
        flash_errors(form)
    return render_template("core/change_password.html", form=form)
コード例 #18
0
ファイル: register.py プロジェクト: patelkanuv/UserProfile
def service_reset_password():
    params = json.loads(request.get_data(cache=False, as_text=True))
    form = ResetPasswordForm.from_json(params)
    if form.validate_on_submit():
        current_user.set_password(form.password.data)
        db.session.add(current_user)
        db.session.commit()
        data = { 'message' : 'Your password changed successfully.',
                 'success': True }
    else:
        data = { 'error' : form.errors, 'success': False }
    return jsonify(data)
コード例 #19
0
ファイル: session.py プロジェクト: thomasDOTwtf/ffbackbone
def change_password():
    form = ChangePasswordForm()
    if form.validate_on_submit():
        if current_user.verify_password(form.old_password.data):
            current_user.set_password(form.password.data)
            db.session.add(current_user)
            db.session.commit()
            flash('Your password has been updated.')
            return redirect(url_for('index'))
        else:
            flash('Invalid password.')
    return render_template("auth/change_password.html", form=form)
コード例 #20
0
ファイル: shell.py プロジェクト: mikeboers/Spoon
def passwd(args, pass_=None):

    if pass_ is None:
        print 'Resetting password for "%s".' % current_user.name
        pass_ = getpass.getpass('New password: '******'Verify password: '******'Passwords do not match.'
            return 1

    current_user.set_password(pass_)
    db.session.commit()
    print 'Password updated.'
コード例 #21
0
ファイル: account.py プロジェクト: ruitian/VirtualJudge
 def post(self):
     form = ChangePasswordForm()
     if not form.validate():
         return render_template(self.template, form=form)
     if current_user.verify_password(form.old_password.data):
         current_user.set_password(form.password.data)
         current_user.save()
         flash('Your password has been updated.')
         logout_user()
         return redirect(url_for('auth.login'))
     else:
         flash('Invalid password.')
     return redirect(url_for('user.account'))
コード例 #22
0
ファイル: frontend.py プロジェクト: jakkdu/qual
def mypage():
    form = MypageForm(request.form)
    if request.method == 'GET':
        form.realname.data = current_user.realname
        form.nickname.data = current_user.nickname
    next = request.args.get('next') or url_for('frontend.index')
    if request.method == 'POST' and form.validate():
        current_user.realname = form.realname.data
        current_user.nickname = form.nickname.data
        current_user.set_password(form.password.data)
        db.session.commit()
        return redirect(next)
    return render_template('mypage.html', form=form, next=next)
コード例 #23
0
ファイル: views.py プロジェクト: borjaeg/starter
def settings():
    form = None
    if current_user.service == 'local':
        form = SettingsForm(request.form, current_user)
    if request.method == 'POST' and form.validate():
        current_user.email = form.email.data
        current_user.name = form.name.data
        if form.password.data != None:
            current_user.set_password(form.password.data)
            flash("You updated your password.")
        current_user.save()
        flash("You updated your settings.")
    return render_template('settings.html', form=form)
コード例 #24
0
ファイル: main.py プロジェクト: jpeddicord/mmcbox
def change_password():
    """Change password form."""

    form = ChangePasswordForm()
    if form.validate_on_submit():
        current_user.set_password(form.password.data)
        current_user.activation = None
        db.session.add(current_user)
        db.session.commit()
        flash("Password changed.", 'success')
        return redirect(url_for('index'))

    return dict(form=form)
コード例 #25
0
ファイル: user.py プロジェクト: dankolbman/travel_blahg
def edit_profile():
  form = EditProfileForm(username=current_user.username,\
                         email=current_user.email,\
                         api_key=current_user.api_key)
  if form.validate_on_submit():
    current_user.email = form.email.data
    if len(form.password.data)>5 and form.password.data == form.password2.data:
      current_user.set_password(form.password.data)

    db.session.commit()
    flash('Your profile has been updated.')
    return redirect(url_for('main.index'))
  return render_template('user/edit_profile.html', form=form)
コード例 #26
0
ファイル: frontend.py プロジェクト: protos37/qual
def mypage():
    form = MypageForm(request.form)
    if request.method == 'GET':
        form.realname.data = current_user.realname
        form.nickname.data = current_user.nickname
    next = request.args.get('next') or url_for('frontend.index')
    if request.method == 'POST' and form.validate():
        current_user.realname = form.realname.data
        current_user.nickname = form.nickname.data
        current_user.set_password(form.password.data)
        db.session.commit()
        return redirect(next)
    return render_template('mypage.html', form=form, next=next)
コード例 #27
0
ファイル: views.py プロジェクト: carverdo/bible
def profile():
    form = ChangePass()
    if form.validate_on_submit():
        current_user.set_password(form.new_password.data)
        current_user.save()
        return redirect(url_for(
            resolve_confirm_status(current_user)
        ))
    return set_template('panelbuilder.html', form, '.profile',
                        panel_args=dict(
                            patex=current_app.config['PAHDS']['profile'],
                            tadata=current_app.config['TADATA']['profile']
                        ))
コード例 #28
0
def edit_profile():
    form = EditProfileForm(username=current_user.username,\
                           email=current_user.email,\
                           api_key=current_user.api_key)
    if form.validate_on_submit():
        current_user.email = form.email.data
        if len(form.password.data
               ) > 5 and form.password.data == form.password2.data:
            current_user.set_password(form.password.data)

        db.session.commit()
        flash('Your profile has been updated.')
        return redirect(url_for('main.index'))
    return render_template('user/edit_profile.html', form=form)
コード例 #29
0
ファイル: views.py プロジェクト: steffen-mehner/Tests
def password():
    """
    Changing the password is only supported for the current user.
    """

    chpwd_form = ChangePasswordForm()
    if chpwd_form.setpwd.data:
        if chpwd_form.validate():
            current_user.set_password(chpwd_form.password.data)
            db.session.add(current_user)
            db.session.commit()
            flash('Your password has been updated', 'info')
        else:
            flash_errors(chpwd_form)
    chpwd_form.update_data(current_user)

    return render_template("users/password.html", chpwd_form=chpwd_form)
コード例 #30
0
ファイル: web.py プロジェクト: SecureCloud-biz/foauth.org
def password_post():
    form = forms.Password(request.form)
    if form.validate():
        current_user.set_password(form.data['password'])

        # Expire all stored keys, so this can't be used as an attack vector
        for key in current_user.keys:
            key.access_token = ''
            key.refresh_token = ''
            key.secret = ''
            key.service_user_id = ''
            key.expires = datetime.datetime.now()

        models.db.session.add(current_user)
        models.db.session.commit()
        return redirect(url_for('services'))
    else:
        return render_template('password.html', form=form)
コード例 #31
0
def password_post():
    form = forms.Password(request.form)
    if form.validate():
        current_user.set_password(form.data['password'])

        # Expire all stored keys, so this can't be used as an attack vector
        for key in current_user.keys:
            key.access_token = ''
            key.refresh_token = ''
            key.secret = ''
            key.service_user_id = ''
            key.expires = datetime.datetime.now()

        models.db.session.add(current_user)
        models.db.session.commit()
        return redirect(url_for('services'))
    else:
        return render_template('password.html', form=form)
コード例 #32
0
ファイル: profile.py プロジェクト: smlacombe/sageo
def profile():
    form = ProfileForm()

    if form.validate_on_submit():
        language = form.language.data
        password = form.password.data
        current_user.language = language
        # Save password only if it's the same
        if password:
            current_user.set_password(password)
        db_session.commit()
        flash(_('Profile settings saved successfully!'), 'success')
        return redirect('/')
    else:
        form.language.data = current_user.language

    return snapins.render_sidebar_template('users/profile.html',
                                           version='0.1',
                                           form=form)
コード例 #33
0
ファイル: user.py プロジェクト: shaunduncan/breezeminder
def change_password():
    form = PasswordChangeForm(request.form)
    if request.method == 'POST' and form.validate():
        # Check current pasword
        if current_user.hash_password(form.current_password.data) != current_user.password:
            flash('Your current password is incorrect', 'error')
        else:
            current_user.set_password(form.password.data)
            current_user.save()
            flash('Password changed successfully', 'success')
        return redirect(url_for('user.password'))

    context = {
        'title': 'Change Password',
        'description': 'Change your BreezeMinder.com account password',
        'form': form
    }

    return render_template('user/password.html', **context)
コード例 #34
0
ファイル: app.py プロジェクト: tooxie/blatt
def profile_confirmation():
    secret_key = app.config['SECRET_KEY']
    confirmation_form = ProfileConfirmationForm(request.form,
                                                secret_key=secret_key)

    if confirmation_form.validate():
        current_user.name = request.form.get('name')
        current_user.email = request.form.get('email')

        if request.form.get('password'):
            current_user.set_password(request.form.get('password'))

        session.add(current_user)
        session.commit()

        flash(u'Perfil actualizado con éxito')

        return redirect('profile')

    return render_template('profile_confirmation.html', form=confirmation_form)
コード例 #35
0
def profile():
    form = ProfileForm(request.form)
    if request.method == "GET":  #populate registration form with the existing profile
        form.username.data = current_user.username
        form.email.data = current_user.email
        form.registrationkey.data = "DS106TestKey"
        form.atomfeed.data = current_user.atomfeed
        form.password.data = current_user.password

    if form.validate_on_submit():
        current_user.email = form.email.data
        current_user.atomfeed = form.atomfeed.data
        current_user.set_password(form.password.data)
        db.session.commit()
        flash("Profile modified", 'success')
        return redirect(url_for('public.home'))
    else:
        flash_errors(form)

    return render_template("users/profile.html", user=current_user, form=form)
コード例 #36
0
ファイル: views.py プロジェクト: matty-plumski/bloggregator
def profile():
    form = ProfileForm(request.form)
    if request.method == "GET": #populate registration form with the existing profile
        form.username.data = current_user.username
        form.email.data = current_user.email
        form.registrationkey.data = "DS106TestKey"
        form.atomfeed.data = current_user.atomfeed
        form.password.data = current_user.password

    if form.validate_on_submit():
        current_user.email = form.email.data
        current_user.atomfeed = form.atomfeed.data
        current_user.set_password(form.password.data)
        db.session.commit()
        flash("Profile modified", 'success')
        return redirect(url_for('public.home'))
    else:
        flash_errors(form)
        
    return render_template("users/profile.html",user=current_user, form=form)
コード例 #37
0
ファイル: frontend.py プロジェクト: nederhrj/nyan
def ajax_change_password():
    if not current_user.is_authenticated():
        abort(403)

    old_password = request.form['old_password']
    new_password = request.form['new_password']
    new_password_repeat = request.form['new_password_repeat']

    #check old password
    m = hashlib.sha256()
    m.update(old_password.encode("UTF-8"))
    m.update(SALT.encode("UTF-8"))

    #old password is wrong
    if m.hexdigest() != current_user.mongodb_user['password']:
        abort(403)

    if new_password != new_password_repeat:
        abort(403)

    if new_password == "":
        abort(400)

    #change password
    m = hashlib.sha256()
    m.update(new_password.encode("UTF-8"))
    m.update(SALT.encode("UTF-8"))

    try:
        current_user.set_password(new_password=m.hexdigest())
    except OperationError as e:
        app.logger.error("Could not save password to database")
        abort(500)
    except Exception as inst:
        app.logger.error("Could not change password %s: %s" % (type(inst), type))
        abort(500)

    return ""
コード例 #38
0
ファイル: views.py プロジェクト: femtobit/dudel
def user_settings():
    if current_user.source == "manual":
        form = SettingsFormPassword(obj=current_user)
    elif current_user.source == "ldap":
        form = SettingsFormLdap(obj=current_user)
    else:
        abort(404)

    if form.validate_on_submit():
        current_user.preferred_language = form.preferred_language.data
        current_user.autowatch = form.autowatch.data
        current_user.allow_invitation_mails = form.allow_invitation_mails.data

        if current_user.source == "manual":
            form.populate_obj(current_user)
            if form.password1.data:
                current_user.set_password(form.password1.data)

        db.session.commit()
        flash(gettext("Your user settings were updated."), "success")
        return redirect(url_for('user_settings'))

    return render_template("user/settings.html", form=form)
コード例 #39
0
ファイル: views.py プロジェクト: Akasch/dudel
def user_settings():
    if current_user.source == "manual":
        form = SettingsFormPassword(obj=current_user)
    elif current_user.source == "ldap":
        form = SettingsFormLdap(obj=current_user)
    else:
        abort(404)

    if form.validate_on_submit():
        current_user.preferred_language = form.preferred_language.data
        current_user.autowatch = form.autowatch.data
        current_user.allow_invitation_mails = form.allow_invitation_mails.data

        if current_user.source == "manual":
            form.populate_obj(current_user)
            if form.password1.data:
                current_user.set_password(form.password1.data)

        db.session.commit()
        flash(gettext("Your user settings were updated."), "success")
        return redirect(url_for('user_settings'))

    return render_template("user/settings.jade", form=form)
コード例 #40
0
def account():
    if request.method == "GET":
        form = AccountForm(obj=current_user)
    else:
        form = AccountForm(request.form)
    try:
        subscribed = Subscription.objects.get(user=current_user.pk)
    except Subscription.DoesNotExist:
        subscribed = None

    if not request.method == 'POST' or not form.validate():
        context = {'form': form, 'subscribed': subscribed}
        return render_template('account.html', **context)

    if form.username.data: current_user.username = form.username.data
    if form.email.data: current_user.email = form.email.data
    if form.phone.data: current_user.phone = form.phone.data
    if form.address.data: current_user.address = form.address.data
    if form.subscribe.data: current_user.subscribe = form.subscribe.data
    if form.password.data: current_user.set_password(form.password.data)
    try:
        current_user.save()
    except Exception, e:
        print str(e)
コード例 #41
0
ファイル: views.py プロジェクト: toastwaffle/nhtg15
def update_details():
    valid = True
    flashes = []

    if (
        flask.request.form['email'] != current_user.email and
        models.User.get_by_email(flask.request.form['email']) is not None
    ):
        flashes.append(u'That email address is already in use. ')
        valid = False

    if (
        'oldpassword' in flask.request.form and
        flask.request.form['oldpassword'] != ''
    ):
        if not current_user.check_password(flask.request.form['oldpassword']):
            flashes.append(u'Current password is incorrect')
            valid = False

        if (
            'password' not in flask.request.form or
            'confirm' not in flask.request.form or
            flask.request.form['password'] == '' or
            flask.request.form['password'] != flask.request.form['confirm']
        ):
            flashes.append(u'New passwords do not match')
            valid = False

        if len(flask.request.form['password']) < 8:
            flashes.append(u'Password must be at least 8 characters long')
            valid = False

    if (
        'firstname' not in flask.request.form or
        flask.request.form['firstname'] == ''
    ):
        flashes.append(u'First Name cannot be blank')
        valid = False

    if (
        'surname' not in flask.request.form or
        flask.request.form['surname'] == ''
    ):
        flashes.append(u'Surname cannot be blank')
        valid = False

    if (
        'email' not in flask.request.form or
        flask.request.form['email'] == ''
    ):
        flashes.append(u'Email cannot be blank')
        valid = False

    if (
        'phone' not in flask.request.form or
        flask.request.form['phone'] == ''
    ):
        flashes.append(u'Phone cannot be blank')
        valid = False

    if (
        'postcode' not in flask.request.form or
        flask.request.form['postcode'] == ''
    ):
        flashes.append(u'Postcode cannot be blank')
        valid = False

    location = models.Location.get_by_postcode(flask.request.form['postcode'])

    if not location:
        flashes.append(u'Postcode not recognised')
        valid = False

    if not valid:
        flash(
            (
                u'There were errors in your provided details. Please fix '
                u'these and try again'
            ),
            'error'
        )
        for msg in flashes:
            flash(msg, 'warning')
    else:
        current_user.firstname = flask.request.form['firstname']
        current_user.surname = flask.request.form['surname']
        current_user.location_id = location.id

        if flask.request.form['email'] != current_user.email:
            current_user.email = flask.request.form['email']
            current_user.email_verified = False
            current_user.email_verification_key = str(random.randint(100000, 999999))
            current_user.send_email_verification()

        if flask.request.form['phone'] != current_user.phone:
            current_user.phone = flask.request.form['phone']
            current_user.sms_verified = False
            current_user.sms_verification_key = str(random.randint(100000, 999999))
            current_user.send_sms_verification()

        if (
            'password' in flask.request.form and
            flask.request.form['password'] != ""
        ):
            current_user.set_password(flask.request.form['password'])

        database.DB.session.commit()

        flask.flash(u'Your details have been updated', 'success')

        return flask.redirect(flask.url_for('.index'))
コード例 #42
0
ファイル: views.py プロジェクト: heyLinsir/railgun
def profile_edit():
    """The form page for the user to edit their profile.

    For the accounts from third-party authentication providers, some fields
    of the form may be locked and cannot be modified.  This feature isn't
    implemented here, but in :mod:`railgun.website.userauth`.

    You may refer to :func:`railgun.website.userauth.AuthProvider.init_form`
    for more details.

    :route: /profile/edit/
    :method: GET, POST
    :template: profile_edit.html
    :form: :class:`railgun.website.forms.ProfileForm`
    """
    # Profile edit should use typeahead.js
    g.scripts.deps('typeahead.js')

    # Create the profile form.
    # Note that some fields cannot be edited in certain auth providers,
    # which should be stripped from from schema.
    form = ProfileForm(obj=current_user.dbo)
    if current_user.provider:
        auth_providers.init_form(current_user.provider, form)

    if form.validate_on_submit():
        # Set password if passwd field exists
        if 'password' in form:
            pwd = form.password.data
            if pwd:
                current_user.set_password(pwd)
            del form['password']
            del form['confirm']
        else:
            pwd = None
        # Copy values into current_user object
        form.populate_obj(current_user.dbo)
        # Commit to main database and auth provider
        try:
            if current_user.provider:
                auth_providers.push(current_user.dbo, pwd)
            db.session.commit()
            flash(_('Profile saved.'), 'info')
        except Exception:
            app.logger.exception('Cannot update account %s' %
                                 current_user.name)
            flash(_("I'm sorry but we may have met some trouble. Please try "
                    "again."), 'warning')
        return redirect(url_for('profile_edit'))

    # If form has errors, flash message to notify the user
    if form.errors:
        flash(
            _("You've got some errors in the form, please check your input."),
            'warning'
        )

    # Clear password & confirm here is ok.
    if 'password' in form:
        form.password.data = None
        form.confirm.data = None

    mongo_user = app.config['USERS_COLLECTION'].find_one({"_id":current_user.name})
    mongo_user_course = mongo_user['course']
    if len(mongo_user_course) == 0:
        mongo_user_course = _('Empty course')
    return render_template('profile_edit.html', locale_name=str(get_locale()),form=form,course = mongo_user_course)
コード例 #43
0
ファイル: routes.py プロジェクト: sc4599/lebi
def password_edit():
    form = PasswordEditForm()
    if form.validate_on_submit():
        current_user.set_password(form.new_password.data)
        return redirect(url_for('user.index'))
    return render_template('user/password_edit.html', form=form)
コード例 #44
0
ファイル: views.py プロジェクト: lzz12/railgun
def profile_edit():
    """The form page for the user to edit their profile.

    For the accounts from third-party authentication providers, some fields
    of the form may be locked and cannot be modified.  This feature isn't
    implemented here, but in :mod:`railgun.website.userauth`.

    You may refer to :func:`railgun.website.userauth.AuthProvider.init_form`
    for more details.

    :route: /profile/edit/
    :method: GET, POST
    :template: profile_edit.html
    :form: :class:`railgun.website.forms.ProfileForm`
    """
    # Profile edit should use typeahead.js
    g.scripts.deps('typeahead.js')

    # Create the profile form.
    # Note that some fields cannot be edited in certain auth providers,
    # which should be stripped from from schema.
    form = ProfileForm(obj=current_user.dbo)
    if current_user.provider:
        auth_providers.init_form(current_user.provider, form)

    if form.validate_on_submit():
        # Set password if passwd field exists
        if 'password' in form:
            pwd = form.password.data
            if pwd:
                current_user.set_password(pwd)
            del form['password']
            del form['confirm']
        else:
            pwd = None

        # Copy values into current_user object
        form.populate_obj(current_user.dbo)

        # Commit to main database and auth provider
        try:
            if current_user.provider:
                auth_providers.push(current_user.dbo, pwd)
            db.session.commit()
            flash(_('Profile saved.'), 'info')
        except Exception:
            app.logger.exception('Cannot update account %s' %
                                 current_user.name)
            flash(_("I'm sorry but we may have met some trouble. Please try "
                    "again."), 'warning')
        return redirect(url_for('profile_edit'))

    # If form has errors, flash message to notify the user
    if form.errors:
        flash(
            _("You've got some errors in the form, please check your input."),
            'warning'
        )

    # Clear password & confirm here is ok.
    if 'password' in form:
        form.password.data = None
        form.confirm.data = None

    return render_template('profile_edit.html', locale_name=str(get_locale()),
                           form=form)