Exemplo n.º 1
0
    def handle_noargs(self, **options):
        tmp = UserProfile.objects.values('user').filter(send_report=1)
        ids = [profile['user'] for profile in tmp]
        users = User.objects.filter(id__in=ids)
        url = getattr(settings, 'QUARANTINE_REPORT_HOSTURL', '')
        a_day = datetime.timedelta(days=1)
        yesterday = datetime.date.today() - a_day
        from_email = getattr(settings, 'DEFAULT_FROM_EMAIL',
                            'postmaster@localhost')
        logo_path = getattr(settings, 'MEDIA_ROOT', '') + '/imgs/css/logo.jpg'
        logo = open(logo_path, 'rb').read()
        print _("=== Processing quarantine notifications ===")
        for user in users:
            if email_re.match(user.email) or email_re.match(user.username):
                spam_list = Message.quarantine_report.for_user(user).values(
                    'id', 'timestamp', 'from_address', 'to_address', 'subject'
                ).exclude(timestamp__lt=yesterday).exclude(
                spam=0).order_by('sascore')[:25]
                policy_list = Message.quarantine_report.for_user(user).values(
                    'id', 'timestamp', 'from_address', 'to_address', 'subject'
                ).exclude(timestamp__lt=yesterday).exclude(Q(spam=1) |
                Q(nameinfected=0) | Q(otherinfected=0) | Q(virusinfected=0)
                ).order_by('sascore')[:25]
                subject = _('Baruwa quarantine report for %(user)s') % {
                            'user': user.username}

                if email_re.match(user.username):
                    to_addr = user.username
                if email_re.match(user.email):
                    to_addr = user.email

                if spam_list or policy_list:
                    for query_list in [spam_list, policy_list]:
                        add_uuids(query_list)

                    html_content = render_to_string(
                        'messages/quarantine_report.html',
                        {'spam_items': spam_list, 'policy_items': policy_list,
                        'host_url': url})
                    text_content = render_to_string(
                        'messages/quarantine_report_text.html',
                        {'spam_items': spam_list, 'policy_items': policy_list,
                        'host_url': url})

                    msg = EmailMultiAlternatives(subject, text_content,
                        from_email, [to_addr])
                    embed_img(msg, 'baruwalogo', logo)
                    msg.attach_alternative(html_content, "text/html")
                    try:
                        msg.send()
                        for query_list in [spam_list, policy_list]:
                            generate_release_records(query_list)

                        print _("sent quarantine report to %(addr)s") % {'addr': to_addr}
                    except SMTPException:
                        print _("failed to send to: %(addr)s") % {'addr': to_addr}
                else:
                    print _("skipping report to %(addr)s no messages") % {'addr': to_addr}
        print _("=== completed quarantine notifications ===")
Exemplo n.º 2
0
    def clean(self):
        cleaned_data = self.cleaned_data
        field_function = cleaned_data.get("field_function")
        choices = cleaned_data.get("choices")
        field_type = cleaned_data.get("field_type")
        required = cleaned_data.get("required")

        if field_function == "GroupSubscription":
            if field_type != "BooleanField":
                raise forms.ValidationError(_("This field's function requires Checkbox as a field type"))
            if not choices:
                raise forms.ValidationError(_("This field's function requires at least 1 group specified."))
            else:
                for val in choices.split(','):
                    try:
                        Group.objects.get(name=val.strip())
                    except Group.DoesNotExist:
                        raise forms.ValidationError(_("The group \"%(val)s\" does not exist" % { 'val' : val }))

        if field_function == "Recipients":
            if (field_type != "MultipleChoiceField/django.forms.CheckboxSelectMultiple" and
                field_type != "MultipleChoiceField" and
                field_type != "BooleanField" and
                field_type != "ChoiceField"):
                raise forms.ValidationError(_("The \"Email to Recipients\" function requires Multi-select - Checkboxes "
                                            + "or Multi-select - Select Many as field type"))

            if field_type == "BooleanField":
                if not choices:
                    raise forms.ValidationError(_("The \"Email to Recipients\" function requires at least 1 email specified."))
                else:
                    for val in choices.split(','):
                        if not email_re.match(val.strip()):
                            raise forms.ValidationError(_("\"%(val)s\" is not a valid email address" % {'val':val}))
            else:
                if not choices:
                    raise forms.ValidationError(_("The \"Email to Recipients\" function requires at least 1 choice specified."))
                else:
                    for val in choices.split(','):
                        val = val.split(':')
                        if len(val) < 2:
                            raise forms.ValidationError(_("The \"Email to Recipients\" function requires choices to be in the following format: <choice_label>:<email_address>."))
                        if not email_re.match(val[1].strip()):
                            raise forms.ValidationError(_("\"%(val)s\" is not a valid email address" % {'val':val[1]}))

        if field_function != None and field_function.startswith("Email"):
            if field_type != "CharField":
                raise forms.ValidationError(_("This field's function requires Text as a field type"))

        #unrequire the display only fields
        if field_type == "CharField/tendenci.apps.forms_builder.forms.widgets.Description":
            cleaned_data['required'] = False
        elif field_type == "CharField/tendenci.apps.forms_builder.forms.widgets.Header":
            cleaned_data['required'] = False

        return cleaned_data
Exemplo n.º 3
0
def create_mri_action(request):
    name = request.POST['name']
    email = request.POST['email']
    address = request.POST['address']
    address2 = request.POST['address2']
    state = request.POST['state']
    city = request.POST['city']
    
    try:
        phone = long(request.POST['phone'])
        zip = int(request.POST['zip'])    
    except:
        messages.error(request, 'Phone and zipcode must be numbers')
        return redirect('main.views.quantmd.create_mri_view') 
    
    if (not name.strip() or not email.strip() or not address.strip() or not city.strip() or not state.strip()): 
        messages.error(request, 'Only address line 2 can be empty.')
        return redirect('main.views.quantmd.create_mri_view')
    
    if not email_re.match(email):
        messages.error(request, 'Email format not correct.')
        return redirect('main.views.quantmd.create_mri_view')

    if MRICenter.objects.filter(name=name).exists():
        messages.error('There is a same name MRI center in quantmd')
        return redirect('main.views.quantmd.create_mri_view')
    
    city = city.upper()
    mri = MRICenter.objects.create(name=name,address=address,phone=phone,email=email,state=state,city=city,zip=zip)
    if len(address2) != 0:
        mri.address2 =address2
        
    mri.save()
    return render_to_response('quantmd/mri-create-confirm.htm',{'mri':mri}, context_instance=RequestContext(request))
Exemplo n.º 4
0
 def clean_send_to(self):
     value = self.cleaned_data["send_to"]
     emails = filter(bool, split_re.split(value))
     for email in emails:
         if not email_re.match(email):
             raise ValidationError("%s is not a valid e-mail address." % (email,))
     return ",".join(emails)
Exemplo n.º 5
0
 def save(self, *args, **kwargs):
     if self.nombre == u'':
         self.nombre = "(Anonymous)"
     if self.correo:
         if not email_re.match(self.correo):
             raise ValidationError(u'%s no es una dirección de correo válida' % self.correo)
     super(User, self).save(*args, **kwargs)
Exemplo n.º 6
0
def subscribe(request):
    # get and validate email
    email = request.POST.get('email', '')
    if not email or not email_re.match(email):
        error = u'Please, enter valid email address.'
        return render_to_response('index.html', {'error': error},
            context_instance=RequestContext(request))

    # get subscribers list and try to add new subscriber
    try:
        elist = mailchimp.utils.get_connection().get_list_by_id(
            MAILCHIMP_LIST_ID)
    except Exception:
        error = u'Sorry, there are some issues on the server. Please, try ' \
            'again  a bit later'
        return render_to_response('index.html', {'error': error},
            context_instance=RequestContext(request))
    
    # finally try to subscribe
    try:
        elist.subscribe(email, {'EMAIL': email})
    except Exception, e:
        # check if already subscribed
        if u'is already subscribed' in e.message:
            error = u'You are already subscribed to our newsletter.'
        elif u'Invalid Email Address' in e.message:
            error = u'Please, enter valid email address.'
        else:
            error = u'Sorry, there are some issues on the server. Please, ' \
                'try again  a bit later'
        return render_to_response('index.html', {'error': error},
            context_instance=RequestContext(request))
Exemplo n.º 7
0
Arquivo: api.py Projeto: jart/sparkles
def verify_email(email, **kwargs):
    ip = _try_to_get_ip(kwargs)
    yesterday = utils.now() - timedelta(days=1)
    five = utils.now() - timedelta(seconds=5)
    if db.EmailVerify.objects.filter(email=email, created__gt=five).count():
        return []
    invalid = False
    invalid |= not email_re.match(email)
    invalid |= db.User.objects.filter(email=email).count() > 0
    invalid |= db.EmailBlacklist.objects.filter(email=email).count() > 0
    invalid |= (
        db.EmailVerify.objects.filter(email=email, created__gt=yesterday).count() > settings.SPARK_AUTH_MAX_EMAIL_DAY
    )
    if ip:
        invalid |= (
            db.EmailVerify.objects.filter(ip=ip, created__gt=yesterday).count() > settings.SPARK_AUTH_MAX_EMAIL_DAY
        )
    if invalid:
        raise utils.APIException("invalid email address")
    code = db.base36(4)
    db.EmailVerify.objects.create(email=email, code=code, ip=ip)
    body = render_to_string("sparkles/email_verify.html", {"code": code})
    msg = mail.EmailMessage("Sparkles Email Verification Code", body, "*****@*****.**", [email])
    msg.content_subtype = "html"
    msg.send()
    return []
Exemplo n.º 8
0
    def clean(self):
        cleaned_data = super(UserEditForm, self).clean()
        current_password = cleaned_data.get("current_password")
        new_password = cleaned_data.get("new_password")
        new_password_check = cleaned_data.get("new_password_check")
        new_email = cleaned_data.get("new_email")
        location = cleaned_data.get("location")
        
        if not current_password:
            raise forms.ValidationError(
                'You must enter your current password to make any changes.')
        if not self.user.check_password(current_password):
            raise forms.ValidationError('That password was incorrect.')

        if new_password and new_password_check:
            if len(new_password) < 5:
                raise forms.ValidationError(
                    'Your new password must be at least 5 characters.')
            if new_password != new_password_check:
                raise forms.ValidationError('Your new passwords do not match.')

        elif new_email:
            if not email_re.match(new_email):
                raise forms.ValidationError('Not a valid email address')

        elif location == 'empty':
            raise forms.ValidationError(
                'You have not changed any information.')

        return cleaned_data
Exemplo n.º 9
0
def register(request):
    username = request.POST['username']
    password = request.POST['password']
    email = request.POST['email']
    # Check to make sure stuffs is valid
    errors = {}
    if email:
        if not email_re.match(email):
            errors['email'] = "Invalid email format."
        else:
            try:
                User.objects.get(email=email)
                errors['email'] = "Email is already taken."
            except User.DoesNotExist:
                pass

    if not username:
        errors['username'] = "******"
    else:
        try:
            User.objects.get(username=username)
            errors['username'] = "******"
        except User.DoesNotExist:
            pass

    if not password:
        errors['password'] = "******"

    if errors:
        return HttpResponse(json.simplejson.dumps(errors), mimetype="application/json")
    User.objects.create_user(username, email, password)
    return login_user(request)
Exemplo n.º 10
0
def send_email(request):
	if not request.method == "POST":
		raise Http404

	p = request.POST
	try:
		name = p.get('_name','')
		email = p.get('_email','')
		s = p.get('_subject','')
		m = p.get('_message','')
	except:
		return render_to_response('ajaxresponse.html',{'data':json.dumps( { 'status': { 'no':2 } } ) })


	if (not name) or (not s) or (not m):
		return render_to_response('ajaxresponse.html',{'data':json.dumps( { 'status': { 'no':2 } } ) })
	elif not email_re.match(email):
		return render_to_response('ajaxresponse.html',{'data':json.dumps( { 'status': { 'no':2} } ) })


	try:
		send_mail(s,m,email,['*****@*****.**'])
	except BadHeaderError:
		return render_to_response('ajaxresponse.html',{'data':json.dumps( { 'status': { 'no':2} } ) })
	

	return render_to_response('ajaxresponse.html',{'data':json.dumps( { 'status': { 'no':1} } ) })
Exemplo n.º 11
0
def ajax_change(request):
    resp = {
        "success": False,
    }
    if('old_pass' in request.POST and 'new_pass' in request.POST):
        #got a change for pass
        #check to make sure old_pass matches
        user = authenticate(username=request.user.username, password=request.POST['old_pass'])
        if(user is not None and user.is_active):
            #old pass matches, change pass to new one
            if len(request.POST['new_pass']) < MIN_PASS_LENGTH or len(request.POST['new_pass']) > MAX_PASS_LENGTH:
                resp['error'] = 'Passwords must be 8-30 characters'
            else:
                user.set_password(request.POST['new_pass'])
                user.save()
                resp['success'] = True
        else:
            #old pass didn't match, pass back an error
            resp['error'] = 'The password is incorrect. Did you forget it?'
    elif('email' in request.POST):
        #got a change for email
        if not email_re.match(request.POST['email']):
            resp['error'] = 'Please enter a valid email'
        else:
            request.user.email = request.POST['email']
            request.user.save()
            resp['success'] = True
    else:
        resp['error'] = 'Please fill out all the fields. They are all necessary'

    return HttpResponse(json.dumps(resp), mimetype="application/json")
Exemplo n.º 12
0
def handle_login(request, data):
    """
    Login for user
    """
    user_id = data.get('username', None)
    if user_id:
        user_id = user_id.replace(' ', '')

    if email_re.match(user_id):
        try:
            target_user = User.objects.get(email__iexact = user_id)
        except ObjectDoesNotExist:
            target_user = None
    else:
        try:
            target_user = User.objects.get(username__iexact = user_id)
        except ObjectDoesNotExist:
            target_user = None
    
    if target_user:
        user = authenticate(username = target_user.username,
                                password = data.get('password', None))
        user_object = target_user
    else:
        user = None
        
    if user is not None:
        login(request, user)
    return user
Exemplo n.º 13
0
Arquivo: main.py Projeto: Hajfajf/Same
 def post(self):
     session = sessions.Session()
     owner = Owner()
     project = Project()
     owner.first_name = str(self.request.get("first_name"))
     owner.last_name = str(self.request.get("last_name"))
     owner.company = str(self.request.get("company"))
     owner.department = str(self.request.get("department"))
     owner.project = str(self.request.get("project"))
     if email_re.match(self.request.get("email")):
         owner.email = self.request.get("email")
     else:
         print("Email format is not valid")  # Replace by sentence below the input to allow edition
     owner.put()
     project.name = str(self.request.get("project"))
     project.company = str(self.request.get("company"))
     project.department = str(self.request.get("department"))
     project.owner_name = str(self.request.get("first_name")) + " " + str(self.request.get("last_name"))
     project.owner_email = self.request.get("email")
     project.owner_key = str(owner.key())
     project.put()
     owner.project_key = str(project.key())
     owner.put()
     session["ProjectID"] = project.key()  # sets keyname to value
     self.redirect("/setup-team")
Exemplo n.º 14
0
def is_valid_email(email):
    '''
    check is the email valid
    '''
    if email_re.match(email):
        return True
    return False
Exemplo n.º 15
0
    def handle(self, *args, **options):
        """Read emails from text file and create accounts. If
        options['email'] is set then send out emails to invited users.

        """
        if len(args) != 1:
            LOGGER.error('Please provide a file with emails.')
            sys.exit(-1)

        with open(args[0], 'r') as input_file:
            for email in input_file:
                email = email.strip()

                if not email_re.match(email):
                    LOGGER.warning('Ignoring not valid email: "%s"' % email)
                    continue

                user, created = User.objects.get_or_create(
                    username=USERNAME_ALGO(email),
                    email=email)

                if not created:
                    LOGGER.warning('User "%s" already exists' % email)
                    continue

                # Send invitation email if option is True. Default (yes)
                if options['email']:
                    send_mail(self.SUBJECT, self.MESSAGE,
                              self.FROM_EMAIL, [email])
Exemplo n.º 16
0
def sanitize(first, last, email, bio, password):

    result = [True, True, True, True, True]
    
    for c in first:
        if (c not in string.ascii_letters + '-') and (c.isspace() is False):
            result[0] = False
            print "invalid first name"
            break
    if len(first) == 0:
        result[0] = False
    for c in last:
        if (c not in string.ascii_letters + '-') and (c.isspace() is False):
            result[1] = False
            print "invalid last name"
            break
    if len(last) == 0:
        result[1] = False
    if len(bio) > 500:
        result[3] = False
        print "invalid bio"
    if len(password) == 0:
        result[4] == False
    if email_re.match(email):
       return result
    else:
       result[2] = False
       print "invalid email"
       return result
Exemplo n.º 17
0
def settings(request):
    if request.user.is_authenticated():
        settings = UserProfile.objects.get(user_id=request.user.id)
        user = User.objects.get(pk=request.user.id)
        if request.method == "POST":  # If the form has been submitted...
            if request.POST.get("full_name", ""):
                settings.full_name = request.POST["full_name"]
                settings.save()
            elif request.POST.get("position", ""):
                settings.staff_position = request.POST["position"]
                settings.save()
            elif request.POST.get("bio", ""):
                settings.bio = request.POST["bio"]
                settings.save()
            elif request.POST.get("receive_notifications", ""):
                settings.receive_notifications = request.POST["receive_notifications"]
                settings.save()
            elif request.POST.get("notification_email", ""):
                if email_re.match(request.POST["notification_email"]):
                    settings.notification_email = request.POST["notification_email"]
                    settings.save()
                else:
                    error = "Please enter a valid email address."
                    return HttpResponse(json.dumps(error))

            return django.http.HttpResponseRedirect("/settings/")  # Redirect after POST

        return render(
            request, "tail/settings/index.html", {"settings": settings}, context_instance=RequestContext(request)
        )
    else:
        return HttpResponseRedirect("/")
Exemplo n.º 18
0
 def clean_send_to(self):
     value = self.cleaned_data['send_to']
     emails = filter(bool, split_re.split(value))
     for email in emails:
         if not email_re.match(email):
             raise ValidationError('%s is not a valid e-mail address.' % email)
     return ','.join(emails)
Exemplo n.º 19
0
def is_valid_email(email):
    """ 
    Is the string a valid email? 
    
    (We use the regex Django uses to define an email address)
    """
    return True if email_re.match(email) else False
Exemplo n.º 20
0
	def clean_username_or_email(self):
		field = self.cleaned_data['username_or_email']
		
		if not re.match(r'^[\w]+$', field) and not email_re.match(field):
			raise forms.ValidationError('That doesn\'t appear to be a username or an email address')
		
		return field
Exemplo n.º 21
0
Arquivo: views.py Projeto: braskin/pd
def save_email_list(request):
    if request.method == 'POST':
        post = request.POST
        emails = post.get('emails', None)

        if emails is None:
            raise Exception('no email list passed in')

        email_list_unstripped = emails.split(',')
        email_list = []
        bad_emails = []
        for email in email_list_unstripped:
            if email_re.match(email.strip()):
                email_list.append(email.strip())
            else:
                bad_emails.append(email)

        response_dict = {}
        if not bad_emails:
            request.session["email_list"] = email_list
            response_dict = { "success":True, "message": "Done" }
        else:
            response_dict = { "success":False, "message": "Invalid emails found", "bad_emails":bad_emails }
    
        return HttpResponse(simplejson.dumps(response_dict, cls=PDEncoder), mimetype='application/javascript')
Exemplo n.º 22
0
    def clean(self):
        """
        Validates the quarantine form
        """
        cleaned_data = self.cleaned_data
        use_alt = cleaned_data.get("use_alt")
        altrecipients = cleaned_data.get("altrecipients")
        learn = cleaned_data.get("learn")
        release = cleaned_data.get("release")
        todelete = cleaned_data.get("todelete")

        if not learn and not release and not todelete:
            raise forms.ValidationError(_("Select atleast one action to perform"))
        else:
            if altrecipients in EMPTY_VALUES and use_alt and release:
                raise forms.ValidationError(
                    _("Provide atleast one alternative recipient"))
            else:
                if use_alt and release:
                    emails = altrecipients.split(',')
                    for email in emails:
                        if not email_re.match(email.strip()):
                            raise forms.ValidationError(
                            _('%(email)s is not a valid e-mail address.')
                            % {'email': force_escape(email)})
        return cleaned_data
Exemplo n.º 23
0
def signup(request, username, password, email, **kwargs):
    """Create a new account

    - Username must have only letters/numbers and be 3-30 chars
    - Password must be 6-128 chars
    - Email is optional
    """
    raise APIException("disabled")
    if request.user.is_authenticated():
        raise APIException(_("you're already logged in"))
    check_username(username=username)
    if len(password) < 6:
        raise APIException(_("password must be at least six characters"))
    if len(password) > 128:
        raise APIException(_("password too long"))
    if email:
        if not email_re.match(email):
            raise APIException(_("invalid email address"))
    user = db.User()
    user.username = username
    user.set_password(password)
    user.email = email
    user.save()
    userinfo = db.UserInfo()
    userinfo.user = user
    userinfo.attendance = 'maybe'
    userinfo.save()
    user.userinfo = userinfo
    user.save()
    res = login(request, username, password)
    res[0]['conversion'] = render_to_string('occupywallst/conversion.html')
    return res
Exemplo n.º 24
0
def adduser(request):
    if  request.GET['email']!="" and request.GET['uname']!="" and request.GET['pass']!="":
        x= bool(email_re.match(request.GET['email']))
        if x:
            db = MySQLdb.connect(user='******', db='devesh mysite', passwd='', host='')
            cursor = db.cursor()
            sql="select email from users where email=%s"
            ml=request.GET['email']
            cursor.execute(sql,[ml])
            x = [row[0] for row in cursor.fetchall()]
            if x:
                msg="already exists"
            else:
                unm=request.GET['uname']
                ps=request.GET['pass']
                sql="insert into users(name,email,password) values(%s,%s,%s)"
                cursor.execute(sql,[unm,ml,ps])
                db.commit()
                request.session["umail"] = request.GET['email']
                return render_to_response('loggedin.html',{'msg': "added user"})
            db.close()
        else:
            msg="invalid email"
    else:
        msg = 'You submitted an empty form.'
    return HttpResponse(msg)
Exemplo n.º 25
0
def sync_atg_user(atg_user_name, profile=None):
    from tinla.users.models import Email, Phone

    if not atg_user_name:
        return
    try:
        if not profile:
            if email_re.match(atg_user_name):
                try:
                    e = Email.objects.get(email=atg_user_name)
                    profile = e.user
                except Email.DoesNotExist:
                    pass
            elif phone_regex.match(atg_user_name):
                try:
                    p = Phone.objects.get(phone=atg_user_name)
                    profile = p.user
                except Phone.DoesNotExist:
                    pass
            if not profile:
                # not able to find a matching user in tinla database
                # create new profile and user
                user, profile = utils.utils.get_or_create_user(atg_user_name)
        profile.atg_username = atg_user_name
        profile.save()
        return profile
    except Exception, e:
        log.exception("Error syncing atg user %s" % repr(e))
Exemplo n.º 26
0
def team_invite(request, organization_slug, team_id ):
    organization = get_object_or_404(Organization, slug=organization_slug)
    if not organization.hasStaffAccess( request.user ):
        raise PermissionDenied()
    team = get_object_or_404(Team, id=team_id)
    if team.organization != organization:
        raise PermissionDenied() # Shenanigans!
    userinput = request.POST.get("invitee")

    users = User.objects.filter(username__iexact=userinput)
    if len(users) == 0:
        users = User.objects.filter(email__iexact=userinput)

    if len(users) > 0:
        new_member = users[0]
        team.members.add( new_member )
        team.save()
        return team_detail(request, organization_slug, team_id)

    if email_re.match( userinput ):
        key = ''.join(random.choice(string.letters + string.digits) for i in xrange(8))
        invite = TeamInvite(email_address=userinput, team=team, key=key)
        invite.save()

        subject = _("Invtation to ScrumDo team")
        message = render_to_string("organizations/team_invite_email.txt", {
            "invite": invite,
            "inviter": request.user
        })

        send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [userinput])

    return team_detail(request, organization_slug, team_id)
Exemplo n.º 27
0
def marketplace(request):
    submitted = False
    error = False
    email = ''

    if request.method == 'POST':
        email = request.POST['email']
        format_ = 'T' if request.POST.get('format') == 'text' else 'H'
        newsletter = 'app-dev'

        if not email_re.match(email):
            error = 'email'

        if not request.POST.get('privacy', None):
            error = 'privacy'

        if not error:
            basket.subscribe(email, newsletter, format=format_)
            submitted = True
            
    return l10n_utils.render(request,
                             "marketplace/marketplace.html",
                             {'submitted': submitted,
                              'error': error,
                              'email': email})
Exemplo n.º 28
0
def submit(request, category):
	categories = [x[1].lower() for x in SIGNUP_CATEGORIES]

	# Looks like a malicious request - ignore (go back to homepage)
	if category not in categories or request.method != 'POST':
		return redirect('home')
	else:
		email = request.POST.get('email', '')
		name = request.POST.get('name', '')

		title = 'Unable to process submission'
		if email == '' or not email_re.match(email):
			message = 'Please enter a valid email address and name.'
		elif name == '':
			message = 'Please enter your name.'
		else:
			try:
				Person.objects.create(email=email, name=name, category=categories.index(category))
				title = 'Successful signup'
				message = 'Thank you for signing up for our %s listserv.' % category
			except IntegrityError:
				message = 'That email address has already been used. Perhaps you signed up before and forgot about it?'

		# Why is this method so messy. Switch to using forms later?
		data = {
			'title': title,
			'message': message
		}

		return render(request, 'confirmation.html', data)
Exemplo n.º 29
0
def is_valid_email(email_str):
    try:
        from django.core.validators import email_re
        return email_re.match(email_str)
    except ImportError:
        logging.warning("Django not installed; email validation not performed")
        return True
Exemplo n.º 30
0
def login (request):
  redirect_url = '/'
  if('redirect_url' in request.GET.keys()):
    redirect_url = urllib.unquote_plus(request.GET['redirect_url'])

  if not redirect_url or redirect_url == '':
    redirect_url = '/'

  if request.method == "POST":
    errors = []
    login_email = ''

    if('redirect_url' in request.POST.keys()):
      redirect_url = urllib.unquote_plus(request.POST['redirect_url'])

    
    email = None 
    try:
      login_id = request.POST["login_id"].lower()
      login_password = hashlib.sha1(request.POST["login_password"]).hexdigest()
      email = email_re.match(login_id.lower().strip())
      user = None
      if email:
        user = User.objects.get(email=login_id, password=login_password)
      else:
        user = User.objects.get(username=login_id, password=login_password)
      clear_session(request)
      request.session[kEmail] = user.email
      request.session[kUsername] = user.username

      redirect_url = redirect_url + urllib.unquote_plus('?auth_user=%s' %(user.username))
      return HttpResponseRedirect(redirect_url)
    except User.DoesNotExist:
      try:
        if email:
          User.objects.get(email=login_id)
        else:
          User.objects.get(username=login_id)
        errors.append(
            'Wrong password. Please try again.<br /><br />'
            '<a class="blue bold" href="/account/forgot">Click Here</a> '
            'to reset your password.')
      except User.DoesNotExist:
        errors.append(
            'Could not find any account associated with login_id: '
            '%s.<br /><br /><a class="blue bold" '
            'href="/account/register?redirect_url=%s">Click Here</a> '
            'to create an account.' %(login_id,
                urllib.quote_plus(redirect_url)))
      return login_form(
          request, redirect_url = urllib.quote_plus(redirect_url),
          errors = errors) 
    except:
      errors.append('Login failed.')
      return login_form(
          request, redirect_url = urllib.quote_plus(redirect_url),
          errors = errors)          
  else:
    return login_form(request, urllib.quote_plus(redirect_url))
Exemplo n.º 31
0
    def authenticate(self, username=None, password=None):

        if not '@' in username:
            return None

        login_user, domain = username.split('@')
        dom = UserAddresses.objects.filter(address=domain, address_type=1)

        if not dom:
            return None

        hosts = MailAuthHost.objects.filter(useraddress=dom)

        if not hosts:
            return None

        for host in hosts:
            if not host.split_address:
                login_user = username

            if self.mail_auth(host.protocol, login_user, password,
                              host.address, host.port):
                try:
                    user = User.objects.get(username=username)
                except User.DoesNotExist:
                    user = User(username=username)
                    user.set_unusable_password()
                    user.is_staff = False
                    user.is_superuser = False
                    if email_re.match(username):
                        user.email = username
                    user.save()
                try:
                    profile = user.get_profile()
                except UserProfile.DoesNotExist:
                    profile = UserProfile(user=user, account_type=3)
                    profile.save()
                return user
        return None
Exemplo n.º 32
0
def register(request):
    import re
    from django.core.validators import email_re

    context = {}
    if 'account' in request.POST:
        account = request.POST['account'].lower()
        email = request.POST['email'].lower()
        password = request.POST['password']

        # alphanumeric and underscore symbols allowed, no more than 30
        if not re.match(r'^[a-zA-Z0-9_]{1,30}$', account):
            context['error_acc_inval'] = True

        if not email_re.match(email):
            context['error_email'] = True

        if request.POST['password2'] != password:
            context['error_password'] = True

        if context == {}:
            try:
                user = models.User.objects.create_user(account, email,
                                                       password)
                user.save()
                # Always return an HttpResponseRedirect after successfully
                # dealing with POST data. This prevents data from being posted
                # twice if a user hits the Back button.
                return HttpResponseRedirect(
                    reverse('sight.views.signin_account', args=[account]))
            except IntegrityError:  # There is a record of the same user
                context['error_acc_registered'] = True

        context['account'] = account
        context['email'] = email
    return render_to_response('sight/register.html',
                              context,
                              context_instance=RequestContext(request))
Exemplo n.º 33
0
    def backwards(self, orm):
        # set third_party_identifier
        for user in orm.AstakosUser.objects.all():
            for auth_provider in user.auth_providers.all():
                user.provider = auth_provider.module
                user.third_party_identifier = auth_provider.identifier

            user.save()

        # reset usernames
        for u in orm.AstakosUser.objects.all():
            u.uuid = None
            u.auth_providers.all().delete()
            if email_re.match(u.username):
                username = None
                while not username:
                    username_val = uuid.uuid4().hex[:30]
                    try:
                        orm.AstakosUser.objects.get(username=username_val)
                    except orm.AstakosUser.DoesNotExist, e:
                        username = username_val
                u.username = username
            u.save()
Exemplo n.º 34
0
                def _doCheckValid():
                    # check if it is valid username
                    # - from 2 to 20 characters long
                    # - word, number, ., _, -
                    mtch = re.match('^[\w\d\_\.\-]{2,20}$', request.POST.get("username", "").strip())
                    if not mtch:  return 6

                    # check if it is valid email
                    if not bool(email_re.match(request.POST["email"].strip())): return 7

                    if request.POST.get("password", "") != request.POST.get("password2", "").strip(): return 8
                    if len(request.POST.get("password", "").strip()) < 6: return 9

                    if len(request.POST.get("fullname", "").strip()) > 30: return 11

                    # check if this user exists
                    try:
                        u = auth.models.User.objects.get(username=request.POST.get("username", ""))
                        return 10
                    except auth.models.User.DoesNotExist:
                        pass

                    return 0
Exemplo n.º 35
0
    def authenticate(self, username=None, password=None):
        """
        Retorna o usuário atraves do username ou email e password.
        se não encontrar retorna None.
        """
        # verifica se e um email
        if email_re.match(username):
            try:
                user = User.objects(email=username).first()
            except User.DoesNotExist:
                return None

        # caso nao autentica no modo padrao
        else:
            try:
                user = User.objects(username=username).first()
            except User.DoesNotExist:
                return None

        if user:
            if password and user.check_password(password):
                return user
        return None
Exemplo n.º 36
0
    def _import_data_sender(self, form_model, organization, values):
        try:
            mobile_number = case_insensitive_lookup(values, "m")

            if not mobile_number:
                raise MobileNumberMandatoryException()
            if organization.in_trial_mode:
                from accountmanagement.helper import is_mobile_number_unique_for_trial_account
                if not is_mobile_number_unique_for_trial_account(
                        organization, mobile_number):
                    raise MultipleReportersForANumberException(mobile_number)
                else:
                    data_sender = DataSenderOnTrialAccount.objects.model(
                        mobile_number=mobile_number, organization=organization)
                    data_sender.save(force_insert=True)
        except IntegrityError:
            raise MultipleReportersForANumberException(mobile_number)
        except Exception as ex:
            raise ex

        if len(",".join(values["l"])) > 500:
            raise MangroveException(
                "Location Name cannot exceed 500 characters.")

        email = case_insensitive_lookup(values, "email")
        if email:
            if not email_re.match(email):
                raise InvalidEmailException(message="Invalid email address.")

            self._validate_duplicate_email_address(email)

            response = self.submit(form_model, values, [])

        else:
            response = self.submit(form_model, values, [])

        return response
Exemplo n.º 37
0
    def clean(self):
        """clean_address"""
        if self._errors:
            return self.cleaned_data

        cleaned_data = self.cleaned_data
        address = cleaned_data['address']
        user = cleaned_data['user']
        if user.is_superuser:
            error_msg = _('Super users do not use addresses')
            self._errors["address"] = ErrorList([error_msg])
            del cleaned_data['address']
        account = UserProfile.objects.get(user=user)
        if account.account_type == 2:
            if not DOM_RE.match(address):
                error_msg = _('provide a valid domain address')
                self._errors["address"] = ErrorList([error_msg])
                del cleaned_data['address']
        else:
            if not email_re.match(address):
                error_msg = _('provide a valid email address')
                self._errors["address"] = ErrorList([error_msg])
                del cleaned_data['address']
        return cleaned_data
Exemplo n.º 38
0
 def clean_user_identifiers(self):
     value = self.cleaned_data["invite_user_identifiers"]
     invitees, errors = [], []
     
     for ui in value.split(","):
         ui = ui.strip()
         
         if email_re.match(ui):
             try:
                 invitees.append(User.objects.get(email=ui))
             except User.DoesNotExist:
                 invitees.append(ui)
         else:
             try:
                 invitees.append(User.objects.get(username=ui))
             except User.DoesNotExist:
                 errors.append(ui)
     
     if errors:
         message = ("The following are not valid email addresses or "
             "usernames: %s; no invitations sent" % ", ".join(errors))
         raise forms.ValidationError(message)
     
     return invitees
Exemplo n.º 39
0
def is_valid_email(email):
    """ check if a string is a valid email address
    django dependant

    @param email: - the string to evaluate
    @return: boolean, True if valid, False if not

    >>> is_valid_email("*****@*****.**")
    True
    >>> is_valid_email("foobar")
    False
    """
    try:
        from django.core.validators import email_re

        return True if email_re.match(email) else False
    except ImportError:
        from django.core.validators import validate_email

        try:
            validate_email(email)
        except ValidationError:
            return False
        return True
Exemplo n.º 40
0
def email_is_valid(email):
    return True if email_re.match(email) else False
Exemplo n.º 41
0
def is_valid_email(email):
    return True if email_re.match(email) else False
Exemplo n.º 42
0
 def validate(self, value):
     if len(value) == 0:
         raise ValidationError('Choose one contact at least.')
     for email in value:
         if not email_re.match(email):
             raise ValidationError('Incorrect choice.')
Exemplo n.º 43
0
 def is_valid(self):
     """
     Checks if this Mail is valid by validating the email address.
     """
     return email_re.match(self.person.get_email())
Exemplo n.º 44
0
def register (request):
  redirect_url = '/'
  if('redirect_url' in request.GET.keys()):
    redirect_url = urllib.unquote_plus(request.GET['redirect_url'])

  if request.method == "POST":
    errors = []
    email = ''
    try:
      error = False
      if('redirect_url' in request.POST.keys()):
        redirect_url = urllib.unquote_plus(request.POST['redirect_url'])

      username = request.POST["username"].lower()
      email = request.POST["email"].lower()
      password = request.POST["password"]

      if(email_re.match(email.strip()) == None):
        errors.append("Invalid Email.")
        error = True
      if(not is_valid_username(username)):
        errors.append("Invalid Username.")
        error = True
      if(password == ""):
        errors.append("Empty Password.")
        error = True

      try:
        user = User.objects.get(username=username)
        errors.append("Username already taken.")
        error = True
      except User.DoesNotExist:
        pass

      if not error:
        hashed_password = hashlib.sha1(password).hexdigest()
        try:
          DataHubManager.create_user(username=username, password=hashed_password)
        except Exception, e:
          pass

        try:
          DataHubManager.change_password(username=username, password=hashed_password)
        except Exception, e:
          errors.append(str(e))
          error = True

      if(error):
        return register_form(request, redirect_url = urllib.quote_plus(redirect_url), errors = errors)

      user = User(username=username, email=email, password=hashed_password)
      user.save()

      clear_session(request)
      request.session[kEmail] = user.email
      request.session[kUsername] = user.username

      encrypted_email = encrypt_text(user.email)

      subject = "Welcome to DataHub"

      msg_body = '''
      Dear %s,

      Thanks for registering to DataHub. 

      Please click the link below to start using DataHub:

      %s://%s/account/verify/%s

      ''' % (
          user.email,
          'https' if request.is_secure() else 'http',
          request.get_host(),          
          encrypted_email)

      pool.apply_async(send_email, [user.email, subject, msg_body])

      return HttpResponseRedirect(redirect_url)
Exemplo n.º 45
0
 def testGetValue(self):
     """Tests getValue().
 """
     value = self.provider.getValue()
     self.assertTrue(value is not None)
     self.assertTrue(email_re.match(value))
Exemplo n.º 46
0
def api_add_rp(data):
    """Create a recurrring payment account. Accepted format: json
    
    Input fields:
        email - required
        description - required
        payment_amount - required
        billing_period - optional, default to 'month'
        billing_frequency - optional, default to 1
        billing_start_dt - optional, default to today
        num_days - optional, default to 0
        has_trial_period - optional, default to False
        trial_period_start_dt - optional, default to today
        trial_period_end_dt - optional, default to today
        trial_amount - optional, default to 0
        
    Output:
        rp_id - a recurring payment id
        result_code
    """
    ALLOWED_FIELES = ('email',
                      'description',
                      'payment_amount',
                      'billing_period',
                      'billing_frequency',
                      'billing_start_dt',
                      'num_days',
                      'has_trial_period',
                      'trial_period_start_dt',
                      'trial_period_end_dt',
                      'trial_amount',
                      )
    from decimal import Decimal
    from django.core.validators import email_re
    import dateutil.parser as dparser
    from tendenci.core.imports.utils import get_unique_username
    
    email = data.get('email', '')
    payment_amount = data.get('payment_amount', '')
    try:
        payment_amount = Decimal(payment_amount)
    except:
        payment_amount = 0
    
    
    if not all([email_re.match(email), 
                data.has_key('description'),
                payment_amount>0]):
        return False, {}
    
    
    rp = RecurringPayment()
    for key, value in data.items():
        if key in ALLOWED_FIELES:
            if hasattr(rp, key):
                setattr(rp, key, value)
            
    if rp.billing_start_dt:
        try:
            rp.billing_start_dt = dparser.parse(rp.billing_start_dt)
        except:
            rp.billing_start_dt = datetime.now()
    else:
        rp.billing_start_dt = datetime.now()
    if rp.trial_period_start_dt:
        try:
            rp.trial_period_start_dt = dparser.parse(rp.trial_period_start_dt)
        except:
            rp.trial_period_start_dt = datetime.now()
    
    if rp.trial_period_end_dt:
        try:
            rp.trial_period_end_dt = dparser.parse(rp.trial_period_end_dt)
        except:
            rp.trial_period_end_dt = datetime.now()
        
    rp.payment_amount = Decimal(rp.payment_amount)
    
    try:
        rp.billing_frequency = int(rp.billing_frequency)
    except:
        rp.billing_frequency = 1
    try:
        rp.num_days = int(rp.num_days)
    except:
        rp.num_days = 1
    if rp.has_trial_period in ['True', '1',  True, 1] and all([rp.trial_period_start_dt,
                                                              rp.trial_period_end_dt]):
        rp.has_trial_period = True
    else:
        rp.has_trial_period = False
        
    # start the real work
    
#    # get or create a user account with this email
#    users = User.objects.filter(email=email)
#    if users:
#        u = users[0]
#    else:

    # always create a new user account - This is very important!
    # it is to prevent hacker from trying to use somebody else's account. 
    u = User()
    u.email=email
    u.username = data.get('username', '')
    if not u.username:
        u.username = email.split('@')[0]
    u.username = get_unique_username(u)
    raw_password = data.get('password', '')
    if not raw_password:
        raw_password = User.objects.make_random_password(length=8)
    u.set_password(raw_password)
    u.first_name = data.get('first_name', '')
    u.last_name = data.get('last_name', '')
    u.is_staff = False
    u.is_superuser = False
    u.save()
    
#    profile = Profile.objects.create(
#           user=u, 
#           creator=u, 
#           creator_username=u.username,
#           owner=u, 
#           owner_username=u.username, 
#           email=u.email
#        )
    
    # add a recurring payment entry for this user
    rp.user = u
    # activate it when payment info is received
    rp.status_detail = 'inactive'
    rp.save()
    
    return True, {'rp_id': rp.id}
Exemplo n.º 47
0
def email_validate(val):
    if email_re.match(val): return True
    return False
Exemplo n.º 48
0
    def clean(self):
        cleaned_data = self.cleaned_data
        field_function = cleaned_data.get("field_function")
        choices = cleaned_data.get("choices")
        field_type = cleaned_data.get("field_type")
        required = cleaned_data.get("required")

        if field_function == "GroupSubscription":
            if field_type != "BooleanField":
                raise forms.ValidationError(
                    _("This field's function requires Checkbox as a field type"
                      ))
            if not choices:
                raise forms.ValidationError(
                    _("This field's function requires at least 1 group specified."
                      ))
            else:
                for val in choices.split(','):
                    try:
                        Group.objects.get(name=val.strip())
                    except Group.DoesNotExist:
                        raise forms.ValidationError(
                            _("The group \"%(val)s\" does not exist" %
                              {'val': val}))

        if field_function == "Recipients":
            if (field_type !=
                    "MultipleChoiceField/django.forms.CheckboxSelectMultiple"
                    and field_type != "MultipleChoiceField"
                    and field_type != "BooleanField"
                    and field_type != "ChoiceField"):
                raise forms.ValidationError(
                    _("The \"Email to Recipients\" function requires Multi-select - Checkboxes "
                      + "or Multi-select - Select Many as field type"))

            if field_type == "BooleanField":
                if not choices:
                    raise forms.ValidationError(
                        _("The \"Email to Recipients\" function requires at least 1 email specified."
                          ))
                else:
                    for val in choices.split(','):
                        if not email_re.match(val.strip()):
                            raise forms.ValidationError(
                                _("\"%(val)s\" is not a valid email address" %
                                  {'val': val}))
            else:
                if not choices:
                    raise forms.ValidationError(
                        _("The \"Email to Recipients\" function requires at least 1 choice specified."
                          ))
                else:
                    for val in choices.split(','):
                        val = val.split(':')
                        if len(val) < 2:
                            raise forms.ValidationError(
                                _("The \"Email to Recipients\" function requires choices to be in the following format: <choice_label>:<email_address>."
                                  ))
                        if not email_re.match(val[1].strip()):
                            raise forms.ValidationError(
                                _("\"%(val)s\" is not a valid email address" %
                                  {'val': val[1]}))

        if field_function != None and field_function.startswith("Email"):
            if field_type != "CharField":
                raise forms.ValidationError(
                    _("This field's function requires Text as a field type"))

        #unrequire the display only fields
        if field_type == "CharField/tendenci.apps.forms_builder.forms.widgets.Description":
            cleaned_data['required'] = False
        elif field_type == "CharField/tendenci.apps.forms_builder.forms.widgets.Header":
            cleaned_data['required'] = False

        return cleaned_data
Exemplo n.º 49
0
def api_rp_setup(data): 
    """Create a recurrring payment account. Accepted format: json
    
    Input fields:
        email - required
        description - required
        amount - required
        cp_id - customer profile id, required
        pp_id - customer payment profile id, required
        billing_cycle_start_dt - required
        billing_cycle_end_dt - required
        response_str - required
        login_name 
        login_password
        url 
        first_name
        last_name
          
        
        billing_period - optional, default to 'month'
        billing_frequency - optional, default to 1
        billing_start_dt - optional, default to today
        num_days - optional, default to 0
        has_trial_period - optional, default to False
        trial_period_start_dt - optional, default to today
        trial_period_end_dt - optional, default to today
        trial_amount - optional, default to 0
        
    Output:
        rp_id - a recurring payment id
        rp_url - url to rp
        username        
        result_code
    """
    from decimal import Decimal
    from django.core.validators import email_re
    import dateutil.parser as dparser
    from tendenci.core.imports.utils import get_unique_username
    
    email = data.get('email', '')
    description = data.get('description', '')
    url = data.get('url')
    payment_amount = data.get('amount', '')
    taxable = data.get('taxable', 0)
    if taxable in ('True', 'true', '1', 1): 
        taxable = 1
    else: 
        taxable = 0
    try:
        tax_rate = Decimal(data.get('tax_rate', 0))
        if tax_rate > 1: tax_rate = 0
    except:
        tax_rate = 0
    tax_exempt = data.get('tax_exempt', 0)
    if tax_exempt in ('True', 'true', '1', 1): 
        tax_exempt = 1
    else: 
        tax_exempt = 0
    try:
        payment_amount = Decimal(payment_amount)
    except:
        payment_amount = 0
    cp_id = data.get('cp_id')
    pp_id = data.get('pp_id')
    billing_cycle_start_dt = data.get('billing_cycle_start_dt')
    if billing_cycle_start_dt:
        billing_cycle_start_dt = dparser.parse(billing_cycle_start_dt)
    billing_cycle_end_dt = data.get('billing_cycle_end_dt')
    if billing_cycle_end_dt:
        billing_cycle_end_dt = dparser.parse(billing_cycle_end_dt)
        
    direct_response_str = data.get('response_str')
    
    if not all([email_re.match(email), 
                description,
                payment_amount>0,
                cp_id,
                pp_id,
                billing_cycle_start_dt,
                billing_cycle_end_dt,
                direct_response_str] 
               ):
        return False, {}
    
    # 1) get or create user
    username = data.get('login_name')
    
    # check if user already exists based on email and username
    users = User.objects.filter(email=email, username=username)
    if users:
        u = users[0]
    else:
        # create user account
        u = User()
        u.email=email
        u.username = username
        if not u.username:
            u.username = email.split('@')[0]
        u.username = get_unique_username(u)
        raw_password = data.get('login_password')
        if not raw_password:
            raw_password = User.objects.make_random_password(length=8)
        u.set_password(raw_password)
        u.first_name = data.get('first_name', '')
        u.last_name = data.get('last_name', '')
        u.is_staff = False
        u.is_superuser = False
        u.save()
        
        profile = Profile.objects.create(
           user=u, 
           creator=u, 
           creator_username=u.username,
           owner=u, 
           owner_username=u.username, 
           email=u.email
        )
        
    # 2) create a recurring payment account
    rp = RecurringPayment()
    rp.user = u
    rp.description = description
    rp.url = url
    rp.payment_amount = payment_amount
    rp.taxable = taxable
    rp.tax_rate = tax_rate
    rp.tax_exempt = tax_exempt
    rp.customer_profile_id = cp_id
    rp.billing_start_dt = billing_cycle_start_dt
    
    has_trial_period = data.get('has_trial_period')
    trial_period_start_dt = data.get('trial_period_start_dt')
    trial_period_end_dt = data.get('trial_period_end_dt')
    if has_trial_period in ['True', '1',  True, 1] and all([trial_period_start_dt,
                                                            trial_period_end_dt]):
        rp.has_trial_period = True
        rp.trial_period_start_dt = dparser.parse(trial_period_start_dt) 
        rp.trial_period_end_dt = dparser.parse(trial_period_end_dt)
    else:
        rp.has_trial_period = False
        
    rp.status_detail = 'active'
    rp.save()
    
    # 3) create a payment profile account
    payment_profile_exists = PaymentProfile.objects.filter(
                                        customer_profile_id=cp_id,
                                        payment_profile_id=pp_id
                                        ).exists()
    if not payment_profile_exists:
        PaymentProfile.objects.create(
                        customer_profile_id=cp_id,
                        payment_profile_id=pp_id,
                        owner=u,
                        owner_username=u.username
                        )
        
    # 4) create rp invoice
    billing_cycle = {'start': billing_cycle_start_dt,
                     'end': billing_cycle_end_dt}
    rp_invoice = rp.create_invoice(billing_cycle, billing_cycle_start_dt)
    rp_invoice.invoice.tender(rp.user)
    
    # 5) create rp transaction
    now = datetime.now()
    payment = Payment()
    payment.payments_pop_by_invoice_user(rp.user, 
                                         rp_invoice.invoice, 
                                         rp_invoice.invoice.guid)
    payment_transaction = PaymentTransaction(
                                    recurring_payment=rp,
                                    recurring_payment_invoice=rp_invoice,
                                    payment_profile_id=pp_id,
                                    trans_type='auth_capture',
                                    amount=rp_invoice.invoice.total,
                                    status=True)
    payment = payment_update_from_response(payment, direct_response_str)
    payment.mark_as_paid()
    payment.save()
    rp_invoice.invoice.make_payment(rp.user, Decimal(payment.amount))
    rp_invoice.invoice.save()
    
    
    rp_invoice.payment_received_dt = now
    rp_invoice.save()
    rp.last_payment_received_dt = now
    rp.num_billing_cycle_completed += 1
    rp.save()
    
    payment_transaction.payment = payment
    payment_transaction.result_code = data.get('result_code')
    payment_transaction.message_code = data.get('message_code')
    payment_transaction.message_text = data.get('message_text')
        
    payment_transaction.save()
    
    site_url = get_setting('site', 'global', 'siteurl')

    
    return True, {'rp_id': rp.id,
                  'rp_url': '%s%s' %  (site_url, 
                                reverse('recurring_payment.view_account', args=[rp.id])),
                  'username': rp.user.username}
Exemplo n.º 50
0
def is_valid_email(email):
    if email_re.match(email):
        return True
    return False
Exemplo n.º 51
0
def _is_valid_email(email):
    return email_re.match(email)
Exemplo n.º 52
0
def is_valid_email(email):
    return bool(email_re.match(email))
Exemplo n.º 53
0
def validate_email(value):
    """Validate that a username is email like."""
    if not email_re.match(value):
        raise ValidationError(_('Enter a valid address.'))
    return value
Exemplo n.º 54
0
    def run(self, legacy_obj):

        from alibrary.models import Label, Relation, Distributor, DistributorLabel

        status = 1

        log = logging.getLogger('util.migrator.run')
        log.info('migrate release: %s' % legacy_obj.name)

        obj, created = Label.objects.get_or_create(legacy_id=legacy_obj.id)

        if created:
            log.info('object created: %s' % obj.pk)
        else:
            log.info('object found by legacy_id: %s' % obj.pk)

        if created:
            """
			Mapping data
			1-to-1 fields
			"""
            obj.name = legacy_obj.name
            obj.created = legacy_obj.created
            obj.updated = legacy_obj.updated

            if legacy_obj.published:
                obj.published = legacy_obj.published

            if legacy_obj.label_type:
                obj.type = legacy_obj.label_type

            if legacy_obj.label_code:
                log.debug('label_code: %s' % legacy_obj.label_code)
                obj.labelcode = legacy_obj.label_code[:200]

            if legacy_obj.profile:
                if legacy_obj.notes:
                    obj.description = "%s\n\n%s" % (legacy_obj.profile,
                                                    legacy_obj.notes)
                else:
                    obj.description = legacy_obj.profile

            if legacy_obj.address:
                obj.address = legacy_obj.address

            if legacy_obj.contact:
                log.debug('contact: %s' % legacy_obj.contact)
                if email_re.match(legacy_obj.contact):
                    obj.email = legacy_obj.contact

            if legacy_obj.country:
                log.debug('country: %s' % legacy_obj.country)
                country = None
                if len(legacy_obj.country) == 2:
                    try:
                        country = Country.objects.get(
                            iso2_code=legacy_obj.country)
                    except Exception, e:
                        pass

                else:
                    try:
                        country = Country.objects.get(
                            printable_name=legacy_obj.country)
                    except Exception, e:
                        pass

                if country:
                    log.debug('got country: %s' % country.name)
                    obj.country = country
Exemplo n.º 55
0
def isValidEmail(email):
    if email_re.match(email):
        return True
    return False
Exemplo n.º 56
0
    def clean(self):
        "validate the form"
        cleaned_data = self.cleaned_data
        submited_field = cleaned_data.get('filtered_field')
        submited_by = int(cleaned_data.get('filtered_by'))
        submited_value = cleaned_data.get('filtered_value')
        if submited_by != 0:
            sbi = (submited_by - 1)
        else:
            sbi = submited_by

        if submited_field in BOOL_FIELDS:
            if not submited_by in BOOL_FILTER:
                filter_items = dict(FILTER_ITEMS)
                error_msg = _("%(field)s does not support the %(filt)s filter") % {
                'field': filter_items[submited_field], 'filt': FILTER_BY[sbi][1]}
                raise forms.ValidationError(error_msg)
        if submited_field in NUM_FIELDS:
            if not submited_by in NUM_FILTER:
                filter_items = dict(FILTER_ITEMS)
                error_msg = _("%(field)s does not support the %(filt)s filter") % {
                'field': filter_items[submited_field], 'filt': FILTER_BY[sbi][1]}
                raise forms.ValidationError(error_msg)
            if submited_value in EMPTY_VALUES:
                raise forms.ValidationError(_("Please supply a value to query"))
            if not isnumeric(submited_value):
                raise forms.ValidationError(_("The value has to be numeric"))
        if submited_field in TEXT_FIELDS:
            if not submited_by in TEXT_FILTER:
                filter_items = dict(FILTER_ITEMS)
                error_msg = _("%(field)s does not support the %(filt)s filter") % {
                'field': filter_items[submited_field], 'filt': FILTER_BY[sbi][1]}
                raise forms.ValidationError(error_msg)
            if submited_value in EMPTY_VALUES and submited_by not in [9, 10]:
                raise forms.ValidationError(_("Please supply a value to query"))
            if ((submited_field == 'from_address' or
                submited_field == 'to_address') and
                submited_by in [1, 2]):
                if not email_re.match(submited_value.strip()):
                    raise forms.ValidationError(
                        _('%(email)s is not a valid e-mail address.')
                        % {'email': force_escape(submited_value)})
            else:
                if submited_by in [7, 8]:
                    try:
                        re.compile(submited_value)
                    except re.error:
                        raise forms.ValidationError(
                            _("Please provide a valid regex")
                        )
            if ((submited_field == 'from_domain' or
                submited_field == 'to_domain') and
                submited_by in [1, 2]):
                if not DOM_RE.match(submited_value.strip()):
                    raise forms.ValidationError(
                        _('Please provide a valid domain name'))
            else:
                if submited_by in [7, 8]:
                    try:
                        re.compile(submited_value)
                    except re.error:
                        raise forms.ValidationError(
                            _("Please provide a valid regex")
                        )
            if submited_field == 'clientip':
                if not ipv4_re.match(submited_value.strip()):
                    raise forms.ValidationError(
                        _('Please provide a valid ipv4 address'))
            if submited_field == 'hostname':
                if ((not ipv4_re.match(submited_value.strip())) and
                (not DOM_RE.match(submited_value.strip()))):
                    raise forms.ValidationError(
                    _("Please provide a valid hostname or ipv4 address")
                    )
        if submited_field in TIME_FIELDS:
            if not submited_by in TIME_FILTER:
                filter_items = dict(FILTER_ITEMS)
                error_msg = _("%(field)s does not support the %(filt)s filter") % {
                'field': filter_items[submited_field], 'filt': FILTER_BY[sbi][1]}
                raise forms.ValidationError(error_msg)
            if submited_value in EMPTY_VALUES:
                raise forms.ValidationError(_("Please supply a value to query"))
            if submited_field == 'date':
                try:
                    datetime.date(
                        *time.strptime(submited_value, '%Y-%m-%d')[:3])
                except ValueError:
                    raise forms.ValidationError(
                        _('Please provide a valid date in YYYY-MM-DD format'))
            if submited_field == 'time':
                try:
                    datetime.time(*time.strptime(submited_value, '%H:%M')[3:6])
                except ValueError:
                    raise forms.ValidationError(
                        _('Please provide valid time in HH:MM format'))

        return cleaned_data
Exemplo n.º 57
0
def migrate():
    # Migration plan
    # Read user, user address book from atg
    # Create one user in tinla per atg user

    #ezone_orders_users = FtbOrder.objects.select_related('order').all().values(
    #    'order__profile').distinct()
    #atg_users = DpsUser.objects.filter(dps_id__in = ezone_orders_users)
    atg_users = DpsUser.objects.all()

    count = atg_users.count()
    log.info('Found %s users in atg.' % count)
    index = 0
    exists = 0
    non_existing = 0
    newly_created = 0
    migrated = 0
    errors = 0
    attached = 0
    not_attached = 0
    atg_users = queryset_iterator(atg_users)
    for atg_user in atg_users:
        index += 1
        db.reset_queries()
        # Check if username is already taken in tinla
        # Tinla's usernames are phone numbers and email addresses
        email = None
        phone = None
        profile = None
        auth_user = None
        found = False
        username = atg_user.login
        try:
            email = Email.objects.select_related(
                'user', 'user__user').get(email=username)
            profile = email.user
            auth_user = profile.user
            found = True
        except Email.DoesNotExist:
            try:
                phone = Phone.objects.select_related(
                    'user', 'user__user').get(phone=username[:10])
                profile = phone.user
                auth_user = profile.user
                found = True
            except Phone.DoesNotExist:
                pass
        if found:
            exists += 1
            if profile.atg_login:
                migrated += 1
                if profile.atg_login != username:
                    log.info(
                        'Skipping user: %s. Check if it matches with: %s' %
                        (username, profile.atg_login))
            else:
                try:
                    profile.atg_login = username
                    profile.atg_password = atg_user.password
                    profile.save()
                    log.info(
                        'User exists. Just mapping atg_login and atg_password %s'
                        % username)
                    attached += 1
                except:
                    log.info('User exists. Duplicate atg_login %s' % username)
                    not_attached += 1
        else:
            non_existing += 1
            log.info('%s not found in tinla' % username)
            # No email and phone taken.
            if phone_re.match(username):
                phone = Phone(phone=username[:10])
            if email_re.match(username):
                email = Email(email=username)
            try:
                profile = new_profile(atg_user, phone, email)
                if profile:
                    newly_created += 1
                    log.info('Created new profile for %s. id is %s' %
                             (username, profile.id))
            except Exception, e:
                errors += 1
                log.exception('Error migrating %s. %s' % (username, repr(e)))

        if index % 10000 == 0:
            log.info('Processed %s/%s' % (index, count))
Exemplo n.º 58
0
    def register(self, request, **kwargs):
        # Allows POST request
        self.method_check(request, allowed=['post'])

        # Deserialize the JSon response
        data = self.deserialize(request,
                                request.raw_post_data,
                                format=request.META.get(
                                    'CONTENT_TYPE', 'application/json'))

        # Get the needed datas
        username = data.get('username', '')
        email = data.get('email', '')
        password1 = data.get('password1', '')
        password2 = data.get('password2', '')

        if len(username
               ) == 0:  # If password1 and password2 don't match, return error
            return self.create_response(request, {
                'success': False,
                'reason': 'username is empty',
            })
        elif len(User.objects.filter(username=username)
                 ) != 0:  # the username is already taken, return error
            return self.create_response(request, {
                'success': False,
                'reason': 'user already exist',
            })
        elif len(email) == 0:  # If email is empty, return error
            return self.create_response(request, {
                'success': False,
                'reason': 'email is empty',
            })
        elif not email_re.match(
                email):  # If email data is not a good email, return error
            return self.create_response(request, {
                'success': False,
                'reason': 'email not valid',
            })
        elif len(User.objects.filter(
                email=email)) != 0:  # If email already exist, return error
            return self.create_response(request, {
                'success': False,
                'reason': 'email already in use',
            })
        elif len(password1) == 0:  # If password is empty, return error
            return self.create_response(request, {
                'success': False,
                'reason': "passwords don't exist",
            })
        elif password1 != password2:  # If password1 and password2 don't match, return error
            return self.create_response(request, {
                'success': False,
                'reason': "passwords don't match",
            })
        else:  # If already is ok, let's go for regisrtation
            # create a user and authenticate him (needed for login)
            user = User.objects.create_user(username, email, password1)
            user = authenticate(username=username, password=password1)
            # If user exist and is active, log him
            if user:
                if user.is_active:
                    login(request, user)

            # Create a member object and link the user to it
            member = Member()
            member.user = user
            member.save()

            # Create a dictionnary for json response and delete unuse datas
            member = member.__dict__
            del member["_state"]
            del member["user_id"]
            # Add his api_key
            api_key = ApiKey.objects.get(user=user).key
            member["api_key"] = api_key

            # Return success = True and the member object
            return self.create_response(request, {
                'success': True,
                'member': member
            })
Exemplo n.º 59
0
 def is_valid_email(request, email):
     encontrado = False
     if email_re.match(email):
         encontrado = True
     return encontrado
Exemplo n.º 60
0
class Migration(DataMigration):
    def forwards(self, orm):
        # valid activation_sent/email_verified
        for user in orm.AstakosUser.objects.all():
            if user.is_active:
                if not user.activation_sent:
                    user.activation_sent = datetime.datetime.now()
                    user.email_verified = True
                    user.save()

            while not user.uuid:
                uuid_val = str(uuid.uuid4())
                try:
                    orm.AstakosUser.objects.get(uuid=uuid_val)
                except orm.AstakosUser.DoesNotExist, e:
                    user.uuid = uuid_val
                    user.save()

        # migrate to auth providers
        for user in orm.AstakosUser.objects.all():
            if user.provider and user.provider != 'local':
                orm.AstakosUserAuthProvider.objects.create(
                    user=user,
                    module=user.provider,
                    identifier=user.third_party_identifier)
            else:
                orm.AstakosUserAuthProvider.objects.create(
                    user=user, module='local', auth_backend='astakos')

            user.save()

        # migrate duplicate emails
        to_remove = getattr(
            settings, 'ASTAKOS_MIGRATION_0045_DELETE_DUPLICATE_USER_IDS', [])
        for pk in to_remove:
            try:
                u = orm.AstakosUser.objects.get(pk=int(pk))
                print "Removing user: %s (%d)" % (u.email, u.pk)
            except Exception:
                msg = "You requested user with id %s to be removed but such user doesn't exist in database" % str(
                    pk)
                raise Exception(msg)

            if orm.AstakosUser.objects.filter(
                    email__iexact=u.email).count() == 1:
                msg = (
                    "You requested user with duplicate email %s and id (%d) to"
                    " be removed, but it seems that only one user exists with this"
                    " email in the database.") % (u.email, pk)
                raise Exception(msg)
            else:
                orm.AstakosUser.objects.filter(pk=int(pk)).delete()

        for u in orm.AstakosUser.objects.all():
            if orm.AstakosUser.objects.filter(
                    email__iexact=u.email).count() > 1:
                existing = orm.AstakosUser.objects.filter(
                    email__iexact=u.email)
                print "Duplicate email found in database"
                for e in existing:
                    print "%d: %s (is_active: %s)" % (e.pk, e.email,
                                                      e.is_active)
                keep = input(
                    "Select which user id you want to BE PRESERVED in the database: "
                )
                if keep:
                    for e in existing.exclude(pk=int(keep)):
                        e.delete()
                else:
                    raise Exception(
                        "Email %s is not unique %r. Please resolve conflicts and run migrate again."
                        % (u.email, existing))
            u = orm.AstakosUser.objects.get(email__iexact=u.email)
            save = False
            if not email_re.match(u.username):
                u.username = u.email.lower()
                save = True
            if save:
                u.save()