예제 #1
0
def update_password(request):
    """
    url = administrator/updatePassword/

    parameters:
        currentpass: contraseña actual
        newpass1: contraseña a establecer
        newpass2: repetición de la contraseña

    returns:
        {'success': true/false: 'errors': [...]}

    errors:
        'formNotValid': si el formulario no es válido
        'passwordsDontMatch' : si las contraseñas no coinciden
        'currentPasswordInvalid" : si la contraseña actual no escorrecta

    template: ninguna (ajax)
    """

    # Check that the user is logged in and it's an administrator
    admin = get_current_admin_or_403(request)

    if request.method == 'POST':
        # Process the form
        form = EmployeePasswordForm(request.POST)

        if form.is_valid():

            if not admin.user.check_password(form.cleaned_data["currentpass"]):
                return JsonResponse({
                    'success': False,
                    'errors': ['currentPasswordInvalid']
                })
            #Check password validation
            if not validate_pass(form.cleaned_data["newpass1"]):
                return JsonResponse({
                    'success': False,
                    'errors': ['newPasswordInvalid']
                })

            pass1 = form.cleaned_data["newpass1"]
            pass2 = form.cleaned_data["newpass2"]

            if pass1 != pass2:
                return JsonResponse({
                    'success': False,
                    'errors': ['passwordsDontMatch']
                })

            user = admin.user
            user.set_password(pass1)
            user.save()
            update_session_auth_hash(request, user)

            return JsonResponse({'success': True, 'errors': []})
        else:
            # Invalid form
            return JsonResponse({'success': False, 'errors': ['formNotValid']})
예제 #2
0
def update_password(request, username):
    """
    url = employee/updatePassword/<username>

    parameters:
        password1: contraseña a establecer
        password2: repetición de la contraseña

    returns:
        {'success': true/false: 'errors': [...]}

    errors:
        'employeeCreation_formNotValid': si el formulario no es válido
        'employeeCreation_passwordsDontMatch' : si las contraseñas no coinciden

    template: ninguna (ajax)
    """

    # Check that the user is logged in and it's an administrator
    admin = get_admin_executive_or_403(request)
    employee = get_object_or_404(Employee,
                                 user__username=username,
                                 user__is_active=True)

    # Check that the admin has permission to view that employee
    same_company_or_403(admin, employee)

    if request.method == 'POST':
        # Process the form
        form = EmployeePasswordForm(request.POST)

        if form.is_valid():
            pass1 = form.cleaned_data["newpass1"]
            pass2 = form.cleaned_data["newpass2"]

            # Check password validation
            if not validate_pass(pass1):
                return JsonResponse({
                    'success': False,
                    'errors': ['newPasswordInvalid']
                })

            if pass1 != pass2:
                return JsonResponse({
                    'success':
                    False,
                    'errors': ['employeeCreation_passwordsDontMatch']
                })

            user = employee.user
            user.set_password(pass1)
            user.save()

            if form.cleaned_data["send_password_notification"]:
                notify_password_change(
                    user.email,
                    user.first_name,
                    newpass=pass1,
                    notifynewpass=form.cleaned_data["notify_new_pass"])

            return JsonResponse({'success': True, 'errors': []})
        else:
            # Invalid form
            return JsonResponse({
                'success': False,
                'errors': ['employeeCreation_formNotValid']
            })
    else:
        # Invalid HTTP operation
        raise SuspiciousOperation
예제 #3
0
def create(request):
    """
    parameters:
        redirect: opcional, incluir en la URL de la petición si se quiere redirigir a la página del empleado creado
    returns:
        form: formulario con los datos necesarios para el registro del empleado
        success: opcional, si se ha tenido éxito al crear un empleado
        errors: opcional, array de mensajes de error si ha habido algún error

    errores: (todos empiezan por employeeCreation_)
        passwordsDontMatch: las contraseñas no coinciden
        usernameNotUnique: el nombre de usuario ya existe
        imageNotValid: la imagen no es válida por formato y/o tamaño
        formNotValid: el formulario contiene errores
        priceNotValid: el precio debe ser mayor que 0
        emailNotUnique:si el correo no es úinco

    template:
        employee_register.html
    """

    # Check that the user is logged in and it's an administrator
    admin = get_admin_executive_or_403(request)

    # If it's a GET request, return an empty form
    if request.method == "GET":
        return render(request, 'employee/employee_register.html',
                      {'form': EmployeeRegisterForm()})

    elif request.method == "POST":
        # We are serving a POST request
        form = EmployeeRegisterForm(request.POST, request.FILES)

        if form.is_valid():

            errors = []

            # Check that the passwords match
            if not check_passwords(form):
                errors.append('employeeCreation_passwordsDontMatch')

            #Check password validation
            if not validate_pass(form.cleaned_data["password1"]):
                errors.append('newPasswordInvalid')

            # Check that the username is unique
            if not is_username_unique(form.cleaned_data["username"]):
                errors.append('employeeCreation_usernameNotUnique')

            # Check that the email is unique
            if not is_email_unique(form.cleaned_data["email"]):
                errors.append('employeeCreation_emailNotUnique')

            # Check that the image is OK
            if not check_image(form, 'photo'):
                errors.append('employeeCreation_imageNotValid')

            # Check that the price is OK
            if form.cleaned_data['price_per_hour'] <= 0:
                errors.append('employeeCreation_priceNotValid')

            if not errors:
                # Everything is OK, create the employee
                employee_user = create_employee_user(form)
                employee = create_employee(employee_user, admin, form)
                EmployeeLog.objects.create(
                    employee_id=employee,
                    event="A",
                    price_per_hour=employee.price_per_hour)
                send_register_email(form.cleaned_data["email"],
                                    form.cleaned_data["first_name"])

                return HttpResponseRedirect('/employee/view/' +
                                            form.cleaned_data["username"] +
                                            '/')

            else:
                # There are errors
                return render(request, 'employee/employee_register.html', {
                    'form': form,
                    'errors': errors
                })

        # Form is not valid
        else:
            return render(request, 'employee/employee_register.html', {
                'form': form,
                'errors': ['employeeCreation_formNotValid']
            })
    else:
        # Another request method
        raise PermissionDenied
예제 #4
0
def create(request,
           email_template_name='company/company_register_email.html',
           html_email_template_name='company/company_register_email.html'):
    """
    parameters/returns:
    form: el formulario con los datos de la compañía y el administrador de la compañía

    template:
    company_form.html
    """
    # If it's a GET request, return an empty form
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = RegistrationForm(request.POST, request.FILES)
        # check whether it's valid:
        if form.is_valid():
            errors = []

            # Check that the passwords match
            if not check_passwords(form):
                errors.append('passwordsDontMatch')

            # Check that the username is unique
            if not is_username_unique(form.cleaned_data["username"]):
                errors.append('companyRegister_usernameNotUnique')

            #Check password validation
            if not validate_pass(form.cleaned_data["password"]):
                errors.append('newPasswordInvalid')

            # Check that the admin email is unique
            if Company.objects.filter(
                    email=form.cleaned_data["company_email"]).exists():
                errors.append('companyRegister_companyEmailNotUnique')

            # Check that the admin email is unique
            if not is_email_unique(form.cleaned_data["admin_email"]):
                errors.append('companyRegister_adminEmailNotUnique')

            # Check that the CIF is unique
            if not is_cif_unique(form.cleaned_data["cif"]):
                errors.append('companyRegister_cifNotUnique')

            # Check that the short name is unique
            if get_or_none(Company,
                           short_name=form.cleaned_data["short_name"]):
                errors.append('company_short_name_duplicate')

            # Check that the image is OK
            if not check_image(form, 'logo'):
                errors.append('company_imageNotValid')

            if not form.cleaned_data["terms_agree"]:
                errors.append("agree_terms_error")

            if not errors:
                # process the data in form.cleaned_data as required
                # ...
                # redirect to a new URL:
                company = create_company(form)
                administrator = register_administrator(form, company)

                # This sends an information email to the company and to the admin

                current_site = get_current_site(request)
                site_name = current_site.name
                domain = current_site.domain

                use_https = True
                context = {
                    'domain': domain,
                    'site_name': site_name,
                    'admin': administrator,
                    'company': company.short_name,
                    'protocol': 'https' if use_https else 'http',
                    'html': True
                }

                send_mail('Metronus Info.', email_template_name,
                          [company.email, administrator.user.email],
                          html_email_template_name, context)

                # Login the administrator and send him to the dashboard
                logged_user = authenticate(
                    username=form.cleaned_data['username'],
                    password=form.cleaned_data['password'])
                login(request, logged_user)
                return HttpResponseRedirect("/dashboard/view")
            else:
                return render(request, 'company/company_register.html', {
                    'form': form,
                    'errors': errors
                })

    # if a GET (or any other method) we'll create a blank form
    else:
        form = RegistrationForm()
    return render(request, 'company/company_register.html', {'form': form})