示例#1
0
def change_password():
    form = ChangePassword()
    if form.validate_on_submit():
        exist_stmt_auth = "SELECT EXISTS(SELECT * FROM author WHERE Email=%s)"
        cursor = db.connection.cursor()
        cursor.execute(exist_stmt_auth, [form.email.data])
        exists = cursor.fetchall()
        exists = int(exists[0][0])

        if not exists:
            return render_template("change_password.html",
                                   form=form,
                                   message="Email not found!")
        else:
            print("****************")
            print("EMAIL =", form.email.data, "PASSWORD ="******"****************")
            reset_pswd = "UPDATE author SET Password=%s WHERE Email=%s"
            cursor = db.connection.cursor()
            cursor.execute(reset_pswd, [form.password.data, form.email.data])
            db.connection.commit()
            _ = cursor.fetchall()
            return render_template("change_password.html",
                                   form=form,
                                   message="Password changed successfully!")
    return render_template("change_password.html", form=form)
示例#2
0
文件: app.py 项目: usuario16/DLine
def change_password(id):
    if user_in_session():
        error = None
        user = User.query.filter_by(id=int(id)).first()
        form = ChangePassword()

        if form.validate_on_submit() and request.method == 'POST':
            password_user = sha256((form.password_user.data).encode())

            if validate_password(user.username, password_user.hexdigest()):
                new_password = sha256((form.new_password.data).encode())
                confirm_new_password = sha256((form.confirm_new_password.data).encode())

                if new_password.hexdigest() == confirm_new_password.hexdigest():
                    user.password = new_password.hexdigest()
                    db.session.add(user)
                    db.session.commit()

                    flash('Your password has been changed successfuly!')

                    return redirect(url_for('profile'))

                else:
                    error = 'New passwords no match!'
            else:
                error = 'Incorrect actual password'

        return render_template('auth/session-started/change_password.html', form=form, error=error)

    else:
        abort(404)
def change_password():
    form = ChangePassword()
    if form.validate_on_submit():
        data_obj = User.query.filter_by(id=current_user.id).first()
        data_obj.password = form.password.data
        db.session.merge(data_obj)
        logout_user()
        return redirect(url_for("auth.login_page"))
    return render_template("user_control/change_password.html", form=form)
示例#4
0
def user(user_id):
	user = User.query.filter_by(id = user_id).first()
	kicks = Kicks.query.all()
	form = ChangePassword()
	account = EditAccountInfo(obj=user)
	tix_per_kick = []
	tix_count = []
	all_tix = Tickets.query.filter_by(user_id = user_id).all()
	for t in all_tix:
		print t.kicks_id, t.num_tickets
		kick = Kicks.query.filter_by(id = t.kicks_id).first()
		print kick.shoe_name
		obj = {'kick': kick, 'num_tickets': t.num_tickets, 'date': t.date}
		tix_count.append(obj)



 	#updates password
	if form.validate_on_submit():
		if check_password_hash(user.password, form.old.data):
			if form.new.data == form.confirm_new.data:
				user.password = generate_password_hash(form.new.data)
				db.session.add(user)
				db.session.commit()
				flash('Password was updated')
			else:
				flash('Make sure the new password matches')
		else:
			flash('Wrong password')
	#edit account info
	if account.validate_on_submit():
		print 'account was updated'
		user.firstname = account.firstname.data 
		user.lastname = account.lastname.data
		user.email = account.email.data
		user.address_street = account.address_street.data
		user.address_city = account.address_city.data
		user.address_state = account.address_state.data
		user.address_zipcode = account.address_zipcode.data
		user.address_country = 'USA'
		#Commits changes
		db.session.add(user)
		db.session.commit()
		flash('Info updated!')
	else:
		print account.errors

	print g.user.id
	print user_id
	if int(g.user.id) == int(user_id):
		return render_template('account.html',
			user = user,
			form = form,
			tix = tix_count,
			edit_form = account)
	else:
		return render_template('unauthorized.html')
示例#5
0
def changePassword():
    form = ChangePassword()
    if form.validate_on_submit():
        user = User.query.filter_by(username=current_user.username).first()
        print(check_password_hash(user.password, form.old.data))
        if check_password_hash(user.password, form.old.data):
            user.password = generate_password_hash(form.new.data,
                                                   method='sha256')
            db.session.add(user)
            db.session.commit()
            flash('Password successfully changed.')
            return redirect(url_for('logout'))
        flash('Invalid password.')
    return render_template('change_password.html', form=form)
示例#6
0
 def changepassword():
     form = ChangePassword()
     user = users.find_one({'username': current_user.get_id()})
     if form.validate_on_submit():
         users.update_one(user, {
             '$set': {
                 'password': generate_password_hash(form.password.data)
             }
         })
         flash('Password Changed', 'info')
         return redirect(url_for('index'))
     return render_template('changepassword.html',
                            title="Change Password",
                            form=form)
示例#7
0
def change_password(token):
    """ produces form for changing password"""

    user = User.query.filter(User.reset_token == token).first()
    if user:
        form = ChangePassword()
        if form.validate_on_submit():
            pwd = form.password.data
            user.update_password(pwd)
            user.reset_token = None
            db.session.commit()
            flash("You have successfully changed your password", 'success')
            return redirect('/login')
        return render_template('change_password.html', form=form)
示例#8
0
def change_password(request):
    if request.method=="POST":
        form=ChangePassword(request.POST)
        if form.is_valid():
            register_user=User.objects.get(username=request.user.username)
            register_user.set_password(str(form.cleaned_data['password']))
            register_user.save()
            return HttpResponseRedirect('/foodline/login/')
        else:
            state="please enter a new password"
            return render_to_response('reset.html',locals())
    else:
        form=ChangePassword()
        state="Enter a New Password"
        return render_to_response('reset.html',locals())
示例#9
0
def my_account(request, action=None, conn=None, **kwargs):
    template = "webadmin/myaccount.html"

    experimenter, defaultGroup, otherGroups, isLdapUser, hasAvatar = prepare_experimenter(
        conn)
    try:
        defaultGroupId = defaultGroup.id
    except:
        defaultGroupId = None

    ownedGroups = ownedGroupsInitial(conn)

    password_form = ChangePassword()

    form = None
    if action == "save":
        if request.method != 'POST':
            return HttpResponseRedirect(
                reverse(viewname="wamyaccount", args=["edit"]))
        else:
            email_check = conn.checkEmail(request.REQUEST.get('email'),
                                          experimenter.email)
            form = MyAccountForm(data=request.POST.copy(),
                                 initial={'groups': otherGroups},
                                 email_check=email_check)
            if form.is_valid():
                firstName = form.cleaned_data['first_name']
                middleName = form.cleaned_data['middle_name']
                lastName = form.cleaned_data['last_name']
                email = form.cleaned_data['email']
                institution = form.cleaned_data['institution']
                defaultGroupId = form.cleaned_data['default_group']
                conn.updateMyAccount(experimenter, firstName, lastName, email,
                                     defaultGroupId, middleName, institution)
                return HttpResponseRedirect(reverse("wamyaccount"))

    else:
        form = MyAccountForm(
            initial={
                'omename': experimenter.omeName,
                'first_name': experimenter.firstName,
                'middle_name': experimenter.middleName,
                'last_name': experimenter.lastName,
                'email': experimenter.email,
                'institution': experimenter.institution,
                'default_group': defaultGroupId,
                'groups': otherGroups
            })

    photo_size = conn.getExperimenterPhotoSize()

    context = {
        'form': form,
        'ldapAuth': isLdapUser,
        'experimenter': experimenter,
        'ownedGroups': ownedGroups,
        'password_form': password_form
    }
    context['template'] = template
    return context
示例#10
0
def change_password():
    username = current_user.username
    user = User.query.filter_by(username=username).first()

    form = ChangePassword()
    if form.validate_on_submit():
        old_password = form.old_password.data
        new_password = form.new_password.data
        confirm_password = form.confirm_password.data

        if (user and (check_password_hash(user.password, old_password) and
                      (new_password == confirm_password))):

            update_password(user_id=user.id,
                            password=generate_password_hash(new_password))

            return redirect(f"/user/{username}")

    return render_template("change_password.html", form=form)
示例#11
0
def manage_password(request, account_id, conn=None, **kwargs):
    template = "omero_signup/password.html"

    error = None
    if request.method == 'POST':
        password_form = ChangePassword(data=request.POST.copy())
        if not password_form.is_valid():
            error = password_form.errors
        else:
            old_password = password_form.cleaned_data['old_password']
            password = password_form.cleaned_data['password']
            if conn.isAdmin():
                account = get_object_or_404(models.Account, pk=account_id)
                account.password = password
                account.save()

    context = {'error': error, 'password_form': password_form, 'account_id': account_id}
    context['template'] = template
    return context
示例#12
0
def change_password(request, username=None):
    form = ChangePassword(request.POST or None)
    message = None
    if request.method == 'POST':
        if form.is_valid():
            if authenticate(username=request.user.username,
                            password=form.cleaned_data['current_password']):
                request.user.set_password(form.cleaned_data['new_password'])
                request.user.save()
                #https://docs.djangoproject.com/en/1.7/topics/auth/default/#session-invalidation-on-password-change
                update_session_auth_hash(request, request.user)
                message = "Password actualizada"
            else:
                message = "No es la password actual"
        else:
            message = form.errors.as_data().itervalues().next()[0].message

    context = {'form': form, 'message': message}
    return render(request, 'clients/settings_password.html', context)
def reset_password(email):
    try:
        user = mongo.db.users

        form = ChangePassword()
        if form.validate_on_submit():
            new_password = request.form['change_password']
            hashed_password = bcrypt.generate_password_hash(
                new_password).decode('utf-8')
            findquery = {"email": email}
            newquery = {"$set": {'password': hashed_password}}
            status = user.update_one(findquery, newquery)
            return "<h1>Successfully Changed</h1>"
        else:
            return render_template('reset_password.html',
                                   form=form,
                                   email=email)

    except Exception:
        return dumps({'status': 'error', 'message': str(Exception)})
示例#14
0
def settings():
    latest_messages = current_user.contacts_latest_messages()

    password_form = ChangePassword()

    wrong_password = False

    if password_form.validate_on_submit():
        if current_user.verify_password(password_form.old_password.data):
            current_user.change_password(password_form.new_password.data)
            db.session.commit()
            flash(u"Nouveau mot de passe enregistré")
            return redirect(url_for('auth.logout'))
        else:
            wrong_password = True

    return render_template('prof/settings.html',
                           user=current_user.serialize(),
                           password_form=password_form,
                           wrong_password=wrong_password,
                           latest_messages=latest_messages)
示例#15
0
def change_pass():
    if 'email' in session:
        return redirect(url_for('home'))
    form = ChangePassword()
    if request.method == 'POST':
        if form.validate() is False:
            return render_template('changepassword.html', form=form)
        else:
            user = db_session.query(User).filter_by(
                email=form.email.data).first()
            if user is not None:
                ps_hash = bcrypt.generate_password_hash(form.password.data)
                user.password = ps_hash
                db_session.commit()
                return redirect(url_for('login'))
            else:
                flash('User not in database.')
                return render_template('changepassword.html', form=form)

    elif request.method == 'GET':
        return render_template('changepassword.html', form=form)
示例#16
0
def change_pwd():
   form = ChangePassword()
   if form.validate_on_submit():
      if form.curpwd.data==base64.b64decode(app.config['PASSWORD']):
         if form.password1.data==form.password2.data:
            s = 'USERNAME = "******"\nPASSWORD = "******"'.format(base64.b64encode(form.username.data), base64.b64encode(form.password1.data))
            with open('auth.py', 'w') as f:
               f.write(s)
            if form.username.data!=base64.b64decode(app.config['USERNAME']):
               flash('New username have been saved.')
               app.config['USERNAME']=base64.b64encode(form.username.data)
            if form.curpwd.data!=form.password1.data:
               flash('Password was changed succesfully.')
               app.config['PASSWORD']=base64.b64encode(form.password1.data)
            logout_user()
         else:
            flash('Introduced a different passwords', 'error')
      else:
         flash('Entered an incorrect current password.', 'error')
      return redirect(url_for('change_pwd'))
   return render_template("password.html",
      title = 'Change password', form = form, username=base64.b64decode(app.config['USERNAME']))
def changepass():
    if (not session.get('logged-in')):
        flash('LOGIN TO CONTINUE', 'danger')
        return redirect(url_for('logout'))

    form=ChangePassword()
    if request.method=='POST':
        if form.is_submitted():
            oldp=form.oldpassword.data
            dict1=dataret(session['email'])
            if pbkdf2_sha256.verify(oldp,dict1['passwordd']):
                cursor=mysql.connection.cursor()
                newpassworda=pbkdf2_sha256.hash(form.password.data)
                cursor.execute(f" UPDATE  userinfo  set passwordd = '{newpassworda}' where email='{session['email']}' ")
                conn.commit()
                flash('Update successfull', 'success')
                return redirect(url_for('userhome'))
            else:
                flash('Enter Correct old password', 'danger')
                return redirect(url_for('changepass'))

    return render_template('newpass.html',form=form,title="Change Password")
示例#18
0
def manage_password(request, eid, conn=None, **kwargs):
    template = "webadmin/password.html"

    error = None
    if request.method == 'POST':
        password_form = ChangePassword(data=request.POST.copy())
        if not password_form.is_valid():
            error = password_form.errors
        else:
            old_password = password_form.cleaned_data['old_password']
            password = password_form.cleaned_data['password']
            # if we're trying to change our own password...
            if conn.getEventContext().userId == int(eid):
                try:
                    conn.changeMyPassword(password, old_password)
                except Exception, x:
                    error = x.message   # E.g. old_password not valid
            elif conn.isAdmin():
                exp = conn.getObject("Experimenter", eid)
                try:
                    conn.changeUserPassword(exp.omeName, password, old_password)
                except Exception, x:
                    error = x.message
示例#19
0
def manage_password(request, eid, conn=None, **kwargs):
    template = "webadmin/password.html"

    error = None
    if request.method == 'POST':
        password_form = ChangePassword(data=request.POST.copy())
        if not password_form.is_valid():
            error = password_form.errors
        else:
            old_password = password_form.cleaned_data['old_password']
            password = password_form.cleaned_data['password']
            # if we're trying to change our own password...
            if conn.getEventContext().userId == int(eid):
                try:
                    conn.changeMyPassword(password, old_password)
                except Exception, x:
                    error = x.message   # E.g. old_password not valid
            elif conn.isAdmin():
                exp = conn.getObject("Experimenter", eid)
                try:
                    conn.changeUserPassword(exp.omeName, password, old_password)
                except Exception, x:
                    error = x.message
示例#20
0
def manage_password(request, eid, **kwargs):
    experimenters = True
    template = "webadmin/password.html"
    
    conn = None
    try:
        conn = kwargs["conn"]
    except:
        logger.error(traceback.format_exc())
    
    info = {'today': _("Today is %(tday)s") % {'tday': datetime.date.today()}, 'experimenters':experimenters}

    eventContext = {'userName':conn.getEventContext().userName, 'isAdmin':conn.getEventContext().isAdmin, 'version': request.session.get('version')}
    
    error = None
    if request.method != 'POST':
        password_form = ChangePassword()
    else:
        password_form = ChangePassword(data=request.POST.copy())            
        if password_form.is_valid():
            old_password = password_form.cleaned_data['old_password']
            password = password_form.cleaned_data['password']
            if conn.isAdmin():
                exp = conn.getExperimenter(eid)
                try:
                    conn.changeUserPassword(exp.omeName, password, old_password)
                except Exception, x:
                    error = x.message
                else:
                    request.session['password'] = password
                    return HttpResponseRedirect(reverse(viewname="wamanageexperimenterid", args=["edit", eid]))
            else:
                try:
                    conn.changeMyPassword(password, old_password) 
                except Exception, x:
                    error = x.message
                else:
示例#21
0
def change_password():

    change_pw_form = ChangePassword()

    if request.method == "POST":
        if not check_password_hash(current_user.password,
                                   change_pw_form.current_password.data):
            flash("Current password does not match. Please try again.")
            return redirect(url_for('change_password'))
        elif not change_pw_form.new_password.data == change_pw_form.confirm_new_password.data:
            flash("Passwords do not match. Please try again.")
            return redirect(url_for('change_password'))
        else:
            flash("Password changed successfully.")
            return redirect(url_for('edit_profile'))
            new_password = change_pw_form.new_password.data
            current_user.password = generate_password_hash(
                new_password, method='pbkdf2:sha256', salt_length=8)
            db.session.commit()

    return render_template("change-password.html",
                           current_user=current_user,
                           form=change_pw_form)
示例#22
0
def manage_experimenter(request, action, eid=None, conn=None, **kwargs):
    template = "webadmin/experimenter_form.html"

    groups = list(conn.getObjects("ExperimenterGroup"))
    groups.sort(key=lambda x: x.getName().lower())

    if action == 'new':
        form = ExperimenterForm(
            initial={
                'with_password': True,
                'active': True,
                'groups': otherGroupsInitialList(groups)
            })
        context = {'form': form}
    elif action == 'create':
        if request.method != 'POST':
            return HttpResponseRedirect(
                reverse(viewname="wamanageexperimenterid", args=["new"]))
        else:
            name_check = conn.checkOmeName(request.REQUEST.get('omename'))
            email_check = conn.checkEmail(request.REQUEST.get('email'))

            initial = {
                'with_password': True,
                'groups': otherGroupsInitialList(groups)
            }
            form = ExperimenterForm(initial=initial,
                                    data=request.REQUEST.copy(),
                                    name_check=name_check,
                                    email_check=email_check)
            if form.is_valid():
                logger.debug("Create experimenter form:" +
                             str(form.cleaned_data))
                omename = form.cleaned_data['omename']
                firstName = form.cleaned_data['first_name']
                middleName = form.cleaned_data['middle_name']
                lastName = form.cleaned_data['last_name']
                email = form.cleaned_data['email']
                institution = form.cleaned_data['institution']
                admin = toBoolean(form.cleaned_data['administrator'])
                active = toBoolean(form.cleaned_data['active'])
                defaultGroup = form.cleaned_data['default_group']
                otherGroups = form.cleaned_data['other_groups']
                password = form.cleaned_data['password']

                # default group
                # if default group was not selected take first from the list.
                if defaultGroup is None:
                    defaultGroup = otherGroups[0]
                for g in groups:
                    if long(defaultGroup) == g.id:
                        dGroup = g
                        break

                listOfOtherGroups = set()
                # rest of groups
                for g in groups:
                    for og in otherGroups:
                        # remove defaultGroup from otherGroups if contains
                        if long(og) == long(dGroup.id):
                            pass
                        elif long(og) == g.id:
                            listOfOtherGroups.add(g)

                conn.createExperimenter(omename, firstName, lastName, email,
                                        admin, active, dGroup,
                                        listOfOtherGroups, password,
                                        middleName, institution)
                return HttpResponseRedirect(reverse("waexperimenters"))
            context = {'form': form}
    elif action == 'edit':
        experimenter, defaultGroup, otherGroups, isLdapUser, hasAvatar = prepare_experimenter(
            conn, eid)
        try:
            defaultGroupId = defaultGroup.id
        except:
            defaultGroupId = None

        initial = {
            'omename': experimenter.omeName,
            'first_name': experimenter.firstName,
            'middle_name': experimenter.middleName,
            'last_name': experimenter.lastName,
            'email': experimenter.email,
            'institution': experimenter.institution,
            'administrator': experimenter.isAdmin(),
            'active': experimenter.isActive(),
            'default_group': defaultGroupId,
            'other_groups': [g.id for g in otherGroups],
            'groups': otherGroupsInitialList(groups)
        }
        experimenter_is_me = (conn.getEventContext().userId == long(eid))
        form = ExperimenterForm(experimenter_is_me=experimenter_is_me,
                                initial=initial)
        password_form = ChangePassword()
        context = {
            'form': form,
            'eid': eid,
            'ldapAuth': isLdapUser,
            'password_form': password_form
        }
    elif action == 'save':
        experimenter, defaultGroup, otherGroups, isLdapUser, hasAvatar = prepare_experimenter(
            conn, eid)
        if request.method != 'POST':
            return HttpResponseRedirect(
                reverse(viewname="wamanageexperimenterid",
                        args=["edit", experimenter.id]))
        else:
            name_check = conn.checkOmeName(request.REQUEST.get('omename'),
                                           experimenter.omeName)
            email_check = conn.checkEmail(request.REQUEST.get('email'),
                                          experimenter.email)
            initial = {
                'active': True,
                'groups': otherGroupsInitialList(groups)
            }

            form = ExperimenterForm(initial=initial,
                                    data=request.POST.copy(),
                                    name_check=name_check,
                                    email_check=email_check)

            if form.is_valid():
                logger.debug("Update experimenter form:" +
                             str(form.cleaned_data))
                omename = form.cleaned_data['omename']
                firstName = form.cleaned_data['first_name']
                middleName = form.cleaned_data['middle_name']
                lastName = form.cleaned_data['last_name']
                email = form.cleaned_data['email']
                institution = form.cleaned_data['institution']
                admin = toBoolean(form.cleaned_data['administrator'])
                active = toBoolean(form.cleaned_data['active'])
                if experimenter.getId() == conn.getUserId():
                    active = True  # don't allow user to disable themselves!
                defaultGroup = form.cleaned_data['default_group']
                otherGroups = form.cleaned_data['other_groups']

                # default group
                # if default group was not selected take first from the list.
                if defaultGroup is None:
                    defaultGroup = otherGroups[0]
                for g in groups:
                    if long(defaultGroup) == g.id:
                        dGroup = g
                        break

                listOfOtherGroups = set()
                # rest of groups
                for g in groups:
                    for og in otherGroups:
                        # remove defaultGroup from otherGroups if contains
                        if long(og) == long(dGroup.id):
                            pass
                        elif long(og) == g.id:
                            listOfOtherGroups.add(g)

                conn.updateExperimenter(experimenter, omename, firstName,
                                        lastName, email, admin, active, dGroup,
                                        listOfOtherGroups, middleName,
                                        institution)
                return HttpResponseRedirect(reverse("waexperimenters"))
            context = {'form': form, 'eid': eid, 'ldapAuth': isLdapUser}
    #elif action == "delete":
    #    conn.deleteExperimenter()
    #    return HttpResponseRedirect(reverse("waexperimenters"))
    else:
        return HttpResponseRedirect(reverse("waexperimenters"))

    context['template'] = template
    return context
示例#23
0
def manage_experimenter(request, action, eid=None, conn=None, **kwargs):
    template = "webadmin/experimenter_form.html"

    groups = list(conn.getObjects("ExperimenterGroup"))
    groups.sort(key=lambda x: x.getName().lower())

    user_privileges = conn.get_privileges_for_form(
        conn.getCurrentAdminPrivileges())
    can_modify_user = '******' in user_privileges

    if action == 'new':
        form = ExperimenterForm(can_modify_user=can_modify_user,
                                user_privileges=user_privileges,
                                initial={
                                    'with_password': True,
                                    'active': True,
                                    'groups': otherGroupsInitialList(groups)
                                })
        admin_groups = [
            conn.getAdminService().getSecurityRoles().systemGroupId
        ]
        context = {
            'form': form,
            'admin_groups': admin_groups,
            'can_modify_user': can_modify_user
        }
    elif action == 'create':
        if request.method != 'POST':
            return HttpResponseRedirect(
                reverse(viewname="wamanageexperimenterid", args=["new"]))
        else:
            name_check = conn.checkOmeName(request.POST.get('omename'))
            email_check = conn.checkEmail(request.POST.get('email'))
            my_groups = getSelectedGroups(conn,
                                          request.POST.getlist('other_groups'))
            initial = {
                'with_password': True,
                'my_groups': my_groups,
                'groups': otherGroupsInitialList(groups)
            }
            # This form may be returned to user if invalid
            # Needs user_privileges & can_modify_user for this
            form = ExperimenterForm(can_modify_user=can_modify_user,
                                    user_privileges=user_privileges,
                                    initial=initial,
                                    data=request.POST.copy(),
                                    name_check=name_check,
                                    email_check=email_check)
            if form.is_valid():
                logger.debug("Create experimenter form:" +
                             str(form.cleaned_data))
                omename = form.cleaned_data['omename']
                firstName = form.cleaned_data['first_name']
                middleName = form.cleaned_data['middle_name']
                lastName = form.cleaned_data['last_name']
                email = form.cleaned_data['email']
                institution = form.cleaned_data['institution']
                role = form.cleaned_data['role']
                admin = role in ('administrator', 'restricted_administrator')
                active = form.cleaned_data['active']
                defaultGroup = form.cleaned_data['default_group']
                otherGroups = form.cleaned_data['other_groups']
                password = form.cleaned_data['password']

                # default group
                # if default group was not selected take first from the list.
                if defaultGroup is None:
                    defaultGroup = otherGroups[0]

                privileges = conn.get_privileges_from_form(form)
                if privileges is not None:
                    # Only process privileges that we have permission to set
                    privileges = [
                        p for p in privileges
                        if p in conn.getCurrentAdminPrivileges()
                    ]
                # Create a User, Restricted-Admin or Admin, based on privileges
                conn.createExperimenter(omename, firstName, lastName, email,
                                        admin, active, defaultGroup,
                                        otherGroups, password, privileges,
                                        middleName, institution)

                return HttpResponseRedirect(reverse("waexperimenters"))
            # Handle invalid form
            context = {'form': form, 'can_modify_user': can_modify_user}
    elif action == 'edit':
        experimenter, defaultGroup, otherGroups, isLdapUser, hasAvatar = \
            prepare_experimenter(conn, eid)
        try:
            defaultGroupId = defaultGroup.id
        except:
            defaultGroupId = None

        initial = {
            'omename': experimenter.omeName,
            'first_name': experimenter.firstName,
            'middle_name': experimenter.middleName,
            'last_name': experimenter.lastName,
            'email': experimenter.email,
            'institution': experimenter.institution,
            'active': experimenter.isActive(),
            'default_group': defaultGroupId,
            'my_groups': otherGroups,
            'other_groups': [g.id for g in otherGroups],
            'groups': otherGroupsInitialList(groups)
        }

        # Load 'AdminPrivilege' roles for 'initial'
        privileges = conn.getAdminPrivileges(experimenter.id)
        for p in conn.get_privileges_for_form(privileges):
            initial[p] = True

        role = 'user'
        if experimenter.isAdmin():
            if 'ReadSession' in privileges:
                role = 'administrator'
            else:
                role = 'restricted_administrator'
        initial['role'] = role

        root_id = [conn.getAdminService().getSecurityRoles().rootId]
        user_id = conn.getUserId()
        experimenter_root = long(eid) == root_id
        experimenter_me = long(eid) == user_id
        form = ExperimenterForm(can_modify_user=can_modify_user,
                                user_privileges=user_privileges,
                                experimenter_me=experimenter_me,
                                experimenter_root=experimenter_root,
                                initial=initial)
        password_form = ChangePassword()

        admin_groups = [
            conn.getAdminService().getSecurityRoles().systemGroupId
        ]
        context = {
            'form': form,
            'eid': eid,
            'ldapAuth': isLdapUser,
            'can_modify_user': can_modify_user,
            'password_form': password_form,
            'admin_groups': admin_groups
        }
    elif action == 'save':
        experimenter, defaultGroup, otherGroups, isLdapUser, hasAvatar = \
            prepare_experimenter(conn, eid)
        if request.method != 'POST':
            return HttpResponseRedirect(
                reverse(viewname="wamanageexperimenterid",
                        args=["edit", experimenter.id]))
        else:
            name_check = conn.checkOmeName(request.POST.get('omename'),
                                           experimenter.omeName)
            email_check = conn.checkEmail(request.POST.get('email'),
                                          experimenter.email)
            my_groups = getSelectedGroups(conn,
                                          request.POST.getlist('other_groups'))
            initial = {
                'my_groups': my_groups,
                'groups': otherGroupsInitialList(groups)
            }
            form = ExperimenterForm(can_modify_user=can_modify_user,
                                    user_privileges=user_privileges,
                                    initial=initial,
                                    data=request.POST.copy(),
                                    name_check=name_check,
                                    email_check=email_check)

            if form.is_valid():
                logger.debug("Update experimenter form:" +
                             str(form.cleaned_data))
                omename = form.cleaned_data['omename']
                firstName = form.cleaned_data['first_name']
                middleName = form.cleaned_data['middle_name']
                lastName = form.cleaned_data['last_name']
                email = form.cleaned_data['email']
                institution = form.cleaned_data['institution']
                role = form.cleaned_data['role']
                admin = role in ('administrator', 'restricted_administrator')
                active = form.cleaned_data['active']
                rootId = conn.getAdminService().getSecurityRoles().rootId
                # User can't disable themselves or 'root'
                if experimenter.getId() in [conn.getUserId(), rootId]:
                    # disabled checkbox not in POST: do it manually
                    active = True
                defaultGroup = form.cleaned_data['default_group']
                otherGroups = form.cleaned_data['other_groups']

                # default group
                # if default group was not selected take first from the list.
                if defaultGroup is None:
                    defaultGroup = otherGroups[0]
                for g in groups:
                    if long(defaultGroup) == g.id:
                        dGroup = g
                        break

                listOfOtherGroups = set()
                # rest of groups
                for g in groups:
                    for og in otherGroups:
                        # remove defaultGroup from otherGroups if contains
                        if long(og) == long(dGroup.id):
                            pass
                        elif long(og) == g.id:
                            listOfOtherGroups.add(g)

                # Update 'AdminPrivilege' config roles for user
                privileges = conn.get_privileges_from_form(form)
                if privileges is None:
                    privileges = []
                # Only process privileges that we have permission to set
                to_add = []
                to_remove = []
                for p in conn.getCurrentAdminPrivileges():
                    if p in privileges:
                        to_add.append(p)
                    else:
                        to_remove.append(p)

                conn.updateAdminPrivileges(experimenter.id, to_add, to_remove)

                conn.updateExperimenter(experimenter, omename, firstName,
                                        lastName, email, admin, active, dGroup,
                                        listOfOtherGroups, middleName,
                                        institution)
                return HttpResponseRedirect(reverse("waexperimenters"))
            context = {
                'form': form,
                'eid': eid,
                'ldapAuth': isLdapUser,
                'can_modify_user': can_modify_user
            }
    else:
        return HttpResponseRedirect(reverse("waexperimenters"))

    context['template'] = template
    return context
示例#24
0
def userAdmin(request, userId2):
   WEB_FILES, LIVE_SITE, totalNumberOfGames, sendBackUrl, startOffset, \
   user, userId, message, topHits, topRated = initialVars(request)

   #log(request, 'USERADMINPAGE', 'just landed', sendBackUrl)

   # need to convert to strings otherwise methods are unhappy.
   # (should look into why this is.... TODO)
   userId = str(userId)
   userId2 = str(userId2)

   # set sendBackUrl to their userPage if they logout
   sendBackUrl = "/user/" + userId

   # This will see if the user who's page is queried exists.
   try:
      userAdmin = User.objects.get(id__exact=userId)
   except ObjectDoesNotExist:
      request.session['message'] = "Something is amiss with your session.\
      Please log in again!"
      return HttpResponseRedirect('/')

   if user == None:
      request.session['message'] = "Something is amiss with your session.\
      Please log in again."
      return HttpResponseRedirect('/')
   elif user != userAdmin:
      request.session['message'] = "You aren't allowed on that page!"
      return HttpResponseRedirect('/')
   elif int(userId) != int(userId2):
      # just another paranoid check
      request.session['message'] = "You aren't allowed on that page!"
      return HttpResponseRedirect('/')

   if request.method == 'GET':
      # forms to change password and description
      try:
         userDescription = UserProfile.objects.get(user=user)
      except ObjectDoesNotExist:
         userDescription = None

      passwordForm = ChangePassword(initial={'username': user.username})
      descriptionForm = UserDescription(initial={
      'userId': userId, 
      'description': userDescription
      })

   elif request.method == 'POST':
      whichform = request.POST.get('descriptionName', '')

      if whichform: 
         # Form is description form
         descriptionForm = UserDescription(request.POST)
         if descriptionForm.is_valid():
            userFromProfile = descriptionForm.cleaned_data['userId']
            description = descriptionForm.cleaned_data['description']

            try:
               userDescription = UserProfile.objects.get(user=user)
            except ObjectDoesNotExist:
               userDescription = None

            if userDescription == None:
               userDescription = UserProfile(user=user, description=description)
            else:
               userDescription.description = description

            userDescription.save()

            #log(request, 'USERADMINPAGE', 'modified description', sendBackUrl)

            message = "The description has been changed. Perhaps to something\
            more meaningful. Perhaps to less. Tough to say."
         else:
            # need to reload to User Admin Page with all variables
            message = "Dude, something went wrong. Why you trying to hack our\
            system?"
            #log(request, 'USERADMINPAGEERROR', 'failed to modify description', sendBackUrl)
            # passwordForm = ChangePassword(initial={'username': user.username})
            # return render_to_response('useradmin.html' , locals())

         passwordForm = ChangePassword(initial={'username': user.username})
         return render_to_response('useradmin.html' , locals())

      else:
         # Password form is submitted, POST
         # First reinitialize the description form.
         try:
            userDescription = UserProfile.objects.get(user=user)
         except ObjectDoesNotExist:
            userDescription = None

         descriptionForm = UserDescription(initial={
         'userId': userId, 
         'description': userDescription
         })

         passwordForm = ChangePassword(request.POST)
         if passwordForm.is_valid():
            username = passwordForm.cleaned_data['username']
            passwordOld = passwordForm.cleaned_data['passwordOld']
            passwordNew1 = passwordForm.cleaned_data['passwordNew1']
            passwordNew2 = passwordForm.cleaned_data['passwordNew2']
         else:
            # need to reload to User Admin Page with all variables
            #log(request, 'USERADMINPAGEERROR', 'Password Form not valid', sendBackUrl)
            return render_to_response('useradmin.html' , locals())

         if passwordNew1 != passwordNew2:
            #log(request, 'USERADMINPAGEERROR', 'Passwords do not match', sendBackUrl)
            message = "Passwords do not match!"
            return render_to_response('useradmin.html' , locals())

         try:
            #Check username from hidden field against user.username from session
            if user.username != username:
               message = "User Names don't match. Something Funny's going on."
               return render_to_response('useradmin.html' , locals())

            # get user again based upon username just to be sure.
            u = User.objects.get(username__exact=username)
            if u:
               verifyOldPassword = u.check_password(passwordOld)
               if verifyOldPassword:
                  u.set_password(passwordNew1)
                  u.save()
                  #log(request, 'USERADMINPAGE', 'Successfully Changed passwords', sendBackUrl)
               else:
                  message = "Old Password did not match!"
                  #log(request, 'USERADMINPAGEERROR', 'Old Password did not match', sendBackUrl)
                  return render_to_response('useradmin.html' , locals())

               request.session['message'] = "Password has been changed. Now go do something productive!"
               return HttpResponseRedirect("/useradmin/" + userId)
               #return render_to_response('useradmin.html' , locals())

            else: # No user id?!  Just return the user to the home page.
               return HttpResponseRedirect('/')
         
         except:
            # TODO log that there was an invalid POST
            #log(request, 'USERADMINPAGEERROR', 'invalid form POST', sendBackUrl)
            return HttpResponseRedirect('/')

   return render_to_response('useradmin.html', locals())
示例#25
0
def userAdmin(request, userId2):
    WEB_FILES, LIVE_SITE, totalNumberOfGames, sendBackUrl, startOffset, \
    user, userId, message, topHits, topRated = initialVars(request)

    #log(request, 'USERADMINPAGE', 'just landed', sendBackUrl)

    # need to convert to strings otherwise methods are unhappy.
    # (should look into why this is.... TODO)
    userId = str(userId)
    userId2 = str(userId2)

    # set sendBackUrl to their userPage if they logout
    sendBackUrl = "/user/" + userId

    # This will see if the user who's page is queried exists.
    try:
        userAdmin = User.objects.get(id__exact=userId)
    except ObjectDoesNotExist:
        request.session['message'] = "Something is amiss with your session.\
      Please log in again!"

        return HttpResponseRedirect('/')

    if user == None:
        request.session['message'] = "Something is amiss with your session.\
      Please log in again."

        return HttpResponseRedirect('/')
    elif user != userAdmin:
        request.session['message'] = "You aren't allowed on that page!"
        return HttpResponseRedirect('/')
    elif int(userId) != int(userId2):
        # just another paranoid check
        request.session['message'] = "You aren't allowed on that page!"
        return HttpResponseRedirect('/')

    if request.method == 'GET':
        # forms to change password and description
        try:
            userDescription = UserProfile.objects.get(user=user)
        except ObjectDoesNotExist:
            userDescription = None

        passwordForm = ChangePassword(initial={'username': user.username})
        descriptionForm = UserDescription(initial={
            'userId': userId,
            'description': userDescription
        })

    elif request.method == 'POST':
        whichform = request.POST.get('descriptionName', '')

        if whichform:
            # Form is description form
            descriptionForm = UserDescription(request.POST)
            if descriptionForm.is_valid():
                userFromProfile = descriptionForm.cleaned_data['userId']
                description = descriptionForm.cleaned_data['description']

                try:
                    userDescription = UserProfile.objects.get(user=user)
                except ObjectDoesNotExist:
                    userDescription = None

                if userDescription == None:
                    userDescription = UserProfile(user=user,
                                                  description=description)
                else:
                    userDescription.description = description

                userDescription.save()

                #log(request, 'USERADMINPAGE', 'modified description', sendBackUrl)

                message = "The description has been changed. Perhaps to something\
            more meaningful. Perhaps to less. Tough to say."

            else:
                # need to reload to User Admin Page with all variables
                message = "Dude, something went wrong. Why you trying to hack our\
            system?"

                #log(request, 'USERADMINPAGEERROR', 'failed to modify description', sendBackUrl)
                # passwordForm = ChangePassword(initial={'username': user.username})
                # return render_to_response('useradmin.html' , locals())

            passwordForm = ChangePassword(initial={'username': user.username})
            return render_to_response('useradmin.html', locals())

        else:
            # Password form is submitted, POST
            # First reinitialize the description form.
            try:
                userDescription = UserProfile.objects.get(user=user)
            except ObjectDoesNotExist:
                userDescription = None

            descriptionForm = UserDescription(initial={
                'userId': userId,
                'description': userDescription
            })

            passwordForm = ChangePassword(request.POST)
            if passwordForm.is_valid():
                username = passwordForm.cleaned_data['username']
                passwordOld = passwordForm.cleaned_data['passwordOld']
                passwordNew1 = passwordForm.cleaned_data['passwordNew1']
                passwordNew2 = passwordForm.cleaned_data['passwordNew2']
            else:
                # need to reload to User Admin Page with all variables
                #log(request, 'USERADMINPAGEERROR', 'Password Form not valid', sendBackUrl)
                return render_to_response('useradmin.html', locals())

            if passwordNew1 != passwordNew2:
                #log(request, 'USERADMINPAGEERROR', 'Passwords do not match', sendBackUrl)
                message = "Passwords do not match!"
                return render_to_response('useradmin.html', locals())

            try:
                #Check username from hidden field against user.username from session
                if user.username != username:
                    message = "User Names don't match. Something Funny's going on."
                    return render_to_response('useradmin.html', locals())

                # get user again based upon username just to be sure.
                u = User.objects.get(username__exact=username)
                if u:
                    verifyOldPassword = u.check_password(passwordOld)
                    if verifyOldPassword:
                        u.set_password(passwordNew1)
                        u.save()
                        #log(request, 'USERADMINPAGE', 'Successfully Changed passwords', sendBackUrl)
                    else:
                        message = "Old Password did not match!"
                        #log(request, 'USERADMINPAGEERROR', 'Old Password did not match', sendBackUrl)
                        return render_to_response('useradmin.html', locals())

                    request.session[
                        'message'] = "Password has been changed. Now go do something productive!"
                    return HttpResponseRedirect("/useradmin/" + userId)
                    #return render_to_response('useradmin.html' , locals())

                else:  # No user id?!  Just return the user to the home page.
                    return HttpResponseRedirect('/')

            except:
                # TODO log that there was an invalid POST
                #log(request, 'USERADMINPAGEERROR', 'invalid form POST', sendBackUrl)
                return HttpResponseRedirect('/')

    return render_to_response('useradmin.html', locals())