Exemple #1
0
    def validate(self, request=None, add_messages=False):
        valid = True

        if not validator.name(self.name):
            if add_messages:
                messages.error(request, "Du har glemt å skrive inn navnet ditt.")
            valid = False

        if not validator.address(self.address):
            if add_messages:
                messages.error(request, "Du må oppgi din egen adresse da vi sender faktura og medlemskort hjem til deg.")
            valid = False

        if not validator.zipcode(self.zipcode) or self.area == '':
            # Empty area defines invalid zipcode, as stated in __init__
            if add_messages:
                messages.error(request, "Postnummeret ditt ser ikke riktig ut. Du må oppgi et gyldig postnummer da vi sender faktura og medlemskort hjem til deg.")
            valid = False

        if not validator.memberid(self.memberid, req=False):
            if add_messages:
                messages.error(request, "Medlemsnummeret ditt kan kun bestå av tall. Du trenger ikke være medlem for å bestille gavemedlemskap, da kan du la medlemsnummerfeltet stå tomt.")
            valid = False

        if not validator.phone(self.phone, req=False):
            if add_messages:
                messages.error(request, "Telefonnummeret ditt må være minst 8 siffer. Du trenger ikke oppgi telefonnummeret ditt, men vi anbefaler at du gir oss minst én måte å kontakte deg.")
            valid = False

        if not validator.email(self.email, req=False):
            if add_messages:
                messages.error(request, "E-postadressen din er ikke en gyldig adresse. Du trenger ikke oppgi e-postadressen din, men vi anbefaler at du gir oss minst én måte å kontakte deg.")
            valid = False

        return valid
Exemple #2
0
    def is_valid(self, require_contact_info=False):
        # Name or address is empty
        if not validator.name(self.name):
            return False

        # Gender is not set
        if self.gender != 'm' and self.gender != 'f':
            return False

        # Use validator for phone number, require only if required
        if not validator.phone(self.phone, req=require_contact_info):
            return False

        # Use validator for email address, require only if required
        if not validator.email(self.email, req=require_contact_info):
            return False

        # Date of birth is saved as NULL when invalid
        if self.dob is None:
            return False

        # Birthyear is out of smalldatetime range (MSSQLs datetime datatype will barf)
        if self.dob.year < 1900 or self.dob.year > 2078:
            return False

        # Birthdate can't be in the future
        if self.dob > date.today():
            return False

        # All tests passed!
        return True
Exemple #3
0
    def validate(self, request=None, add_messages=False):
        valid = True

        if self.type_index < 0 or self.type_index >= len(membership_types):
            if add_messages:
                messages.error(request, "Du har på en eller annen måte klart å angi en ugyldig medlemskapstype. Vennligst bruk select-boksen til å velge medlemskapstype.")
            valid = False

        if not validator.name(self.name):
            if add_messages:
                if len(self.name) > 0:
                    messages.error(request, "Du må angi fullt navn til %s." % self.name)
                else:
                    messages.error(request, "En av mottakerne mangler navn.")
            valid = False

        if not isinstance(self.dob, datetime):
            if add_messages:
                messages.error(request, "Fødselsdatoen til %s er ugyldig." % self.name)
            valid = False

        if isinstance(self.dob, datetime) and self.dob >= datetime.now():
            if add_messages:
                messages.error(request, "Fødselsdatoen til %s kan ikke være i fremtiden." % self.name)
            valid = False

        if not validator.address(self.address):
            if add_messages:
                messages.error(request, "%s mangler adresse." % self.name)
            valid = False

        if not validator.zipcode(self.zipcode) or self.area == '':
            if add_messages:
                messages.error(request, "Postnummeret til %s er mangler eller er feil." % self.name)
            valid = False

        if not validator.phone(self.phone, req=False):
            if add_messages:
                messages.error(request, "Telefonnummeret til %s må bestå av minst 8 siffer." % self.name)
            valid = False

        if not validator.email(self.email, req=False):
            if add_messages:
                messages.error(request, "E-postadressen til %s er ikke gyldig." % self.name)
            valid = False

        return valid
Exemple #4
0
def upload(request):
    try:
        image_file = request.FILES['file']
    except KeyError:
        raise PermissionDenied

    if not validator.name(request.POST.get('name', '')):
        raise PermissionDenied

    if not validator.phone(request.POST.get('phone', '')):
        raise PermissionDenied

    if not validator.email(request.POST.get('email', '')):
        raise PermissionDenied

    if len(request.POST.get('description', '').strip()) == 0:
        raise PermissionDenied

    post_name = request.POST['name'].strip()
    post_phone = request.POST['phone'].strip()
    post_email = request.POST['email'].strip()
    post_description = request.POST['description'].strip()

    try:
        conn = boto.connect_s3(settings.AWS_ACCESS_KEY_ID, settings.AWS_SECRET_ACCESS_KEY)
        bucket = conn.get_bucket(s3_bucket())

        image_key = Image.generate_unique_random_key()
        data = image_file.read()
        ext = image_file.name.split(".")[-1].lower()
        pil_image = PIL.Image.open(StringIO(data))
        exif_json = json.dumps(get_exif_tags(pil_image))
        image_file_tags = xmp.find_keywords(data)
        thumbs = [{'size': size, 'data': create_thumb(pil_image, ext, size)} for size in settings.THUMB_SIZES]

        if pil_image.size[0] < MIN_SIZE or pil_image.size[1] < MIN_SIZE:
            return HttpResponseBadRequest(json.dumps({
                'files': [{
                    'name': image_file.name,
                    'size': image_file.size,
                    'error': u"Bildet må være minst 800x800 piksler",
                }]
            }))

        # Give boto an encoded str, not unicode
        content_type = image_file.content_type.encode('utf-8')

        key = boto.s3.key.Key(bucket, '%s%s.%s' % (settings.AWS_IMAGEGALLERY_PREFIX, image_key, ext))
        key.content_type = content_type
        key.set_contents_from_string(data, policy='public-read')

        for thumb in thumbs:
            key = boto.s3.key.Key(bucket, '%s%s-%s.%s' % (settings.AWS_IMAGEGALLERY_PREFIX, image_key, thumb['size'], ext))
            key.content_type = content_type
            key.set_contents_from_string(thumb['data'], policy='public-read')

        destination_album = Fotokonkurranse.objects.get().album
        licence_text = "Kan brukes i DNTs egne kommunikasjonskanaler som magasiner, nettsider og sosiale medier, i PR og for bruk av DNTs sponsorer."

        image = Image(
            key=image_key,
            extension=ext,
            hash=sha1(data).hexdigest(),
            description=post_description,
            album=destination_album,
            photographer=post_name,
            credits="%s / DNTs fotokonkurranse" % post_name,
            licence="%s Kontakt: %s (%s / %s)" % (licence_text, post_name, post_phone, post_email),
            exif=exif_json,
            uploader=request.user if not request.user.is_anonymous() else None,
            width=pil_image.size[0],
            height=pil_image.size[1])
        image.save()

        for tag in [tag.lower() for tag in image_file_tags]:
            obj, created = Tag.objects.get_or_create(name=tag)
            image.tags.add(obj)

        # Note that we're caching the email address for one hour and not resending the email receipt
        # for further uploads from that address during this period.
        if cache.get('fotokonkurranse.emails.%s' % post_email) is None:
            # Set the cache quickly when we know we're going to send an email. Don't wait until after
            # it's sent, because other upload requests may try to send meanwhile and we don't want them to.
            cache.set('fotokonkurranse.emails.%s' % post_email, True, 60 * 60)
            try:
                t = loader.get_template('central/fotokonkurranse/email_confirmation.txt')
                c = RequestContext(request, {
                    'user_name': post_name,
                })
                send_mail(EMAIL_CONFIRMATION_SUBJECT, t.render(c), settings.DEFAULT_FROM_EMAIL, [post_email])
            except (SMTPException, SSLError):
                cache.delete('fotokonkurranse.emails.%s' % post_email)
                logger.warning(u"Kvitteringsepost for fotokonkurranse feilet",
                    exc_info=sys.exc_info(),
                    extra={'request': request}
                )

        return HttpResponse(json.dumps({
            'files': [{
                'name': image_file.name,
                'size': image_file.size,
                'url': '',
                'thumbnailUrl': '',
                'deleteUrl': '',
                'deleteType': '',
            }]
        }))
    except Exception as e:
        logger.error(u"Feil ved opplasting av bilde til fotokonkurranse",
            exc_info=sys.exc_info(),
            extra={'request': request}
        )
        return HttpResponseBadRequest(json.dumps({
            'files': [{
                'name': image_file.name,
                'size': image_file.size,
                'error': "Exception ved bildeopplasting: %s" % e,
            }]
        }))
Exemple #5
0
def update_account(request):
    if not request.user.is_member():
        if request.method == 'GET':
            context = {
                'user_password_length': settings.USER_PASSWORD_LENGTH
            }
            return render(request, 'common/user/account/update_account_nonmember.html', context)

        elif request.method == 'POST':
            if not Settings.get_cached().focus_writes:
                return redirect('user:account')

            errors = False

            if not validator.email(request.POST['email']):
                messages.error(request, 'invalid_email_address')
                errors = True

            if request.user.has_perm('sherpa') and 'sherpa-email' in request.POST and not validator.email(request.POST['sherpa-email'], req=False):
                messages.error(request, 'invalid_sherpa_email_address')
                errors = True

            if User.objects.filter(identifier=request.POST['email']).exclude(id=request.user.id).exists():
                messages.error(request, 'duplicate_email_address')
                errors = True

            if errors:
                return redirect('user:update_account')

            if request.user.has_perm('sherpa') and 'sherpa-email' in request.POST:
                user = request.user
                user.sherpa_email = request.POST['sherpa-email']
                user.save()

            if 'phone_mobile' in request.POST:
                request.user.phone_mobile = request.POST['phone_mobile']

            if all([key in request.POST for key in ['b_day', 'b_month', 'b_year']]):
                try:
                    request.user.birth_date = datetime.strptime(
                        "%s-%s-%s" % (request.POST['b_year'], request.POST['b_month'], request.POST['b_day']),
                        "%Y-%m-%d",
                    ).date()
                except ValueError:
                    request.user.birth_date = None

            request.user.identifier = request.POST['email']
            request.user.email = request.POST['email']
            request.user.save()
            messages.info(request, 'update_success')
            return redirect('user:account')
    else:
        if request.method == 'GET':
            context = {
                'address_field_max_length': ADDRESS_FIELD_MAX_LENGTH,
                'settings': Settings.get_cached(),
            }
            return render(request, 'common/user/account/update_account.html', context)

        elif request.method == 'POST':
            errors = False

            if not validator.email(request.POST['email']):
                messages.error(request, 'invalid_email_address')
                errors = True

            if request.user.has_perm('sherpa') and 'sherpa-email' in request.POST and not validator.email(request.POST['sherpa-email'], req=False):
                messages.error(request, 'invalid_sherpa_email_address')
                errors = True

            if not validator.phone(request.POST['phone_home'], req=False):
                messages.error(request, 'invalid_phone_home')
                errors = True

            if not validator.phone(request.POST['phone_mobile'], req=False):
                messages.error(request, 'invalid_phone_mobile')
                errors = True

            if request.user.address.country.code == 'NO' and not request.user.is_related_member():
                if not validator.address(request.POST['address']):
                    messages.error(request, 'invalid_address')
                    errors = True

                if len(request.POST['address']) >= ADDRESS_FIELD_MAX_LENGTH:
                    messages.error(request, 'too_long_address')
                    errors = True

                try:
                    zipcode = Zipcode.get_by_zipcode(zipcode=request.POST['zipcode'])
                except Zipcode.DoesNotExist:
                    messages.error(request, 'invalid_zipcode')
                    errors = True

            if errors:
                return redirect('user:update_account')

            if request.user.has_perm('sherpa') and 'sherpa-email' in request.POST:
                user = request.user
                user.sherpa_email = request.POST['sherpa-email']
                user.save()

            attributes = {
                'email': request.POST['email'],
                'phone_home': request.POST['phone_home'],
                'phone_mobile': request.POST['phone_mobile']
            }
            address_attributes = None
            if request.user.address.country.code == 'NO' and not request.user.is_related_member():
                address_attributes = {}
                address_attributes['a1'] = request.POST['address']
                if 'address2' in request.POST:
                    address_attributes['a2'] = request.POST['address2']
                if 'address3' in request.POST:
                    address_attributes['a3'] = request.POST['address3']
                address_attributes['zipcode_id'] = zipcode.zipcode
                address_attributes['area'] = zipcode.area
            request.user.set_contact_info(attributes, address_attributes, update_changedby=True)

            messages.info(request, 'update_success')
            return redirect('user:account')
Exemple #6
0
def update_account(request):
    if not request.user.is_member():
        if request.method == 'GET':
            context = {
                'user_password_length': settings.USER_PASSWORD_LENGTH
            }
            return render(request, 'common/user/account/update_account_nonmember.html', context)

        elif request.method == 'POST':
            errors = False

            if not validator.email(request.POST['email']):
                messages.error(request, 'invalid_email_address')
                errors = True

            if request.user.has_perm('sherpa') and 'sherpa-email' in request.POST and not validator.email(request.POST['sherpa-email'], req=False):
                messages.error(request, 'invalid_sherpa_email_address')
                errors = True

            if User.objects.filter(identifier=request.POST['email']).exclude(id=request.user.id).exists():
                messages.error(request, 'duplicate_email_address')
                errors = True

            if errors:
                return redirect('user.views.update_account')

            if request.user.has_perm('sherpa') and 'sherpa-email' in request.POST:
                user = request.user
                user.sherpa_email = request.POST['sherpa-email']
                user.save()

            request.user.identifier = request.POST['email']
            request.user.email = request.POST['email']
            request.user.save()
            messages.info(request, 'update_success')
            return redirect('user.views.account')
    else:
        if request.method == 'GET':
            context = {
                'address_field_max_length': ADDRESS_FIELD_MAX_LENGTH
            }
            return render(request, 'common/user/account/update_account.html', context)

        elif request.method == 'POST':
            errors = False

            if not validator.email(request.POST['email']):
                messages.error(request, 'invalid_email_address')
                errors = True

            if request.user.has_perm('sherpa') and 'sherpa-email' in request.POST and not validator.email(request.POST['sherpa-email'], req=False):
                messages.error(request, 'invalid_sherpa_email_address')
                errors = True

            if not validator.phone(request.POST['phone_home'], req=False):
                messages.error(request, 'invalid_phone_home')
                errors = True

            if not validator.phone(request.POST['phone_mobile'], req=False):
                messages.error(request, 'invalid_phone_mobile')
                errors = True

            if request.user.get_address().country.code == 'NO' and not request.user.is_household_member():
                if not validator.address(request.POST['address']):
                    messages.error(request, 'invalid_address')
                    errors = True

                if len(request.POST['address']) >= ADDRESS_FIELD_MAX_LENGTH:
                    messages.error(request, 'too_long_address')
                    errors = True

                try:
                    zipcode = Zipcode.objects.get(zipcode=request.POST['zipcode'])
                except Zipcode.DoesNotExist:
                    messages.error(request, 'invalid_zipcode')
                    errors = True

            if errors:
                return redirect('user.views.update_account')

            if request.user.has_perm('sherpa') and 'sherpa-email' in request.POST:
                user = request.user
                user.sherpa_email = request.POST['sherpa-email']
                user.save()

            attributes = {
                'email': request.POST['email'],
                'phone_home': request.POST['phone_home'],
                'phone_mobile': request.POST['phone_mobile']
            }
            address_attributes = None
            if request.user.get_address().country.code == 'NO' and not request.user.is_household_member():
                address_attributes = {}
                address_attributes['a1'] = request.POST['address']
                if 'address2' in request.POST:
                    address_attributes['a2'] = request.POST['address2']
                if 'address3' in request.POST:
                    address_attributes['a3'] = request.POST['address3']
                address_attributes['zipcode'] = zipcode.zipcode
                address_attributes['area'] = zipcode.area
            request.user.update_personal_data(attributes, address_attributes, update_changedby=True)

            messages.info(request, 'update_success')
            return redirect('user.views.account')