Example #1
0
def recover(secret_key):
    form = PasswordChangeForm(request.form)
    data = RecoveryData.query.filter_by(secret_key=secret_key).first()
    if data is None:
        flash('Secret key for password recovery was invalid', 'danger')
        return redirect(url_for('home'))

    if not data.is_valid():
        flash('This recovery link has expired.')
        database.session.delete(data)
        database.session.commit()
        return redirect(url_for('home'))

    if request.method == 'POST' and form.validate():
        account = Account.query.filter_by(name=data.name, email=data.email).first()
        if account is None:
            flash('Something went wrong, unknown user', 'danger')
            return redirect(url_for('home'))

        account.password = bcrypt.generate_password_hash(form.data['password'])
        database.session.delete(data)
        database.session.commit()

        flash('Successfully changed your password', 'success')
        return redirect(url_for('login'))

    return render_template('views/recover.html', form=form)
Example #2
0
def changepassword():
    form = PasswordChangeForm()
    if request.method == 'GET':
        return render_template('changepassword.html',
                               form=form,
                               name=current_user.email)
    else:
        if form.validate_on_submit():
            if current_user.validate_password(form.currentpassword.data):
                local_object = db.session.merge(current_user)
                local_object.password = current_user.update_password(
                    form.newpassword.data)
                db.session.add(local_object)
                db.session.commit()
                Mail_Service.send_email(current_user.email, "Password Changed",
                                        current_user, request.remote_addr)
                flash("Password Sucessfully Changed")
            else:
                flash("Incorrect Current Password")
                return render_template('changepassword.html',
                                       form=form,
                                       name=current_user.email)
        else:
            flash("Error with form")
            return render_template('changepassword.html',
                                   form=form,
                                   name=current_user.email)
    return redirect(url_for('account'))
Example #3
0
def passwordChange():
    form = PasswordChangeForm()
    if form.validate_on_submit():
        old_pass = form.old_password.data
        new_pass = form.new_password.data
        conf_pass = form.new_password_confirm.data

        # Password change
        if new_pass == conf_pass and check_password_hash(current_user.password, old_pass):
            user = current_user
            user.password = generate_password_hash(new_pass)
            db.session.add(user)
            db.session.commit()
            flash(gettext('User password successfully changed.'))

        else:
            if new_pass != conf_pass:
                flash(gettext('New password must match confirmation!'))
            elif not check_password_hash(current_user.password, old_pass):
                flash(gettext('Current password is incorrect!'))
            return redirect(url_for('passwordChange'))
        return redirect(url_for('user'))

    return render_template('/settings/passwordchange.html',
                           title=gettext("Password Change"),
                           form=form)
Example #4
0
def profile():
    user = authnz.current_user
    user_info = _(username=user.username,
                  email_addr=user.email_addr,
                  role=user.role)
    
    session = get_session()['messages']
    if request.method == 'POST':
        form = PasswordChangeForm(request, user)
        try:
            if form.is_valid():
                form.save()
                session['pass'].append('Password has been changed successfully.')
                return authnz.logout(success_redirect='/profile')
            else:
                session['fail'].append(form.errors)
        except HTTPResponse:
            raise
        except Exception as ex:
            error_message = 'Password change failed. Error: %s' % str(ex)
            session['fail'].append(error_message)
            logging.error(error_message, exc_info=True)
    
    roles = sorted(
        list(authnz.list_roles()),
        key=lambda x: x[1], reverse=True)
    return {
        'title': 'Profile',
        'user': user_info,
        'roles': roles,
        'readonly': True,
    }
Example #5
0
def user_settings(request, post_change_redirect=None):
    user = request.user

    if post_change_redirect is None:
        post_change_redirect = reverse('apps.user_settings.views.user_settings')

    if request.method == 'POST':
        resp = HttpResponseRedirect(post_change_redirect)

        pw_form = PasswordChangeForm(user, data=request.POST)
        email_form = EmailChangeForm(user=user, data=request.POST)
        subscription_form = SubscriptionForm(user=user, data=request.POST)
        https_form = SecureOnlyForm(request.user, request.COOKIES, http_response=resp, data=request.POST)
        browsing_form = BrowsingSettingsForm(user, data=request.POST)
        connections_form = ConnectionsForm(user, data=request.POST)
        all_forms = [pw_form, email_form, subscription_form, https_form, browsing_form, connections_form]
        views.handle_unsubscribe_post(user, request.REQUEST, request)

        if all(form.is_valid() for form in all_forms):
            for form in all_forms:
                form.save()

            if pw_form.password_changed():
                request.session['password_updated'] = True
            return resp

    else:
        pw_form = PasswordChangeForm(user)
        email_form = EmailChangeForm(user=user)
        subscription_form = SubscriptionForm(user=user, initial={
            'newsletter': not EmailUnsubscribe.objects.get_or_none(email=user.email),
        })
        https_form = SecureOnlyForm(user, request.COOKIES)
        browsing_form = BrowsingSettingsForm(user)
        connections_form = ConnectionsForm(user)
        all_forms = [pw_form, email_form, subscription_form, https_form, browsing_form, connections_form]

    context = {
        'pw_form': pw_form,
        'email_form': email_form,
        'subscription_form': subscription_form,
        'https_form': https_form,
        'browsing_form': browsing_form,
        'all_forms': all_forms,
        'connections_form': connections_form,
        'is_staff': request.user.is_staff,
        'email_confirmation': EmailConfirmation.objects.get_or_none(user=user),
        'unsubscribed_settings': views.get_unsubscriptions(user),
    }

    def handle_updated_field(name):
        if request.session.get(name, False):
            context[name] = True
            del request.session[name]

    map(handle_updated_field, ['email_updated', 'password_updated'])

    return render_to_response('user/settings.django.html', context,
                              context_instance=RequestContext(request))
Example #6
0
 def put(self):
     data = ImmutableMultiDict(request.json)
     change_password_form = PasswordChangeForm(data, csrf_enabled=False)
     if change_password_form.validate():
         obj = User.query.filter(User.username == current_identity.username).first()
         change_password_form.save(obj)
         return jsonify({"status": "success", "message": "Password Changed"})
     return change_password_form.errors
Example #7
0
 def test_pw_length(self):
     user = create_user()
     for pw, success in [('a', False,), ('a' * User.MINIMUM_PASSWORD_LENGTH, True,)]:
         form = PasswordChangeForm(user=user, data={
             'old_password': PASSWORD,
             'new_password1': pw,
             'new_password2': pw,
         })
         self.assertEqual(form.is_valid(), success)
Example #8
0
def update_password(request):
    if request.method == 'POST':
        form = PasswordChangeForm(request.POST)
        if form.is_valid():
            request.user.set_password(form.cleaned_data['password1'])
            request.user.save()
            return render(request, 'registration/update_password.html', {'success': True})
    else:
        form = PasswordChangeForm()
    return render(request, 'registration/update_password.html', {'form': form})
Example #9
0
def update_password(request):
    if request.method == 'POST':
        form = PasswordChangeForm(request.POST)
        if form.is_valid():
            request.user.set_password(form.cleaned_data['password1'])
            request.user.save()
            return render(request, 'registration/update_password.html', {'success': True})
    else:
        form = PasswordChangeForm()
    return render(request, 'registration/update_password.html', {'form': form})
Example #10
0
def edit(request):
    """
    Change password only, for now...
    """
    if request.POST:
        form = PasswordChangeForm(request.user, request.POST)
        if form.is_valid():
            instance = form.save()
            return HttpResponse('')
    else:
        form = PasswordChangeForm(user=request.user)
    return render_to_response('users/change_password.html', {'form': form}, context_instance=RequestContext(request))
Example #11
0
def password_change(request):
    message = ''
    saved = False
    form = PasswordChangeForm()

    # is the user logged in?
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/nest/login/')
    if request.user.is_staff:
        return HttpResponseRedirect('/admin/')

    # change password
    if request.method == 'POST':
        pcform = PasswordChangeForm(data=request.POST)

        if pcform.is_valid():
            # still have to check if old password matches
            u = request.user
            oldpass = request.POST.get('oldpass')
            newpass = request.POST.get('newpass1')

            if u.check_password(oldpass):
                # passwords match so it's safe to change the password
                u.set_password(newpass)
                u.save()

                # for some reason, the user gets logged out so we have to log them in again
                login(request,
                      authenticate(username=u.username, password=newpass))

                # create a message and redirect to the dashboard
                messages.add_message(
                    request, messages.SUCCESS,
                    "Your password has been changed successfully")
                return HttpResponseRedirect('/nest/')

            else:
                form = pcform
                message = '<span style="color:firebrick">Old password is incorrect. Please try again</span>'

        else:
            form = pcform
            message = '<span style="color:firebrick">Please correct the errors below</span>'

    context = {
        'title': 'Change my password' + SITE_SUF,
        'navlight': 3,
        'request': request,
        'message': message,
        'form': form,
        'saved': saved,
    }
    return render(request, 'nest/passwordchange.html', context)
Example #12
0
def change_password(request):
    if request.POST:
        form = PasswordChangeForm(request.POST)
        if form.is_valid():
            mail_user = form.cleaned_data["user"]
            mail_user.change_password(form.cleaned_data["new_password"])
            return render_to_response(
                "mailauth/password_change.html",
                {"message": "Password changed successfully"},
                context_instance=RequestContext(request),
            )
    else:
        form = PasswordChangeForm()
    return render_to_response("mailauth/password_change.html", {"form": form}, context_instance=RequestContext(request))
Example #13
0
def changePassword(request):
    form = PasswordChangeForm()
    if 'ok' in request.POST:
        form = PasswordChangeForm(request.POST)
        if form.is_valid():
            u = User.objects.get(username=request.user)
            password1 = request.POST.get('confirm_password', '')
            u.set_password(password1)
            u.save()
            return HttpResponse(status=201)

    return render_to_response("establishment/accounts/change_password.html",
                              {'form': form},
                              context_instance=RequestContext(request))
Example #14
0
def settings():
    pw_form = PasswordChangeForm()
    set_form = SettingsForm()
    if 'pw_change' in request.form and pw_form.validate_on_submit():
        try:
            g.user.set_password(pw_form.new_password.data)
            db.session.commit()
            flash(u'Passwort wurde geändert.')
        except:
            flash(u'Passwort konnte nicht geändert werden.')
    if 'settings_change' in request.form and set_form.validate_on_submit():
        g.user.name = set_form.name.data
        db.session.commit()
        flash(u'Einstellungen wurde geändert.')
    return render_template('user/settings.html', pw_form=pw_form, set_form=set_form)
def password_change(request, template_name='registration/password_change_form.html',
                    post_change_redirect=None):
    if post_change_redirect is None:
        #post_change_redirect = reverse('django.contrib.auth.views.password_change_done')
        post_change_redirect = reverse('auth.views.password_change_done')
    if request.method == "POST":
        form = PasswordChangeForm(request.user, request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(post_change_redirect)
    else:
        form = PasswordChangeForm(request.user)
    return render_to_response(template_name, {
        'form': form,
    }, context_instance=RequestContext(request))
Example #16
0
def settings_view(request):
    if request.method == 'POST':
        form = PasswordChangeForm(user=request.user, data=request.POST, files=request.FILES)
        #imgform = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            update_session_auth_hash(request, form.user)
            return HttpResponseRedirect(reverse('settings_view'))
        else:
            pass
    else:
        form = PasswordChangeForm(user=request.user)
        #imgform = UploadFileForm()
    context = {'form': form, }
    return render(request, "profile.html", context)
Example #17
0
 def test_pw_length(self):
     user = create_user()
     for pw, success in [(
             'a',
             False,
     ), (
             'a' * User.MINIMUM_PASSWORD_LENGTH,
             True,
     )]:
         form = PasswordChangeForm(user=user,
                                   data={
                                       'old_password': PASSWORD,
                                       'new_password1': pw,
                                       'new_password2': pw,
                                   })
         self.assertEqual(form.is_valid(), success)
Example #18
0
def change_password(request):
    user = request.user
    if request.method == "POST":
        form = PasswordChangeForm(request.POST)
        if form.is_valid():
            password = form.cleaned_data['password']
            user.set_password(password)
            user.save()
            logger.info("Changed password for user %s" % user.username)
            messages.info(request, "Password was changed!")
    else:
        form = PasswordChangeForm()

    data = {'form': form}
    return render_to_response('people/change-password.html', data,
                              RequestContext(request))
def edit_user_password(user_id_number):
    # This form allows the administrator to change a user's password.
    error = None

    # Grabs user information from database based on user_id_number and assigns it to user
    user = User.query.get(user_id_number)
    form = PasswordChangeForm()

    if form.validate_on_submit() and request.method == 'POST':

        # Calls method to allow password to be changed based on form input.
        user.set_password(form.password.data)
        db.session.add(user)
        db.session.commit()
        flash("Password has been updated.")

    return render_template('edit_user_password.html', form=form, user=user)
Example #20
0
def changepassword(secretstring):
    form = PasswordChangeForm()
    if form.validate_on_submit():
        if form.password.data:
          s = URLSafeSerializer('12fe454t')
          uname, uemail = s.loads(secretstring)
          user = Users.query.filter_by(username=uname).first()
          db.session.add(user)
          user.pwdhash = bcrypt.generate_password_hash(form.password.data)
          db.session.commit()
          flash('succsessful password reset')
          return redirect(url_for('login'))
        else:
            flash('Try again')
            return redirect(url_for('resetpassword'))

    return render_template('general/change_password.html', form=form)
Example #21
0
def password_change(request):

    if request.method == "POST":
        form = PasswordChangeForm(request.POST)

        if form.is_valid():
            cd = form.cleaned_data
            user = authenticate(username=request.user.username,
                                password=cd['current_password'])

            if not user:
                form.errors['__all__'] = form.error_class(
                    ['Current password incorrect'])

            else:
                user.set_password(cd['password1'])
                user.save()
                update_session_auth_hash(request, user)

                # Success !
                message = "You have successfully changed your password"
                url = reverse('profile')
                return success(request, url, message)

    else:
        form = PasswordChangeForm()

    return render(
        request, 'password_change_form.html', {
            'form': form,
            'form_title': 'Change Password',
            'action': reverse('password_change')
        })
Example #22
0
def change_password(secretstring):
    form = PasswordChangeForm()
    if form.validate_on_submit():

        if form.password.data:
            s = URLSafeSerializer("serliaizer_code")
            uname, uemail = s.loads(secretstring)
            user = Users.query.filter_by(username=uname).first()
            db.session.add(user)
            user.pwdhash = bcrypt.generate_password_hash(form.password.data)
            db.session.commit()
            flash(u"succsessful password reset")
            return redirect(url_for("login"))
        else:
            flash("Try again!")
            return redirect(url_for("reset_password"))

    return render_template("change_password.html", form=form)
Example #23
0
def change_password(request):
    user = request.user
    if request.method == "POST":
        form = PasswordChangeForm(request.POST)
        if form.is_valid():
            password = form.cleaned_data['password']
            user.set_password(password)
            user.save()
            logger.info("Changed password for user %s" % user.username)
            messages.info(request, "Password was changed!")
    else:
        form = PasswordChangeForm()
    
    data = {
        'form': form
    }
    return render_to_response('people/change-password.html', data,
        RequestContext(request))
Example #24
0
def change_password(secretstring):
    form = PasswordChangeForm()
    if form.validate_on_submit():

        if form.password.data:
            s = URLSafeSerializer('serliaizer_code')
            uname, uemail = s.loads(secretstring)
            user = Users.query.filter_by(username=uname).first()
            db.session.add(user)
            user.pwdhash = bcrypt.generate_password_hash(form.password.data)
            db.session.commit()
            flash(u'succsessful password reset')
            return redirect(url_for('login'))
        else:
            flash('Try again!')
            return redirect(url_for('reset_password'))

    return render_template('change_password.html', form=form)
Example #25
0
def changepasswd():
    session_id = request.cookies.get(SESSION_ID)
    if session_id is None:
        return redirect(url_for('logout'))
    if not session_db.exists(session_id):
        return redirect(url_for('logout'))
    form = PasswordChangeForm()
    hidden = request.cookies.get('login')
    if hidden is None:
        return render_template('problem.html')
    form.hidden = hidden
    if form.validate_on_submit():
        ssid = request.cookies.get(SESSION_ID)
        user = session_db.get(ssid)
        user_data = dbc.getUserByLogin(user)
        user_id = user_data[0]
        dbc.updatePassword(user_id, hash_password(form.newpassword.data))
        return render_template('changegood.html')
    return render_template('changepasswd.html', form=form)
Example #26
0
def password_change():
    form = PasswordChangeForm()

    if form.validate_on_submit():
        user_id = current_user.get_id()
        user = User.query.get(user_id)
        if user and not bcrypt.check_password_hash(user.Password,
                                                   form.old_password.data):
            flash('Old password is incorrect.', 'danger')
        else:
            hashed_password = bcrypt.generate_password_hash(
                form.password.data).decode('utf-8')
            user.Password = hashed_password
            db.session.add(user)
            db.session.commit()
            flash('Your password has been changed.', 'success')

    return render_template('password-change.html',
                           title='Change Password',
                           form=form)
Example #27
0
def change_password(request):
    if request.method == 'POST':
        form = PasswordChangeForm(request.POST)
        password_correct = False
        if form.is_valid():
            current_password = form.cleaned_data['current_password']
            new_pass = form.cleaned_data['new_password1']

            password_correct = request.user.check_password(current_password)
            if password_correct:
                request.user.set_password(new_pass)
                request.user.save()
                json = {'location': '.'}
                return HttpResponse(simplejson.dumps(json),
                    mimetype="application/json")

        if not password_correct:
            form._errors['current_password'] = ErrorList()
            form._errors['current_password'].append(_("Your password is incorrect"))
    else:
        raise Http404
    return render(request, 'password_change_modal.html', {'form': form})
Example #28
0
 def test_pw_change(self):
     user = create_user()
     pw = 'new_pass1'
     form = PasswordChangeForm(user=user,
                               data={
                                   'old_password': PASSWORD,
                                   'new_password1': pw,
                                   'new_password2': pw,
                               })
     form.is_valid()
     form.save()
     self.assertTrue(form.password_changed())
def password_reset():
    from datetime import datetime
    form = PasswordChangeForm()

    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()

        if user:
            reset_timer = user.reset_timer
            current_time = datetime.now()
            reset_check = (current_time.day + 100) - reset_timer
            print "*" * 30
            print "Reset Check: ", reset_check
            print "*" * 30
            if (reset_check <= 3):

                user.set_password(form.password.data)
                user.reset_key = ""
                user.reset_timer = ""
                db.session.commit()

            return redirect(url_for('login'))

    return render_template('password_reset.html', form=form)
Example #30
0
 def test_pw_change(self):
     user = create_user()
     pw = 'new_pass1'
     form = PasswordChangeForm(user=user, data={
         'old_password': PASSWORD,
         'new_password1': pw,
         'new_password2': pw,
     })
     form.is_valid()
     form.save()
     self.assertTrue(form.password_changed())
Example #31
0
def password_change(request,
                    template_name='registration/password_change_form.html',
                    post_change_redirect=None):
    if post_change_redirect is None:
        #post_change_redirect = reverse('django.contrib.auth.views.password_change_done')
        post_change_redirect = reverse('auth.views.password_change_done')
    if request.method == "POST":
        form = PasswordChangeForm(request.user, request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(post_change_redirect)
    else:
        form = PasswordChangeForm(request.user)
    return render_to_response(template_name, {
        'form': form,
    },
                              context_instance=RequestContext(request))
Example #32
0
def settings_view(request):
    if request.method == 'POST':
        form = PasswordChangeForm(user=request.user,
                                  data=request.POST,
                                  files=request.FILES)
        #imgform = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            update_session_auth_hash(request, form.user)
            return HttpResponseRedirect(reverse('settings_view'))
        else:
            pass
    else:
        form = PasswordChangeForm(user=request.user)
        #imgform = UploadFileForm()
    context = {
        'form': form,
    }
    return render(request, "profile.html", context)
Example #33
0
def changePassword(request):
    # This needs work
    messages = [] 
    if request.method == 'POST':
        print request.POST
        passwordChangeForm = PasswordChangeForm(request.POST)
        if passwordChangeForm.is_valid():
            if hashers.check_password(passwordChangeForm.cleaned_data['oldpassword'], request.user.password):

                if passwordChangeForm.cleaned_data['newpassword1'] == passwordChangeForm.cleaned_data['newpassword2']:
                    request.user.set_password(passwordChangeForm.cleaned_data['newpassword1'])
                    request.user.save()
                    print 'password change request successful'
                    return render(request, 'changePassword.html', {'passwordChangeForm':passwordChangeForm,\
                                                               'messages':messages})
                else: 
                    messages.append('passwords do not match')  
                    passwordChangeForm = PasswordChangeForm()
                    return render(request, 'changePassword.html', {'passwordChangeForm':passwordChangeForm,\
                                                   'messages':messages})
            else:
                messages.append('Bad password supplied')
                passwordChangeForm = PasswordChangeForm()
                return render(request, 'changePassword.html', {'passwordChangeForm':passwordChangeForm,\
                                                               'messages':messages}) 
        
        else:
            messages.append('form is not valid')
            passwordChangeForm = PasswordChangeForm()
            return render(request, 'changePassword.html', {'passwordChangeForm':passwordChangeForm,\
                                                               'messages':messages})

    else:
        passwordChangeForm = PasswordChangeForm()   
        return render(request, 'changePassword.html', {'passwordChangeForm':passwordChangeForm,\
                                                       'messages':messages})
Example #34
0
def account():
    # Get basic database and forms ready to return
    bsdb = get_bsdb()
    acct = AccountSettings(session['user_num'])
    account_settings_change_form = AccountSettingsChangeForm()
    password_change_form = PasswordChangeForm()
    account_settings = bsdb.get_account_settings(session["user_num"])
    show_account_modal = False
    show_password_modal = False
    # Check against requests to change account settings
    if (req.method == 'POST' and
            account_settings_change_form.submit_account_change.data):
        show_account_modal = True
        app.logger.info(f"request received to change user settings for " +
                        f"user {session['user_num']}")
        # Check to make sure form was valid, return form if it was not
        if not account_settings_change_form.validate_on_submit():
            app.logger.warning(f"Settings change form failed validation")
            flash("Your information wouldn't work.  Try again?", "warning")
            return render_template(
                'user/user-home.html',
                account_settings=account_settings,
                account_settings_change_form=account_settings_change_form,
                password_change_form=password_change_form,
                show_account_modal=show_account_modal,
                show_password_modal=show_password_modal
            )
        # Check that the username isn't changing or is available
        if acct.is_username_valid(session['user_num'],
                                  account_settings_change_form.username.data):
            app.logger.info("username is valid")
            try:
                acct.set_account_information(
                    session['user_num'], account_settings_change_form)
                flash("Account information updated.", "success")
                app.logger.info("returning new account info:")
                account_settings = bsdb.get_account_settings(
                    session["user_num"])
                show_account_modal = False
                account_settings = bsdb.get_account_settings(
                    session["user_num"])
            except Exception:
                flash("Error updating your information.  Try again?",
                      "warning")
        else:
            flash("Username is already taken", "warning")

    # Check against request to change password
    elif req.method == 'POST' and password_change_form.submit.data:
        show_password_modal = True
        app.logger.info(f"request received to change password for " +
                        f"user {session['user_num']}")
        if not password_change_form.validate_on_submit():
            app.logger.warning(f"Password change form failed verification")
            flash("Your infromation wouldn't work.  Try again?", "warning")
            return render_template(
                'user/user-home.html',
                account_settings=account_settings,
                account_settings_change_form=account_settings_change_form,
                password_change_form=password_change_form,
                show_account_modal=show_account_modal,
                show_password_modal=show_password_modal
            )
        try:
            correct_password = acct.is_password_correct(session["user_num"],
                                                        password_change_form)
            if not correct_password:
                flash("Original password was not correct.  Please try again.",
                      "warning")
            else:
                app.logger.info("Original password was entered correctly.")
                try:
                    acct.set_password(session["user_num"],
                                      password_change_form)
                    app.logger.info("New Password set")
                    flash("New Password Sucessfully Set.", "success")
                    show_password_modal = False
                except Exception:
                    app.logger.error("Error setting new password")
                    flash("Error setting new password.  Try again?", "warning")

        except Exception:
            flash("Error determining if the original password is correct.  Try again?", "warning")
            app.logger.error("Error checking original password.")

    # We got here either by being GET or succeeding making changes.
    # Refill account_setting and account_settings_change_form
    account_settings_change_form = acct.fill_account_settings_change_form()
    account_settings = bsdb.get_account_settings(session["user_num"])
    return render_template(
        'user/user-home.html',
        account_settings=account_settings,
        account_settings_change_form=account_settings_change_form,
        password_change_form=password_change_form,
        show_account_modal=show_account_modal,
        show_password_modal=show_password_modal
    )
Example #35
0
def editview(request, action):
    if request.user.is_authenticated():
        request_data = None
        context = {}

        if request.method == 'POST':
            request_data = request.POST

        if action == 'password':
            form = PasswordChangeForm(user=request.user, data=request_data)
            context = {'form': form, 'action': 'Change password', 'edition': True}
        elif action == 'settings':
            tz = 'UTC'
            if hasattr(request.user, 'sciriususer'):
                tz = request.user.sciriususer.timezone
            initial = {'timezone': tz}

            if request.user.is_superuser:
                form = UserSettingsForm(request_data, instance=request.user, initial=initial)
            else:
                form = NormalUserSettingsForm(request_data, instance=request.user, initial=initial)

            context = {'form': form, 'action': 'Edit settings for ' + request.user.username, 'edition': True}
        elif action == 'token':
            initial = {}
            token = Token.objects.filter(user=request.user)
            if len(token):
                initial['token'] = token[0]
            form = TokenForm(request_data, initial=initial)
            context = {'form': form, 'action': 'User token', 'edition': True}
        else:
            context = {'action': 'User settings', 'edition': False}

        if request.method == 'POST':
            orig_superuser = request.user.is_superuser
            orig_staff = request.user.is_staff
            if form.is_valid():
                if action == 'token':
                    current_tokens = Token.objects.filter(user=request.user)
                    for token in current_tokens:
                        token.delete()
                    Token.objects.create(user=request.user)

                    UserAction.create(
                        action_type='edit_user_token',
                        comment=form.cleaned_data['comment'],
                        user=request.user,
                        other_user=request.user
                    )
                    return redirect('accounts_edit', action='token')

                context['edition'] = False
                context['action'] = 'User settings'

                ruser = form.save(commit = False)
                if not orig_superuser:
                    ruser.is_superuser = False
                    ruser.is_staff = orig_staff
                ruser.save()
                if action == 'password':
                    update_session_auth_hash(request, ruser)

                    UserAction.create(
                        action_type='edit_user_password',
                        comment=form.cleaned_data['comment'],
                        user=request.user,
                        other_user=request.user
                    )
                if action == 'settings':
                    try:
                        sciriususer = ruser.sciriususer
                        sciriususer.timezone = form.cleaned_data['timezone']
                    except:
                        sciriususer = SciriusUser.objects.create(user = ruser, timezone = form.cleaned_data['timezone'])

                    UserAction.create(
                        action_type='edit_user',
                        comment=form.cleaned_data['comment'],
                        user=request.user,
                        other_user=request.user
                    )
                    sciriususer.save()
        return scirius_render(request, 'accounts/edit.html', context)