def user_change_password(request, userid):
    if not userid:
        userid = request.user.id

    # only admin can change the password for someone else
    if request.user.id != userid and request.user.profile.role != Profile.ACCESS_ADMIN:
        messages.error(request, 'Something went wrong.')
        return HttpResponse("Something went wrong.")

    qs = User.objects.filter(id=userid)
    if qs.count() < 1:
        return HttpResponse("No such user")
    the_user = qs.get()

    if request.method == 'POST':
        form = AdminPasswordChangeForm(the_user, request.POST)
        if form.is_valid():
            form.save()
            messages.success(
                request, f'Password for "{the_user.username}" {the_user.get_full_name()} ' +
                'was successfully updated.')
            if request.user == the_user:
                return redirect('sis:profile')
            else:
                return redirect(reverse('schooladmin:user', args=[userid]))
        else:
            messages.error(request, 'Please correct the error(s) below.')
    else:
        form = AdminPasswordChangeForm(request.user)
    return render(request, 'sis/user_change_password.html', {'auser': the_user, 'form': form})
Example #2
0
def recover_pass(request):
    if Perfil.objects.filter(code_activation = request.GET['code']):
        perfil = Perfil.objects.get(code_activation = request.GET['code'])
        usuario = User.objects.get(id = perfil.usuario_id)
        categorias = Categorias.objects.all()
        envio = perfil.time + timedelta(hours=2)
        hoy = datetime.now()
        if envio.strftime("%Y-%m-%d %H:%M") >= hoy.strftime("%Y-%m-%d %H:%M"):
            if request.method == 'POST':
                formulario = AdminPasswordChangeForm(user=usuario, data=request.POST)
                if formulario.is_valid():
                    formulario.save()
                    perfil.code_activation += usuario.username
                    perfil.save()
                    sms = "Contraseña Cambiada Correctamente"
                    messages.success(request, sms)
                    return HttpResponseRedirect(reverse(loguet_in))
            else:
                formulario = AdminPasswordChangeForm(user=usuario)
            return render(request, 'users/change_pass.html', {
                'formulario':formulario,
                'categorias':categorias,
            })
        else:
            sms = "El Enlace ya expiro por favor solicite uno nuevo"
            messages.error(request, sms, 'danger')
            return HttpResponseRedirect(reverse(sent_code_reset_pass))
    else:
        sms = "Enlace no Valido"
        messages.error(request, sms, 'danger')
        return HttpResponseRedirect(reverse(sent_code_reset_pass))
Example #3
0
def user_change_password(request, id):
    if not request.user.has_perm('auth.change_user'):
        raise PermissionDenied
    user = get_object_or_404(User, pk=id)
    if request.method == 'POST':
        form = AdminPasswordChangeForm(user, request.POST)
        if form.is_valid():
            new_user = form.save()
            msg = _('Password changed successfully.')
            request.user.message_set.create(message=msg)
            return HttpResponseRedirect('..')
    else:
        form = AdminPasswordChangeForm(user)
    return render_to_response('admin/auth/user/change_password.html', {
        'title': _('Change password: %s') % escape(user.username),
        'form': form,
        'is_popup': '_popup' in request.REQUEST,
        'add': True,
        'change': False,
        'has_delete_permission': False,
        'has_change_permission': True,
        'has_absolute_url': False,
        'opts': User._meta,
        'original': user,
        'show_save': True,
    }, context_instance=RequestContext(request))
Example #4
0
def user_recoverpass(request, user_id, code):
    if ActivationCode.objects.filter(user_id = user_id, state = True, code = code, description='Reset Pass'):
        activation = ActivationCode.objects.get(user_id = user_id, state = True, code = code, description='Reset Pass')
        user = User.objects.get(id = user_id)
        envio = activation.send_time + timedelta(hours=24)
        today = datetime.now()
        if envio.strftime("%Y-%m-%d %H:%M") >= today.strftime("%Y-%m-%d %H:%M"):
            if request.method == 'POST':
                form = AdminPasswordChangeForm(user=user, data=request.POST)
                if form.is_valid():
                    form.save()
                    activation.state = False
                    activation.save()
                    sms = "Contraseña Cambiada Correctamente"
                    messages.success(request, sms)
                    return HttpResponseRedirect(reverse(user_login))
            else:
                form = AdminPasswordChangeForm(user=user)
            return render(request, 'users/reset_pass.html', {
                'form':form,
            })
        else:
            sms = "El Enlace ya expiro por favor solicite uno nuevo"
            messages.error(request, sms, 'danger')
            return HttpResponseRedirect(reverse(user-user-user_sendcoderesetpass))
    else:
        sms = "Enlace no Valido"
        messages.error(request, sms, 'danger')
        return HttpResponseRedirect('/')
Example #5
0
def password_nuevo(request):
    algo=""
    if request.method == 'POST' :
        formulario2=newpass(request.POST)
        if formulario2.is_valid():
            contrasena=request.POST['actual_password']
            usuario=request.user
            acceso=authenticate(username=usuario,password=contrasena)
            if acceso is not None:
                formulario = AdminPasswordChangeForm(user=usuario, data=request.POST)
                if formulario.is_valid():
                    formulario.save()
                    logout(request)
                return HttpResponseRedirect("/db/menu/loginlink/")
                pass
            else:
                formulario = AdminPasswordChangeForm(user=request.user)
                formulario2 = newpass()
                algo="Las contrasena actual no es la misma"
                return render_to_response('repassword.html', {'formulario' :formulario, "formulario2": formulario2, "algo": algo}, context_instance=RequestContext(request))
            pass
    else:
        formulario = AdminPasswordChangeForm(user=request.user)
        formulario2 = newpass()
    return  render_to_response('repassword.html', {'formulario' :formulario, "formulario2": formulario2}, context_instance=RequestContext(request))
Example #6
0
def editZbyAccountView(request, acpk):
    if request.POST:
        print "post edit user"
        instance = get_object_or_404(sysUser, pk=int(acpk))
        userForm = AdminPasswordChangeForm(request.POST, instance=instance)
        if userForm.is_valid():
            print "form is valid"
            instance = userForm.save(commit=True)
            print instance.userid
            ActionlogInstance = Actionlog(userid=119,
                                          logevent=u"编辑账户:" +
                                          instance.username,
                                          loglevel="0")
            ActionlogInstance.save()
            return HttpResponseRedirect("/system/accounts/")
        else:
            return render(request, 'system/addAccount.html', {
                'userForm': userForm,
                'fun': u"编辑"
            })
    try:
        instance = get_object_or_404(sysUser, pk=int(acpk))
        userForm = AdminPasswordChangeForm(instance=instance)
        return render(request, 'system/addAccount.html', {
            'userForm': userForm,
            'fun': u"编辑"
        })
    except Exception, e:
        print e
Example #7
0
 def test_password_whitespace_not_stripped(self):
     user = User.objects.get(username="******")
     data = {"password1": " pass ", "password2": " pass "}
     form = AdminPasswordChangeForm(user, data)
     self.assertTrue(form.is_valid())
     self.assertEqual(form.cleaned_data["password1"], data["password1"])
     self.assertEqual(form.cleaned_data["password2"], data["password2"])
Example #8
0
def change_password(request,
                    user_id,
                    template_name='accounts/admin_change_pw.html'):
    """
    Admin change users password
    """
    user_account = get_object_or_404(User, pk=user_id)
    if request.method == 'POST':
        form = AdminPasswordChangeForm(user_account, request.POST)
        if form.is_valid():
            try:
                form.save()
                msg = _(
                    'The password for user %(account)s has been updated') % {
                        'account': user_account.username
                    }
            except DatabaseError:
                msg = _('The password could not be updated')
            djmessages.info(request, msg)
            return HttpResponseRedirect(reverse('user-profile',
                                                args=[user_id]))
    else:
        form = AdminPasswordChangeForm(user_account)
    user_account = None
    form.fields['password1'].widget.attrs['size'] = '45'
    form.fields['password2'].widget.attrs['size'] = '45'
    return render_to_response(template_name,
                              locals(),
                              context_instance=RequestContext(request))
Example #9
0
def user_change_password(request, pk):
    """
    Función que gestiona la actualización de las contraseña de un usuario.
    """
    model = User
    usuario = get_object_or_404(User, pk=pk)
    print usuario
    form = AdminPasswordChangeForm(user=usuario)
    if request.method == 'POST':
        form = AdminPasswordChangeForm(user=usuario, data=request.POST)
        if form.is_valid():
            form.save()
            messages = ['Se actualizó la contraseña del usuario con éxito']
            usuarios = User.objects.all()
            data = {}
            data['object_list'] = usuarios
            object_list = usuarios
            return render_to_response("usuarios/list_users.html", {
                'messages': messages,
                'object_list': object_list
            },
                                      context_instance=RequestContext(request))
        else:
            print "No se realizó el cambio de contraseña"
    return render(request, 'usuarios/user_change_password.html', {
        'form': form,
        'usuario': usuario
    })
Example #10
0
def user_change_password(request: HttpRequest, user_id) -> HttpResponse:
    # Get the User
    user = get_object_or_404(User, pk=user_id)

    # Dict for view
    view_dict = {}  # type: Dict[str, object]

    # process or create form
    if request.method == 'POST':
        password_form = AdminPasswordChangeForm(user, request.POST)
        # process admin user
        if password_form.is_valid():
            user = password_form.save()
            messages.add_message(request, messages.SUCCESS,
                                 f'User {user.username} password updated.')
            return HttpResponseRedirect(reverse_lazy('index'))

    else:
        password_form = AdminPasswordChangeForm(user)

    # modify the css and label attributes
    password_form.fields['password1'].widget.attrs['class'] = 'form-control'
    password_form.fields['password1'].label = "New Password:"******"New Password (again):"

    view_dict['form'] = password_form
    view_dict['user'] = user

    return render(request, 'user_change_password.html', view_dict)
Example #11
0
def user_change_password(request, id):
    if not request.user.has_perm('auth.change_user'):
        raise PermissionDenied
    user = get_object_or_404(User, pk=id)
    if request.method == 'POST':
        form = AdminPasswordChangeForm(user, request.POST)
        if form.is_valid():
            new_user = form.save()
            msg = _('Password changed successfully.')
            request.user.message_set.create(message=msg)
            return HttpResponseRedirect('..')
    else:
        form = AdminPasswordChangeForm(user)
    return render_to_response(
        'admin/auth/user/change_password.html', {
            'title': _('Change password: %s') % escape(user.username),
            'form': form,
            'is_popup': '_popup' in request.REQUEST,
            'add': True,
            'change': False,
            'has_delete_permission': False,
            'has_change_permission': True,
            'has_absolute_url': False,
            'opts': User._meta,
            'original': user,
            'save_as': False,
            'show_save': True,
            'root_path': re.sub('auth/user/(\d+)/password/$', '',
                                request.path),
        },
        context_instance=RequestContext(request))
Example #12
0
def password_resetenter(request, uidb64=None, token=None):
    """
    Enter new password for reset password.
    """

    context_dict = {}
    if request.method == 'POST':
        assert uidb64 is not None and token is not None
        uid = urlsafe_base64_decode(uidb64)
        user = models.Employee.objects.get(soft_delete=False, pk=uid)
        db_user = user.user
        reset_token = models.PasswordReset.objects.get(token=token, user=user)
        token_check = models.PasswordReset.objects.filter(
            user=user,
            soft_delete=False,
            token_consumed=False,
        ).exclude(token=token).first()
        update_fields = []
        token_check.token_consumed = True
        update_fields.append('token_consumed')
        token_check.soft_delete = True
        update_fields.append('soft_delete')
        token_check.save(update_fields=update_fields)
        time_threshold = timezone.now(
        ) - reset_token.password_request_created_at
        if time_threshold > timedelta(minutes=30):
            try:
                update_fields = []
                reset_token.token_consumed = True
                update_fields.append('token_consumed')
                reset_token.soft_delete = True
                update_fields.append('soft_delete')
                reset_token.save(update_fields=update_fields)
            except Exception as e:
                print(e)
        if reset_token.user == user and reset_token.token == token:
            if reset_token.token_consumed == False and reset_token.soft_delete == False:
                try:
                    update_fields = []
                    reset_token.token_consumed = True
                    update_fields.append('token_consumed')
                    reset_token.soft_delete = True
                    update_fields.append('soft_delete')
                    reset_token.save(update_fields=update_fields)
                except Exception as e:
                    print(e)
                form = AdminPasswordChangeForm(user=db_user, data=request.POST)
                if form.is_valid():
                    form.save()
                    history = models.History(user=user,
                                             activity="",
                                             activity_type="Reset Password")
                    history.save()
                    context_dict["message"] = "Password changed successfully"
                else:
                    context_dict["message"] = "Password not changed"
            else:
                context_dict["message"] = "Link is no longer valid"
    return render(request, "reset.html", context_dict)
Example #13
0
def reset_pass(request):
    if request.method == 'POST' :
        formulario = AdminPasswordChangeForm(user=request.user, data=request.POST)
        if formulario.is_valid():
            formulario.save()
            return HttpResponseRedirect('/user/login')
    else:
        formulario = AdminPasswordChangeForm(user=request.user)
    return  render_to_response('user/reset_pass.html', {'formulario' :formulario}, context_instance=RequestContext(request))
Example #14
0
 def test_success(self, password_changed):
     user = User.objects.get(username="******")
     data = {"password1": "test123", "password2": "test123"}
     form = AdminPasswordChangeForm(user, data)
     self.assertTrue(form.is_valid())
     form.save(commit=False)
     self.assertEqual(password_changed.call_count, 0)
     form.save()
     self.assertEqual(password_changed.call_count, 1)
Example #15
0
def reset_pass(request):
    if request.method == 'POST' :
        formulario = AdminPasswordChangeForm(user=request.user, data=request.POST)
        if formulario.is_valid():
            formulario.save()
            return HttpResponseRedirect('/user/login')
    else:
        formulario = AdminPasswordChangeForm(user=request.user)
    return  render_to_response('user/reset_pass.html', {'formulario' :formulario}, context_instance=RequestContext(request))
def change_admin_password(request):
    if request.method == 'POST':
        form = AdminPasswordChangeForm(request.user, request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('morepractice:thanks'))

    else:
        form = AdminPasswordChangeForm(request.user)
    return render(request, 'morepractice/change_admin_password.html', {'form': form})
Example #17
0
def modifica_password_utente(request,utente_id):
	user = User.objects.get(id=utente_id)
	if request.method == 'POST': # If the form has been submitted...
		form = AdminPasswordChangeForm(user=user, data=request.POST)
		if form.is_valid():
			form.save()
			return HttpResponseRedirect('/utenti/') # Redirect after POST
	else:
		form = AdminPasswordChangeForm(user=user)
	return render(request,'form_password_utente.html',{'request':request, 'form': form, 'user': user,})
 def test_password_whitespace_not_stripped(self):
     user = User.objects.get(username='******')
     data = {
         'password1': ' pass ',
         'password2': ' pass ',
     }
     form = AdminPasswordChangeForm(user, data)
     self.assertTrue(form.is_valid())
     self.assertEqual(form.cleaned_data['password1'], data['password1'])
     self.assertEqual(form.cleaned_data['password2'], data['password2'])
Example #19
0
 def admin_change_password(self, params):
     """As Admin, update another user's password."""
     if not self.user.is_superuser:
         raise HandlerPermissionError()
     user = self.get_object(params)
     form = AdminPasswordChangeForm(user=user, data=get_QueryDict(params))
     if form.is_valid():
         form.save()
     else:
         raise HandlerValidationError(form.errors)
Example #20
0
 def test_password_whitespace_not_stripped(self):
     user = User.objects.get(username='******')
     data = {
         'password1': ' pass ',
         'password2': ' pass ',
     }
     form = AdminPasswordChangeForm(user, data)
     self.assertTrue(form.is_valid())
     self.assertEqual(form.cleaned_data['password1'], data['password1'])
     self.assertEqual(form.cleaned_data['password2'], data['password2'])
Example #21
0
 def test_password_whitespace_not_stripped(self):
     user = User.objects.get(username="******")
     data = {
         "password1": " pass ",
         "password2": " pass ",
     }
     form = AdminPasswordChangeForm(user, data)
     self.assertTrue(form.is_valid())
     self.assertEqual(form.cleaned_data["password1"], data["password1"])
     self.assertEqual(form.cleaned_data["password2"], data["password2"])
Example #22
0
def reset_pass(request):
    if request.method == 'POST':
        form = AdminPasswordChangeForm(user=request.user, data=request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse(user_index))
    else:
        form = AdminPasswordChangeForm(user=request.user)
    return render(request, 'users/reset_pass.html', {
        'form': form,
    })
Example #23
0
def cambiar_password(request):
    if request.method == 'POST' :
        formulario = AdminPasswordChangeForm(user=request.user, data=request.POST)
        if formulario.is_valid():
            formulario.save()
            return HttpResponseRedirect(reverse(iniciar_sesion))
    else:
        formulario = AdminPasswordChangeForm(user=request.user)
    return  render(request, 'users/reset_pass.html', {
        'formulario' :formulario,
        })
Example #24
0
def password_change(req):
    user_to_edit = User.objects.get(id=req.user.id)
    if req.method == 'POST': 
        password_form = AdminPasswordChangeForm(user_to_edit, req.POST)
        if password_form.is_valid():
            password_form.save()
            return HttpResponseRedirect('/')
    else:
        password_form = AdminPasswordChangeForm(user_to_edit)
    template_name="password_change.html"
    return render_to_response(req, template_name, {"form" : password_form})
Example #25
0
def user_changepassword(request):
    if request.method == 'POST' :
        form = AdminPasswordChangeForm(user=request.user, data=request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse(user_notification))
    else:
        form= AdminPasswordChangeForm(user=request.user)
    return  render(request, 'users/change_pass.html', {
        'form' :form,
    })
Example #26
0
def password_change(req):
    user_to_edit = User.objects.get(id=req.user.id)
    if req.method == 'POST':
        password_form = AdminPasswordChangeForm(user_to_edit, req.POST)
        if password_form.is_valid():
            password_form.save()
            return HttpResponseRedirect('/')
    else:
        password_form = AdminPasswordChangeForm(user_to_edit)
    template_name = "password_change.html"
    return render(req, template_name, {"form": password_form})
Example #27
0
def password_change(req, id):
    user_to_edit = User.objects.get(id=id)
    print req.user
    if req.method == "POST":
        password_form = AdminPasswordChangeForm(user_to_edit, req.POST)
        if password_form.is_valid():
            password_form.save()
            return HttpResponseRedirect("/iavi/users/%s/edit" % user_to_edit.id)
    else:
        password_form = AdminPasswordChangeForm(user_to_edit)
    template_name = "iavi/password_change.html"
    return render_to_response(req, template_name, {"current_user": user_to_edit, "form": password_form})
Example #28
0
 def test_success(self, password_changed):
     user = User.objects.get(username='******')
     data = {
         'password1': 'test123',
         'password2': 'test123',
     }
     form = AdminPasswordChangeForm(user, data)
     self.assertTrue(form.is_valid())
     form.save(commit=False)
     self.assertEqual(password_changed.call_count, 0)
     form.save()
     self.assertEqual(password_changed.call_count, 1)
Example #29
0
def update_user_password(request, user_id):
    user = User.objects.get(id=user_id)
    if request.method == 'GET':
        form = AdminPasswordChangeForm(user, None)
        return render_to_response('update_password.html', {'form':form, 'editing':True, 'site_user':user}, context_instance=RequestContext(request))

    if request.method == 'POST':
        form = AdminPasswordChangeForm(user,request.POST)
        if form.is_valid():
            form.save()
            return redirect(reverse_lazy('users:edit_user',kwargs={'user_id':str(user.id)}))
        return render_to_response('update_password.html', {'form':form, 'editing':True, 'site_user':user}, context_instance=RequestContext(request))
Example #30
0
def change_password(request):

    if request.method == 'POST':
        form = AdminPasswordChangeForm(user=request.user, data=request.POST)
        if form.is_valid():
            request.user.set_password(form.clean_password2())
            return HttpResponseRedirect('/recording/')
        else:
            context = {'form': form}
            return render(request, 'change_password.html', {'form': form})
    else:
        form = AdminPasswordChangeForm(user=request.user)
        return render(request, 'change_password.html', {'form': form})
Example #31
0
def user_edit_password(request, user):
    if settings.EXTERNAL_AUTH:
        raise Http404()
    user = get_object_or_404(User, id=user)
    form = AdminPasswordChangeForm(user, request.POST or None)
    if request.method == 'POST' and form.is_valid():
        form.save()
        messages.success(request, 'User password modified successfully.')
        return redirect('show-user', user.id)
    return render(request, 'accounts/user_edit.html', {
        'user': user,
        'form': form,
    })
def password_change(req, id):
    user_to_edit = User.objects.get(id=id)
    print req.user
    if req.method == 'POST': 
        password_form = AdminPasswordChangeForm(user_to_edit, req.POST)
        if password_form.is_valid():
            password_form.save()
            return HttpResponseRedirect('/iavi/users/%s/edit' % user_to_edit.id)
    else:
        password_form = AdminPasswordChangeForm(user_to_edit)
    template_name="iavi/password_change.html"
    return render_to_response(req, template_name, {"current_user" : user_to_edit,
                                                   "form" : password_form})
Example #33
0
def reset_pass(request):
    perfil = Perfil.objects.get(usuario = request.user)
    if request.method == 'POST' :
        formulario = AdminPasswordChangeForm(user=request.user, data=request.POST)
        if formulario.is_valid():
            formulario.save()
            return HttpResponseRedirect(reverse(loguet_in))
    else:
        formulario = AdminPasswordChangeForm(user=request.user)
    return  render(request, 'users/reset_pass.html', {
        'formulario' :formulario,
        'perfil':perfil,
    })
Example #34
0
def user_edit_password(request, user):
    if settings.EXTERNAL_AUTH:
        raise Http404()
    user = get_object_or_404(User, id=user)
    form = AdminPasswordChangeForm(user, request.POST or None)
    if request.method == 'POST' and form.is_valid():
        form.save()
        messages.success(request, 'User password modified successfully.')
        return redirect('show-user', user.id)
    return render(request, 'accounts/user_edit.html', {
        'user': user,
        'form': form,
    })
Example #35
0
def change_password(request):
    if request.method == 'POST':
        formulario = AdminPasswordChangeForm(user=request.user, data=request.POST)
        if formulario.is_valid():
            formulario.save()
            sms = "Contraseña Modificada Correctamente"
            messages.success(request, sms)
            return HttpResponseRedirect(reverse(info_usuario))
    else:
        formulario = AdminPasswordChangeForm(user=request.user)
    return render(request, 'usuarios/change_password.html', {
        'formulario':formulario,
    })
Example #36
0
def modifica_password_utente(request, utente_id):
    user = User.objects.get(id=utente_id)
    if request.method == 'POST':  # If the form has been submitted...
        form = AdminPasswordChangeForm(user=user, data=request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/utenti/')  # Redirect after POST
    else:
        form = AdminPasswordChangeForm(user=user)
    return render(request, 'form_password_utente.html', {
        'request': request,
        'form': form,
        'user': user,
    })
Example #37
0
def definir_senha(request, pk=None):
    user_model = get_user_model()
    user_obj = get_object_or_404(user_model, pk=pk)
    if request.method == "POST":
        form = AdminPasswordChangeForm(user=user_obj, data=request.POST)
        if form.is_valid():
            form.save()
            update_session_auth_hash(request, form.user)
            return HttpResponseRedirect(
                reverse('agentes:agente:detalhes', args=[pk]))
    else:
        form = AdminPasswordChangeForm(user=request.user)
    context = {'agente': user_obj, 'form': form, 'title': 'Redefinir senha'}
    return render(request, 'registration/password_change_form.html', context)
Example #38
0
def password(request, user_id):
    user = get_object_or_404(User, pk=user_id)
    if request.method == 'POST':
        form = AdminPasswordChangeForm(user, request.POST)
        if form.is_valid():
            form.save()
            messages.success(request, _(u'Password changed successfully.'))
            if request.user == user:
                update_session_auth_hash(request, form.user)
            return redirect(reverse('users:user', args=(user.pk, )))
        else:
            messages.error(request, _(u'Please correct the error below.'))
    else:
        form = AdminPasswordChangeForm(user)
    return render(request, 'users/password.html', {'form': form})
def admin_change_password(request, pk):
    if "cancel" in request.POST:
        return redirect('accounts:list_user')
    user_change = get_object_or_404(CustomUser, pk=pk)
    if request.method == 'POST':
        form = AdminPasswordChangeForm(user_change, request.POST)
        if form.is_valid():
            messages.success(request, ' password was successfully updated!')
            return redirect('accounts:list_user')
        else:
            messages.error(request, 'Please correct the error below.')
            return redirect('accounts:list_user')
    else:
        form = AdminPasswordChangeForm(user_change)
    return render(request, 'accounts/change_password.html', {'form': form})
Example #40
0
def appuser_manageView(request, id = None, template_name='registration/user_manage.html'):
	if id:
		userI = get_object_or_404(User, pk=id)
	else:
		userI = User()

	if request.method == 'POST':
		UserForm = AdminPasswordChangeForm(request.POST, request.FILES, instance=userI)
		if UserForm.is_valid():
			UserForm.save()
			return HttpResponseRedirect('/appusers/')
	else:
	 	UserForm = UserCreationForm(instance=userI)

	return render_to_response(template_name, {'UserForm': UserForm,}
			,context_instance = RequestContext(request))
Example #41
0
def admin_client_password(request, pk):
    '''
    Shows change password page
    '''
    user = User.objects.get(pk=pk)
    form = AdminPasswordChangeForm(user)
    if request.method == 'POST':
        form = AdminPasswordChangeForm(user, request.POST)
        if form.is_valid():
            user.set_password(form.cleaned_data.get('password1'))
            user.save()
            return redirect(reverse('admin'))
    return render(request, "admin_client_password.html", {
        'form': form,
        'pk': pk,
    })
Example #42
0
def user_change_password(request, id):
    user = User.objects.get(pk=id)
    form = AdminPasswordChangeForm(user, request.POST)
    if form.is_valid():
        new_user = form.save()
        msg = _('Password changed successfully.')
        request.user.message_set.create(message=msg)
        return HttpResponseRedirect('../../user/users')
    else:
        form = AdminPasswordChangeForm(user)
    extra_context = {
        
        'form': form,
        'change': True
        }
    return direct_to_template(request,"users/user_password_change.html",
                extra_context = extra_context)
Example #43
0
def change_password(request, user_id):
    """
    Changes user's password. Cannot change admins's password.
    """
    user = get_object_or_404(CustomUser, id=user_id, is_staff=False)
    form = AdminPasswordChangeForm(user, data=request.POST or None)

    if form.is_valid():
        form.save()

    resp = render(request, "snippets/change_password_form.html",
                  {"form": form})

    response_data = {"html": resp.content, 'user_id': user.id}

    return HttpResponse(json.dumps(response_data),
                        content_type="application/json")
Example #44
0
def users_setpassword(request, pk):

    object = get_object_or_404(User, pk=pk)

    if request.method == 'POST':  # If the form has been submitted...
        form = AdminPasswordChangeForm(user=object, data=request.POST)

        if form.is_valid():  # If the form is valid
            form.save()

            messages.success(request, 'The password has been saved.')

            return redirect(reverse('main.views.users_show', args=(object.pk, )))
    else:
        form = AdminPasswordChangeForm(user=object)

    return render_to_response('main/users/setpassword.html', {'form': form}, context_instance=RequestContext(request))
Example #45
0
def create_password(request):
    """
    A custom view for the admin password change form used for account activation.
    """

    if request.method == 'POST':
        form = AdminPasswordChangeForm(request.user, request.POST)
        if form.is_valid():
            user = form.save()
            update_session_auth_hash(request, user)  # Important!
            messages.success(request,
                             'Your password was successfully updated!')
            return redirect('users:account')
        else:
            messages.error(request, 'Please correct the errors below.')
    else:
        form = AdminPasswordChangeForm(request.user)
    return render(request, 'users/change_password.html', {'form': form})
Example #46
0
def employee_change_password(request, pk):
    user = get_object_or_404(User, id=pk)
    if request.method == 'POST':
        form = AdminPasswordChangeForm(user, request.POST)
        if form.is_valid():
            user = form.save()
            update_session_auth_hash(request, user)  # Important!
            messages.success(request,
                             'Your password was successfully updated!')
            return redirect('change_password')
        else:
            messages.error(request, 'Please correct the error below.')
    else:
        form = AdminPasswordChangeForm(user)
    return render(request, 'employees/employee_change_password.html', {
        'form': form,
        'object': user,
    })
Example #47
0
def change_password(request, user_id):
    try:
        passwd_user = User.objects.get(pk=user_id)
    except ObjectDoesNotExist:
        raise Http404
    
    if request.method == "POST":
        form = AdminPasswordChangeForm(passwd_user, request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('../../')
    
    else:
        form = AdminPasswordChangeForm(passwd_user)
    
    return render_to_response("accounts/admin_passwd.html",
                                {"form": form, "passwd_user": passwd_user},
                                context_instance=RequestContext(request))
Example #48
0
def change_user_password(request, userId):
    
    user = get_object_or_404(User, id=userId)
    
    if INTEGRATION_ENABLED:
        return redirect('user-password', user=user.pk)
    else:
        if request.method == 'POST':
            passwordForm = AdminPasswordChangeForm(user, request.POST)
            if passwordForm.is_valid():
                user = passwordForm.save()
                request.user.message_set.create(message=_('Password updated'))
                return redirect('picket-admin-users')
        else:
            passwordForm = AdminPasswordChangeForm(user=user)
        
        return direct_to_template(request, 'picket/admin/user_password.html',
            {'password_form': passwordForm,})
Example #49
0
def user_password_change(request, user_id):
    user = get_object_or_404(User, id=user_id)
    if request.method == 'GET':
        form = AdminPasswordChangeForm(user)
        return TemplateResponse(request, 'user_password_change.html', {
            'form': form,
            'user': user
        })
    elif request.method == 'POST':
        form = AdminPasswordChangeForm(user, request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/server/users/')
        else:
            return TemplateResponse(request, 'user_password_change.html', {
                'form': form,
                'user_id': user_id
            })
Example #50
0
def change_password(request, user_id):
    try:
        passwd_user = User.objects.get(pk=user_id)
    except ObjectDoesNotExist:
        raise Http404
    
    if request.method == "POST":
        form = AdminPasswordChangeForm(passwd_user, request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/account/admin/')
    
    else:
        form = AdminPasswordChangeForm(passwd_user)
    
    return render_to_response("account/passwd.html",
                                {"form": form, "passwd_user": passwd_user},
                                context_instance=RequestContext(request))
Example #51
0
def user_password(request, profile_id):
    profile = get_object_or_404(USER_CURATOR.profile_class, id=profile_id)

    if request.method == 'POST':
        form = AdminPasswordChangeForm(profile.user, request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/yacon/nexus/users/list_users/')
    else:  # GET
        form = AdminPasswordChangeForm(profile.user)

    data = {
        'title': 'Change User Password',
        'profile': profile,
        'form': form,
        'clear_autocomplete': True,
    }

    return render(request, 'yacon/nexus/edit_user.html', data)
Example #52
0
def user_update_password(request, pk):
    user = get_object_or_404(User, pk=pk)
    if request.method == 'POST':
        form = AdminPasswordChangeForm(user, request.POST)
        if form.is_valid():
            user = form.save()
            update_session_auth_hash(request, user)  # Important!
            messages.success(
                request, _("User password changed: {}".format(user.username)))
            return redirect("admin:user_list")
        else:
            messages.error(request, _("Wrong Data Provided"))
    else:
        form = AdminPasswordChangeForm(user)

    return render(request, "accounts/change_password_form.html", {
        "form": form,
        "user": user.username
    })
Example #53
0
def change_password(request, user_id, template_name='accounts/change_pw.html'):
    """
    Admin change users password
    """
    user_account = get_object_or_404(User, pk=user_id)
    if request.method == 'POST':
        form = AdminPasswordChangeForm(user_account, request.POST)
        if form.is_valid():
            form.save()
            msg = 'The password for user %s has been updated' % (
                user_account.username)
            request.user.message_set.create(message=msg)
            return HttpResponseRedirect(reverse('user-profile', 
                args=[user_id]))
    else:
        form = AdminPasswordChangeForm(user_account)
    user_account = None
    form.fields['password1'].widget.attrs['size'] = '45'
    form.fields['password2'].widget.attrs['size'] = '45'
    return render_to_response(template_name, locals(), 
        context_instance=RequestContext(request))
Example #54
0
def change_password(request, user_id):
    """
    Changes user's password. Cannot change admins's password.
    """
    user = get_object_or_404(CustomUser, id=user_id, is_staff=False)
    form = AdminPasswordChangeForm(user, data=request.POST or None)

    if form.is_valid():
        form.save()

    resp = render(
        request,
        "snippets/change_password_form.html",
        {"form": form}
    )

    response_data = {"html": resp.content, 'user_id': user.id}

    return HttpResponse(
        json.dumps(response_data),
        content_type="application/json"
    )
Example #55
0
    def reset_password(self, request, id, form_url=''):
        if not self.has_change_permission(request):
            raise PermissionDenied
        user = get_object_or_404(self.queryset(request), pk=id)
        if request.method == 'POST':
            form = AdminPasswordChangeForm(user, request.POST)
            if form.is_valid():
                form.save()
                msg = _('Password changed successfully.')
                messages.success(request, msg)
                return HttpResponseRedirect('..')
        else:
            form = AdminPasswordChangeForm(user)

        fieldsets = [(None, {'fields': form.base_fields.keys()})]
        adminForm = admin.helpers.AdminForm(form, fieldsets, {})

        context = {
            'title': _('Change password: %s') % escape(user.username),
            'adminForm': adminForm,
            'form_url': mark_safe(form_url),
            'form': form,
            'is_popup': '_popup' in request.REQUEST,
            'add': True,
            'change': False,
            'has_delete_permission': False,
            'has_change_permission': True,
            'has_absolute_url': False,
            'opts': self.model._meta,
            'original': user,
            'save_as': False,
            'show_save': True,
        }
        return TemplateResponse(request, [
            'admin/auth/user/change_password.html'
        ], context, current_app=self.admin_site.name)
Example #56
0
def change_password(request, user_id, template_name='accounts/admin_change_pw.html'):
    """
    Admin change users password
    """
    user_account = get_object_or_404(User, pk=user_id)
    if request.method == 'POST':
        form = AdminPasswordChangeForm(user_account, request.POST)
        if form.is_valid():
            try:
                form.save()
                msg = _('The password for user %(account)s has been updated') % {
                'account': user_account.username}
            except DatabaseError:
                msg = _('The password could not be updated')
            djmessages.info(request, msg)
            return HttpResponseRedirect(reverse('user-profile',
                args=[user_id]))
    else:
        form = AdminPasswordChangeForm(user_account)
    user_account = None
    form.fields['password1'].widget.attrs['size'] = '45'
    form.fields['password2'].widget.attrs['size'] = '45'
    return render_to_response(template_name, locals(),
        context_instance=RequestContext(request))
Example #57
0
def custom_modify_user_view(request, targetUsername):
    """ The page to modify a user. """
    if targetUsername == ANONYMOUS_USERNAME:
        messages.add_message(request, messages.WARNING, MESSAGES["ANONYMOUS_EDIT"])
    page_name = "Admin - Modify User"
    targetUser = get_object_or_404(User, username=targetUsername)
    targetProfile = get_object_or_404(UserProfile, user=targetUser)

    update_user_form = UpdateUserForm(
        request.POST if "update_user_profile" in request.POST else None,
        instance=targetUser,
        profile=UserProfile.objects.get(user=request.user),
        prefix="user",
    )
    update_profile_form = FullProfileForm(
        request.POST if "update_user_profile" in request.POST else None, instance=targetProfile, prefix="profile"
    )
    change_user_password_form = AdminPasswordChangeForm(
        targetUser, request.POST if "change_user_password" in request.POST else None
    )
    delete_user_form = DeleteUserForm(
        request.POST if "delete_user" in request.POST else None, user=targetUser, request=request
    )
    if update_user_form.is_valid() and update_profile_form.is_valid():
        update_user_form.save()
        update_profile_form.save()
        messages.add_message(
            request, messages.SUCCESS, MESSAGES["USER_PROFILE_SAVED"].format(username=targetUser.username)
        )
        return HttpResponseRedirect(reverse("custom_modify_user", kwargs={"targetUsername": targetUsername}))
    if change_user_password_form.is_valid():
        change_user_password_form.save()
        messages.add_message(
            request, messages.SUCCESS, MESSAGES["USER_PW_CHANGED"].format(username=targetUser.username)
        )
        return HttpResponseRedirect(reverse("custom_modify_user", kwargs={"targetUsername": targetUsername}))
    if delete_user_form.is_valid():
        delete_user_form.save()
        messages.add_message(request, messages.SUCCESS, MESSAGES["USER_DELETED"].format(username=targetUser.username))
        return HttpResponseRedirect(reverse("custom_manage_users"))

    template_dict = {
        "targetUser": targetUser,
        "targetProfile": targetProfile,
        "page_name": page_name,
        "update_user_form": update_user_form,
        "update_profile_form": update_profile_form,
        "change_user_password_form": change_user_password_form,
        "delete_user_form": delete_user_form,
    }

    if "wiki" in settings.INSTALLED_APPS:
        from wiki.models import Revision

        template_dict["revision_count"] = Revision.objects.filter(created_by=targetUser).count()

    template_dict["thread_count"] = Thread.objects.filter(owner=targetProfile).count()
    template_dict["message_count"] = Message.objects.filter(owner=targetProfile).count()
    template_dict["request_count"] = Request.objects.filter(owner=targetProfile).count()
    template_dict["response_count"] = Response.objects.filter(owner=targetProfile).count()
    template_dict["announcement_count"] = Announcement.objects.filter(incumbent=targetProfile).count()
    template_dict["event_count"] = Event.objects.filter(owner=targetProfile).count()

    return render_to_response("custom_modify_user.html", template_dict, context_instance=RequestContext(request))
Example #58
0
def custom_modify_user_view(request, targetUsername):
    ''' The page to modify a user. '''
    if targetUsername == ANONYMOUS_USERNAME:
        messages.add_message(request, messages.WARNING, MESSAGES['ANONYMOUS_EDIT'])
    page_name = "Admin - Modify User"
    targetUser = get_object_or_404(User, username=targetUsername)
    targetProfile = get_object_or_404(UserProfile, user=targetUser)

    modify_user_form = ModifyUserForm(
        request.POST if "update_user_profile" in request.POST else None,
        user=targetUser,
        request=request,
        )
    change_user_password_form = AdminPasswordChangeForm(
        targetUser,
        request.POST if "change_user_password" in request.POST else None,
        )
    delete_user_form = DeleteUserForm(
        request.POST if "delete_user" in request.POST else None,
        user=targetUser,
        request=request,
        )
    if modify_user_form.is_valid():
        modify_user_form.save()
        messages.add_message(
            request, messages.SUCCESS,
            MESSAGES['USER_PROFILE_SAVED'].format(username=targetUser.username),
            )
        return HttpResponseRedirect(reverse(
            'custom_modify_user', kwargs={'targetUsername': targetUsername}
            ))
    if change_user_password_form.is_valid():
        change_user_password_form.save()
        messages.add_message(
            request, messages.SUCCESS,
            MESSAGES['USER_PW_CHANGED'].format(username=targetUser.username),
            )
        return HttpResponseRedirect(reverse(
            'custom_modify_user', kwargs={'targetUsername': targetUsername})
            )
    if delete_user_form.is_valid():
        delete_user_form.save()
        messages.add_message(
            request, messages.SUCCESS,
            MESSAGES['USER_DELETED'].format(username=targetUser.username),
            )
        return HttpResponseRedirect(reverse("custom_manage_users"))

    return render_to_response('custom_modify_user.html', {
        'targetUser': targetUser,
        'targetProfile': targetProfile,
        'page_name': page_name,
        'modify_user_form': modify_user_form,
        'change_user_password_form': change_user_password_form,
        'delete_user_form': delete_user_form,
        'thread_count': Thread.objects.filter(owner=targetProfile).count(),
        'message_count': Message.objects.filter(owner=targetProfile).count(),
        'request_count': Request.objects.filter(owner=targetProfile).count(),
        'response_count': Response.objects.filter(owner=targetProfile).count(),
        'announcement_count': Announcement.objects.filter(incumbent=targetProfile).count(),
        'event_count': Event.objects.filter(owner=targetProfile).count(),
        }, context_instance=RequestContext(request))