def test_ukranian_regular(self):
        self.assertTrue(validate_email(r'юзер@екзампл.ком')) # Chinese

        self.assertFalse(validate_email(r'')) # No @
        self.assertFalse(validate_email(r'')) # No .
        self.assertFalse(validate_email(r'')) # Nothing after the .
        self.assertFalse(validate_email(r'')) # Nothing before the @
Exemple #2
0
def main(argv):
    input_folder = ''
    input_email = ''

    try:
        opts, args = getopt.getopt(argv,"hf:e:",["ffolder=","eemail="])
    except getopt.GetoptError:
        print 'test.py -f <folder> -e <email>'
        #print 'test.py -i <inputfile> -o <outputfile>'
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print 'globus_share.py -f <folder> -e <email>'
            sys.exit()
        elif opt in ("-f", "--ffolder"):
            input_folder = arg
        elif opt in ("-e", "--eemail"):
            input_email = arg
    
    input_folder = os.path.normpath(input_folder) + os.sep # will add the trailing slash if it's not already there.

    globus_add = "acl-add " + local_user + local_share + os.sep + input_folder  + " --perm r --email " + input_email

    if validate_email(input_email) and os.path.isdir(local_shared_folder + input_folder):
        cmd = "ssh " + globus_user + globus_address + " " + globus_add
        print cmd
        #os.system(cmd)
        print "Download link sent to: ", input_email
    else:
        print "ERROR: "
        if not validate_email(input_email):
            print "email is not valid ..."
        else:
            print local_shared_folder + input_folder, "does not exists on the local server", 
    def test_chinese_regular(self):
        self.assertTrue(validate_email(r'用户@例子.广告')) # Chinese

        self.assertFalse(validate_email(r'用户例子.广告')) # No @
        self.assertFalse(validate_email(r'用户@例子广告')) # No .
        self.assertFalse(validate_email(r'用户@例子.')) # Nothing after the .
        self.assertFalse(validate_email(r'@例子.广告')) # Nothing before the @
  def getErrors(self):
    """
    Searches the data for errors. If no errors are detected, 
    None is returned. If one or more errors are detected, a list
    of errors are returned
    """
    def addError(errors, name, err):
      tmp = errors.get(name, list())
      tmp.append(err)
      errors[name] = tmp

    errors = dict()

    if not self.sender:
      addError(errors, 'sender', 'Required')

    if not self.receivers:
      addError(errors, 'receivers', 'Required')

    if not errors.get('sender', []) and not validate_email(self.sender):
      addError(errors, 'sender', 'Invalid email')

    for receiver in self.receivers:
      if not validate_email(receiver):
        addError(errors, 'receivers', {'email': receiver, 'reason': 'Invalid email'})

    if errors:
      return errors
    else:
      return None
Exemple #5
0
def minion(id=0, field='email'):

    # zmq context and
    context = zmq.Context()

    # receive work
    consumer_receiver = context.socket(zmq.PULL)
    consumer_receiver.connect("tcp://127.0.0.1:5557")

    # send work
    consumer_sender = context.socket(zmq.PUSH)
    consumer_sender.connect("tcp://127.0.0.1:5558")

    # logger
    logger = open("log/{0}".format(id), 'w')

    while True:
        row = consumer_receiver.recv_json()
        email = row[field]
        if validate_email(email):
            if validate_email(email, check_mx=True):
                if validate_email(email, verify=True):
                    res = {'row': row, 'is_valid': True}
                else:
                    res = {'row': row, 'is_valid': False, 'err': 'KO-USER'}
            else:
                res = {'row': row, 'is_valid': False, 'err': 'KO-MX'}
        else:
            res = {'row': row, 'is_valid': False, 'err': 'KO-RFC'}

        consumer_sender.send_json(res)
        logger.write("{0} - {1}\n".format(datetime.now(), res))
        logger.flush()
    def test_german_regular(self):
        self.assertTrue(validate_email(r'Dörte@Sörensen.example.com'))

        self.assertFalse(validate_email(r'DörteSörensen.example.com')) # No @
        self.assertFalse(validate_email(r'Dörte@Sörensenexamplecom')) # No .
        self.assertFalse(validate_email(r'Dörte@Sörensen.')) # Nothing after the .
        self.assertFalse(validate_email(r'@Sörensen.example.com')) # Nothing before the @
    def test_greek_regular(self):
        self.assertTrue(validate_email(r'θσερ@εχαμπλε.ψομ'))

        self.assertFalse(validate_email(r'θσερεχαμπλε.ψομ')) # No @
        self.assertFalse(validate_email(r'θσερ@εχαμπλεψομ')) # No .
        self.assertFalse(validate_email(r'θσερ@εχαμπλε.')) # Nothing after the .
        self.assertFalse(validate_email(r'@εχαμπλε.ψομ')) # Nothing before the @
Exemple #8
0
def parseAddresses(string_):
    string_ = decodeHeader(string_)
    string_ = string_.replace("\n", "").replace("\t", "")
    unparsed = ""
    # if string_.count("<") == string_.count(">") == 1:
    #     addresses_all=[re.findall(r"(.*) {0,1}<(.*?)>",string_)[0][::-1]]
    # elif string_.count("<") == string_.count(">") == 0 and string_.count("@") == 1:
    #     address=[part for part in string_.split() if "@" in part][0]
    #     name=" ".join([part for part in string_.split() if "@" not in part])
    #     addresses_all=[(address,name)]
    # else:
    candidates = re.split(r'''((?:[^,"']|"[^"]*"|'[^']*')+)''', string_)[1::2]  # ?? pra que isso?
    candidates = [i.strip() for i in candidates]
    addresses_all = []
    for candidate in candidates:
        if candidate.count("<") == candidate.count(">") > 0:
            # assume name <address> format
            name, address = re.findall(r"(.*) {0,1}<(.*?)>", candidate)[0]
        elif "@" in candidate:
            address = [part for part in candidate.split() if "@" in part][0]
            name = " ".join([part for part in candidate.split() if "@" not in part])
        else:
            unparsed += candidate
            address = ""
        if address:
            try:
                validate_email(address)
                addresses_all += [(address, name.strip().replace('"', '').replace("'", ""))]
            except:
                unparsed += candidate
    return addresses_all, unparsed
Exemple #9
0
    def parseParticipant(self,fromstring):
        fromstring=decodeHeader(fromstring)
#            fromstring="".join(i for i in str(fromstring) if i in string.printable)
        fromstring=fromstring.replace("\n","").replace("\t","")
        if ">" in fromstring and "<" not in fromstring:
            fromstring=re.sub(r"(.*[ ^]*)(.*>)",   r"\1<\2", fromstring)
            c("-|-|-|-| corrected fromstring:", fromstring)
        elif "<" in fromstring and ">" not in fromstring:
            fromstring=re.sub(r"(<.*)([ $]*.*)",   r"\1>\2", fromstring)
            c("-|-|-|-| corrected fromstring:", fromstring)
        if fromstring.count(">")==fromstring.count("<")>0:
            name,email=re.findall(r"(.*) {0,1}<(.*)>",fromstring)[0]
        elif "(" in fromstring:
            email,name=re.findall(r"(.*) {0,1}\((.*)\)",fromstring)[0]
        elif " " in fromstring:
            raise ValueError("new author field pattern")
        else:
            email=fromstring
            name=""
        email=email.replace("..",".")
        try:
            assert validate_email(email)
        except:
            if "cardecovil.co.kr" in email:
                email="*****@*****.**"
                name=""
            elif re.findall(r"(.*):(.*)",email):
                name,email=re.findall(r"(.*):(.*)",email)[0]
            else:
                raise ValueError("bad email")
        assert validate_email(email)
        return email,name.strip().replace("'","").replace('"','')
def main(argv):
    input_folder = ''
    input_email = ''

    try:
        opts, args = getopt.getopt(argv,"hf:e:",["ffolder=","eemail="])
    except getopt.GetoptError:
        print 'test.py -f <folder> -e <email>'
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print 'globus_share.py -f <folder> -e <email>'
            sys.exit()
        elif opt in ("-f", "--ffolder"):
            input_folder = arg
        elif opt in ("-e", "--eemail"):
            input_email = arg
    
    input_folder = os.path.normpath(input_folder) + os.sep # will add the trailing slash if it's not already there.
    if validate_email(input_email) and os.path.isdir(local_folder + input_folder):

        globus_add = "acl-add " + local_user + local_share1 + os.sep + input_folder  + " --perm r --email " + input_email
        cmd =  globus_ssh + " " + globus_add
        print cmd
        print "ssh [email protected] acl-add decarlo#data/test/ --perm r --email [email protected]"
        #os.system(cmd)
        print "Download link sent to: ", input_email
    else:
        print "ERROR: "
        print "EXAMPLE: python globus_local_share.py -f test -e [email protected]"
        if not validate_email(input_email):
            print "email is not valid ..."
        else:
            print local_folder + input_folder, "does not exists under the Globus Personal Share folder"
        gb.settings()
    def test_hindi_regular(self):
        self.assertTrue(validate_email(r'उपयोगकर्ता@उदाहरण.कॉम')) # Hindi

        self.assertFalse(validate_email(r'उपयोगकर्ताउदाहरण.कॉम')) # No @
        self.assertFalse(validate_email(r'उपयोगकर्ता@उदाहरणकॉम')) # No .
        self.assertFalse(validate_email(r'उपयोगकर्ता@उदाहरण.')) # Nothing after the .
        self.assertFalse(validate_email(r'@उदाहरण.कॉम')) # Nothing before the @
Exemple #12
0
def share(directory, email, mode):
    """
    Send a token e-mail to share a directory under the local or remote Globus Endpoint

    Parameters
    ----------
    directory : str
        Full directory path under the Globus Shared Endpoint

    email : email
        User e-mail address

    mode : str
        local, remote. Shared folder is on local/remote Endpoint 

    Returns
    -------
    cmd : str 
        Globus Command Line string. If executed with os.system() 
        will send notification e-mail to users         
    """

    home = expanduser("~")
    globus = os.path.join(home, 'globus.ini')
    cf = ConfigParser.ConfigParser()
    cf.read(globus)
    globus_address = cf.get('settings', 'cli_address')
    globus_user = cf.get('settings', 'cli_user')
    globus_ssh = "ssh " + globus_user + globus_address

    if mode == 'local':
        user = cf.get('globus connect personal', 'user')
        share = cf.get('globus connect personal', 'share')
        folder = cf.get('globus connect personal', 'folder')

        if os.path.isdir(folder + directory) and validate_email(email):
            globus_add = "acl-add " + user + share + os.sep + \
                directory + " --perm r --email " + email
            cmd = globus_ssh + " " + globus_add
            return cmd
        else:
            if not validate_email(email):
                return -1
            else:
                return -2

    elif mode == 'remote':
        user = cf.get('globus remote server', 'user')
        share = cf.get('globus remote server', 'share')
        folder = cf.get('globus remote server', 'folder')

        if validate_email(email):
            globus_add = "acl-add " + user + share + os.sep + \
                directory + " --perm r --email " + email
            cmd = globus_ssh + " " + globus_add
            return cmd
        else:
            return -1
def get_defaults():
    """Get default parameters and setting.
    These setting are pre-defined for common analysis. For an alternate setup, generate \"RNAseq_pipeline_defaults.txt\" under home folder and/or run path.
    Pre-defined parameters are superseded by \"RNAseq_pipeline_defaults.txt\" file under home path and that, in turn, is superseded by the one under run path.
    """

    # get package defaults
    with open(os.path.join(iLoop_RNAseq_pipeline.__path__[0], 'defaults', 'RNAseq_pipeline_defaults.txt')) as rpd:
        defaults = {}
        for line in rpd.readlines():
            if line.strip():
                defaults[line.split(',')[0].strip()] = line.split(',')[1].strip()

    try:
        with open(os.path.join(os.path.expanduser("~"), 'RNAseq_pipeline_defaults.txt')) as rpd:
            for line in rpd.readlines():
                if line.strip():
                    defaults[line.split(',')[0].strip()] = line.split(',')[1].strip()
    except FileNotFoundError:
        logger.warning('"RNAseq_pipeline_defaults.txt" does not exist under home path. An email address and project ID should be should be define in that file.')

    # replace with user defaults
    try:
        with open('RNAseq_pipeline_defaults.txt') as rpd:
            for line in rpd.readlines():
                if line.strip():
                    defaults[line.split(',')[0].strip()] = line.split(',')[1].strip()
    except FileNotFoundError:
        logger.info(
            '"RNAseq_pipeline_defaults.txt" does not exist under this folder. Defaults from the package and home path will be used.')

    if 'email' not in defaults:
        if not validate_email(defaults['email']):
            while True:
                email = input('Enter a valid email address for job status: \n')
                if validate_email(email):
                    defaults['email'] = email
                    print('Writing email to "RNAseq_pipeline_defaults.txt" under home path.')
                    f = open(os.path.join(os.path.expanduser("~"), 'RNAseq_pipeline_defaults.txt'), 'w+')
                    f.write('\nemail,{}'.format(email))
                    f.close()
                    break
                else:
                    print('{} is not valid, try again.'.format(email))

    if ('project' not in defaults) or (defaults['project'] == 'projectid'):
        project = input('Enter Computerome project ID for billing: \n')
        # TODO It is possible to validate this by checking folder name under "/home/projects".
        defaults['project'] = project
        print('Writing project ID to "RNAseq_pipeline_defaults.txt" under home path.')
        f = open(os.path.join(os.path.expanduser("~"), 'RNAseq_pipeline_defaults.txt'), 'w+')
        f.write('\nproject,{}'.format(project))
        f.close()

    return defaults
Exemple #14
0
def sendRequestEmailWithSES(requestername, requesteremail, tool, particulars,
                            senderemail=app.config['REQUEST_EMAIL_SENDEREMAILADDRESS'],
                            recepientemail=app.config['REQUEST_EMAIL_RECEPIENTEMAILADDRESS']):
    """
    Formats and sends the particulars of a request for access as an email
    to the Zen Desk intake email address using Amazon's Simple Email Service. By default
    the from address will come from the configuration file.

    See https://boto.readthedocs.org/en/latest/ses_tut.html#verifying-a-sender-email-address for
    sender email verification SES process to allow AWS message to send messages from the specified
    address

    """

    # P Make sure the email addresses look good
    if not validate_email(requesteremail):
        raise ValueError("Requester email '%s' is not valid" % requesteremail)
    if not validate_email(senderemail):
        raise ValueError("Sender email '%s' is not valid" % senderemail)
    if not validate_email(recepientemail):
        raise ValueError("Recepient email '%s' is not valid" % recepientemail)

    # P Get a connection to AWS
    #conn = boto.ses.connect_to_region(app.config['REQUEST_AWS_SES_REGION'],
    #                                  aws_access_key_id=app.config['REQUEST_AWS_SES_ACCESS_KEY_ID'],
    #                                  aws_secret_access_key=app.config['REQUEST_AWS_SES_SECRET_ACCESS_KEY'])
    conn = boto.ses.connect_to_region(app.config['REQUEST_AWS_SES_REGION'])

    # P Make sure the sender address has already been validated for sending by SES

    blessedSESaddresses = conn.list_verified_email_addresses()

    if senderemail not in blessedSESaddresses['ListVerifiedEmailAddressesResponse']['ListVerifiedEmailAddressesResult'][
        'VerifiedEmailAddresses']:
        raise ValueError("Sender email '%s' is not SES list of verified email addresses." % senderemail)

    # P OK, should be validated. Create the message
    msg = MIMEMultipart()

    msg['Subject'] = "Access Gossip request for access to %s by %s" % (tool, requestername)
    msg['From'] = senderemail
    msg['To'] = recepientemail

    body = ""
    for particular in particulars:
        body += "\n%s:%s" % (particular[0], particular[1])

    msg.attach(MIMEText(body))

    # P Send the message

    result = conn.send_raw_email(msg.as_string())

    return result if 'ErrorResponse' in result else ''
def validateInput(message_data):
    if not validate_email(message_data['to_email']):
        return FailResult("invalid recipient email")
    if not validate_email(message_data['from_email']):
        return FailResult("invalid sender email")
    if message_data['subject'] == "":
        return FailResult("plese input your subject")
    elif len(message_data['subject']) > MAX_SUBJECT_LENGTH:
        return FailResult("subject is too long, subject cannot be more than %s characters" % MAX_SUBJECT_LENGTH)
    if message_data['content'] == "":
        return FailResult("please input your content")
    elif len(message_data['content']) > MAX_CONTENT_LENGTH:
        return FailResult("content is too long, content cannot be more than %s characters" % MAX_CONTENT_LENGTH)
    def regUsers():
        global username, mejl

        username = request.forms.username
        mejl=request.forms.mejl
        password1=request.forms.password1
        password2=request.forms.password2

        if password1==password2:
            if is_valis= validate_email(mejl, check_mx=True):
            #här finns en mysql
                query('INSERT user(username, mejl, password1)' ' VALUES(%s,%s,%s)', (username, mejl, password1))
                return template("loggain", title=username, username=username, mejl=mejl, password1=password1,password2=password2)
def main(argv):
    input_folder = ''
    input_email = ''

    try:
        opts, args = getopt.getopt(argv,"hf:e:",["ffolder=","eemail="])
    except getopt.GetoptError:
        print 'test.py -f <folder> -e <email>'
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print 'globus_copy_share.py -f <folder> -e <email>'
            print 'copy data from globus connect personal ', local_user + local_share + os.sep + '<folder> to ' + remote_user + remote_share + os.sep + remote_folder
            print 'share data from', remote_user + remote_share + os.sep + remote_folder + "<folder>", ' with ' + "<email>"

            sys.exit()
        elif opt in ("-f", "--ffolder"):
            input_folder = arg
        elif opt in ("-e", "--eemail"):
            input_email = arg
    
    input_folder = os.path.normpath(input_folder) + os.sep # will add the trailing slash if it's not already there.

    path_list = remote_folder.split(os.sep)
    remote_data_share = path_list[len(path_list)-2] + os.sep + path_list[len(path_list)-1]


    globus_scp = "scp -r " + local_user + local_share1 + ":" + os.sep + input_folder + " " + remote_user + remote_share + ":" + os.sep + remote_data_share
    globus_add = "acl-add " + local_user + local_share2  + os.sep + input_folder + " --perm r --email " + input_email
    if validate_email(input_email) and os.path.isdir(local_folder + input_folder):
        cmd_1 = globus_ssh + " " + globus_scp
        cmd_2 = globus_ssh + " " + globus_add
        print cmd_1
        print "ssh [email protected] scp -r decarlo#data:/test/ petrel#tomography:/img/"
        #os.system(cmd1)
        print "Done data trasfer to: ", remote_user
        #os.system(cmd2)
        print cmd_2
        print "ssh [email protected] acl-add decarlo#img/test/ --perm r --email [email protected]"
        print "Download link sent to: ", input_email
    else:
        print "ERROR: "
        print "EXAMPLE: python globus_copy_remote_share.py -f test -e [email protected]"

        if not validate_email(input_email):
            print "email is not valid ..."
        else:
            print local_folder + input_folder, "does not exists under the Globus Personal Share folder"
        gb.settings()
Exemple #18
0
def start():
    white_email = flask.request.form["white_email"]
    white_is_valid = validate_email.validate_email(white_email)
    black_email = flask.request.form["black_email"]
    black_is_valid = validate_email.validate_email(black_email)
    if not white_is_valid or not black_is_valid:
        print "Bad email addresses; %s (%s) %s (%s)" % (
            white_email, white_is_valid, black_email, black_is_valid)
        flask.abort(400)
    white_link, black_link, _, _ = rstore.start_game(white_email, black_email)
    white_url = utils.to_game_url(white_link)
    black_url = utils.to_game_url(black_link)
    emails.send_welcome(white_email, white_url, black_email)
    emails.send_welcome(black_email, black_url, white_email)
    return flask.redirect(flask.url_for("getready"))
Exemple #19
0
    def itervoters(self):
        if self.voter_file_content:
            if type(self.voter_file_content) == unicode:
                content = self.voter_file_content.encode('utf-8')
            else:
                content = self.voter_file_content

            # now we have to handle non-universal-newline stuff
            # we do this in a simple way: replace all \r with \n
            # then, replace all double \n with single \n
            # this should leave us with only \n
            content = content.replace('\r', '\n').replace('\n\n', '\n')

            voter_stream = io.BytesIO(content)
        else:
            voter_stream = open(self.voter_file.path, "rU")

        #reader = unicode_csv_reader(voter_stream)
        reader = unicodecsv.reader(voter_stream, encoding='utf-8')

        for voter_fields in reader:
            # bad line
            if len(voter_fields) < 1:
                continue

            return_dict = {'voter_id': voter_fields[0].strip()}

            if len(voter_fields) > 1:
                if validate_email(voter_fields[1].strip()):
                    return_dict['email'] = voter_fields[1].strip()
                else:
                    return_dict['name'] = voter_fields[1].strip()
            else:
                # assume single field means the email is the same field
                return_dict['email'] = voter_fields[0].strip()

            if len(voter_fields) > 2:
                if validate_email(voter_fields[1].strip()):
                    return_dict['name'] = voter_fields[2].strip()
                else:
                    return_dict['user_type'] = voter_fields[2].strip()
            else:
                return_dict['name'] = return_dict['email']

            if len(voter_fields) > 3:
                return_dict['user_type'] = voter_fields[3].strip()

            yield return_dict
Exemple #20
0
def main():
    if len(sys.argv) < 2:
        print 'Usage : ./checkem.py file.csv'
        sys.exit()
    
    filename = sys.argv[1];

    with open(filename.split('.csv')[0] + '_export.csv', 'w') as csvfile:
        fieldnames = ['email', 'valid']
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
        writer.writeheader()

        with open(sys.argv[1], "rb") as f:
            reader = csv.reader(f, delimiter="\t")

            for i, line in enumerate(reader):
                email = line[0]
                
                try : 
                    is_valid = validate_email(email,verify=True)
                except : 
                    is_valid = True

                writer.writerow({'email': email, 'valid': str(is_valid)})
                print email + ' => ' + str(is_valid)
Exemple #21
0
def loguser(request):
	if not request.user.is_anonymous():
		if request.user.account.type_acount == 'powergym':
			return HttpResponseRedirect(reverse('load_list'))
		#if request.user.account.validity <= datetime.now().date():
			#return HttpResponseRedirect(reverse('payment'))
		#else:
			#return HttpResponseRedirect(reverse('index'))
		return HttpResponseRedirect(reverse('index'))
	message_username = ''
	if request.method == "POST":
		if 'username' in request.POST:
			username = request.POST.get('username')
			password = request.POST.get('password')
			if validate_email(username):
				username_ = User.objects.get(email=username).username
				if not username_:
					message_username = '******'
				else:
					username = username_
			if not message_username:
				access = authenticate(username=username, password=password)
				if access:
					login(request, access)
					return HttpResponseRedirect(reverse('loguser'))
				else:
					message_username = '******'
	return render(request, 'app/login.html',locals())
Exemple #22
0
    def create(self, request):        
        serializer = self.serializer_class(data=request.data)

        if serializer.is_valid():
            try:
                # Check username
                if not re.match("^[a-z]*$", serializer.validated_data.get('username').lower()):
                    return Response({
                        'status': 'Bad request',
                        'message': 'Account could not be created with received data.',
                        'data' : {'error' : 'Repository name should be composed of letters only.'}
                    }, status=status.HTTP_400_BAD_REQUEST)

                # Check email
                if validate_email(serializer.validated_data.get('email')):
                    return Response({
                        'status': 'Bad request',
                        'message': 'Account could not be created with received data.',
                        'data' : {'error' : 'Invalid email.'}
                    }, status=status.HTTP_400_BAD_REQUEST)

                serializer.validated_data['username'] = serializer.validated_data.get('username').lower()
                User.objects.create_user(**serializer.validated_data)
                return Response(serializer.validated_data, status=status.HTTP_201_CREATED)
            except Exception as error:
                return Response({"Error" : error}, status=500)

        return Response({
            'status': 'Bad request',
            'message': 'Account could not be created with received data.',
            'data' : serializer.errors
        }, status=status.HTTP_400_BAD_REQUEST)
Exemple #23
0
def list_detail(request, id, slug):
	subscriberslist = Subscriberslist.objects.get(slug=slug, id=id)
	subscribers = Subscribers.objects.filter(subscriberslist = subscriberslist, delete=False)

	form = SubscribersForm()
	form_import = Import_Form()
	if request.method == "POST":
		if 'delete_subscriber' in request.POST:
			subscriber = all_send
			Subscribers.objects.filter(id = subscriber).delete()
			return HttpResponse(json.dumps({
				"success": "Se eliminó el suscriptor",
				"subscribers":subscriberslist.subscribers(),
				"unsubscribers":subscriberslist.unsubscribers(),
				"total":subscriberslist.total(),
				"actives":subscriberslist.actives(),
				}), content_type="application/json")
		if 'change_subscriber' in request.POST:
			subscriber = request.POST.get('subscriber')
			subscriber = Subscribers.objects.get(id = subscriber)
			subscriber.is_subscribe = not(subscriber.is_subscribe)
			if not subscriber.is_subscribe:
				subscriber.unsubscribe_date = datetime.now()
			subscriber.save()
			return HttpResponse(json.dumps({
				"success": "Se edito la suscripción",
				"subscribers":subscriberslist.subscribers(),
				"unsubscribers":subscriberslist.unsubscribers(),
				"total":subscriberslist.total(),
				"actives":subscriberslist.actives(),
				}), content_type="application/json")
		if 'save_subscribers' in request.POST:
			name = request.POST.get('name')
			email = request.POST.get('email')
			edit = request.POST.get('edit')
			if not validate_email(email):
				return HttpResponse(json.dumps({"error": "El email no es valido!"}), content_type="application/json")
			if edit:
				if Subscribers.objects.filter(subscriberslist = subscriberslist, delete=False, email=email).exclude(id=edit):
					return HttpResponse(json.dumps({"error": "Este correo ya existe en esta lista!"}), content_type="application/json")
				subscriber = Subscribers.objects.get(id=edit)
				subscriber.name = name
				subscriber.email = email
				subscriber.save()
				return HttpResponse(json.dumps({"success": "Se editó el suscriptor!","subscribers":subscriberslist.subscribers(),"unsubscribers":subscriberslist.unsubscribers(),"total":subscriberslist.total(),"actives":subscriberslist.actives(),}), content_type="application/json")
			if Subscribers.objects.filter(subscriberslist = subscriberslist, delete=False, email=email):
				return HttpResponse(json.dumps({"error": "Este correo ya existe en esta lista!"}), content_type="application/json")
			subscribers = Subscribers()
			subscribers.name = name
			subscribers.email = email
			subscribers.subscriberslist = subscriberslist
			subscribers.save()
			return HttpResponse(json.dumps({
				"success": "Se guardo el suscriptor con éxito!",
				"subscribers":subscriberslist.subscribers(),
				"unsubscribers":subscriberslist.unsubscribers(),
				"total":subscriberslist.total(),
				"actives":subscriberslist.actives(),
				}), content_type="application/json")
	return render(request, 'app/list_detail.html',locals())
    def _worker(self, name):
        LOG.debug("new thread started: %s" % name)
        while True:
            try:
                email = self._inQ.get(True, self.THREAD_IDLE_SEC)
            except Empty:
                break
            check_value = self.validate_from_cache(email)
            if check_value is None:
                for i in range(self.VALIDATION_ATTEMPTS):
                    # long I/O bound operation
                    try:
                        check_value = validate_email(email, verify=True,
                                                     verbose=True)
                    except:
                        check_value = False
                    if check_value:
                        break

                self._outputObjLock.acquire()
                now = time.time()
                getattr(self._outputObj, self._storage_name)[email] = (check_value, now)
                transaction.commit()
                self._outputObjLock.release()
            self._inQ.task_done()
        self._workersLock.acquire()
        self._workers[name]['running'] = False
        self._workersLock.release()
        LOG.debug("thread exits after %d seconds idle: %s" % (self.THREAD_IDLE_SEC, name))
        self._workerCountSemaphore.release()
def posturl():
	post_request = request.json
	if post_request is None:
		response = jsonify({'status': 412, 'error': 'what'})
		response.code = 412
		return response
	if 'email' not in post_request:
		response = jsonify({'status': 412, 'error': 'no email provided'})
		response.code = 412
		return response
	elif validate_email(post_request['email']) is not True:
		response = jsonify({'status': 412, 'error': 'not a valid email'})
		response.code = 412
		return response
	emaillower = post_request['email'].lower().strip()
	user = User.query.filter_by(email=emaillower).first()
	if not user:
		user = User(email=emaillower,created_date =datetime.utcnow())
		db.session.add(user)
		db.session.commit()
	url = Url(created_date=datetime.utcnow(), url=post_request['url'], user_id=user.id)
	db.session.add(url)
	db.session.commit()

	return jsonify({'status': 200, 'email': user.email, 'url': url.url})
Exemple #26
0
def devices_get():
    '''This method is only intended for devices with a "long"
    ID to check if they are registered'''

    device_type = request.args.get('tipo', '').strip()
    device_id = request.args.get('id', '').strip()
    delete_flag = request.args.get('borrar', '0')

    # Avoid getting emails database using bruteforce
    if '' in [device_type, device_id] or (device_type == 'email' and delete_flag == '0'):
        return json_response([], 404)

    devices = Device.get(mongo_db, device_type, device_id)

    if len(devices) == 0:
        return json_response(devices, 404)

    if delete_flag == '1':
        # Only emails allowed to do this
        if device_type == 'email' and validate_email(device_id):
            Device.delete_one(mongo_db, devices[0])
            devices[0]['mensaje'] = 'El dispositivo ha sido borrado con éxito'
        else:
            return json_response([], 400)

    return json_response(devices[0:1])
Exemple #27
0
def validate_emails(emails_to_parse):
    emails, bad_emails = [], []
    for email in emails_to_parse.split(','):
        email = email.strip()
        target = emails if validate_email(email) else bad_emails
        target.append(email)
    return emails, bad_emails
Exemple #28
0
def send_post_data(path):
    path_is_valid_email = validate_email(path, verify=True)
    if path_is_valid_email:
        send_email(path, request.data)
        return request.data
    else:
        return "Specified email address {} is not valid.".format(path)
Exemple #29
0
def sanitizeChangeUserInfoData(rdata):
    firstname = rdata.get("firstname", "")
    lastname = rdata.get("lastname", "")
    email = rdata.get("email", None)
    dob = rdata.get("dob", "")
    sex = rdata.get("sex", "")
    cellphone = rdata.get("cellphone", "")
    driver = rdata.get("driverOrNot", 0)
    resp = {"errCode":SUCCESS}
    try:
      u = User.objects.get(email =email)
      resp["errCode"] = ERR_USER_EXISTS
    except User.DoesNotExist:
      #validate not null and not too long firstname
      if(not firstname or len(firstname)> MAX_LENGTH_FIRST_LAST_PASS):
        resp["errCode"] = ERR_BAD_INPUT_OR_LENGTH
      #validate not null and not too long lastname
      if(not lastname or len(lastname)> MAX_LENGTH_FIRST_LAST_PASS):
        resp["errCode"] = ERR_BAD_INPUT_OR_LENGTH
      is_valid = validate_email(email)
      if not is_valid:
        resp["errCode"] = ERR_BAD_EMAIL

      #validate gooe date of birth
      #dob format mm-dd-yyyy e.g 04-17-1992
      try:
        datetime.strptime("".join(dob.split("-")),'%m%d%Y').date()
      except ValueError,SyntaxError:
        resp["errCode"] = ERR_BAD_INPUT_OR_LENGTH
      #validate sex
      if sex not in sex_list:
        resp["errCode"] = ERR_BAD_INPUT_OR_LENGTH
      #validate if driver boolean type
      if (type(driver) is not int) and (driver not in [0,1]):
        resp["errCode"] = ERR_BAD_INPUT_OR_LENGTH
Exemple #30
0
    def validate_recovery_email(cls, email):
        """
        provided email has to pass the validations below,
        otherwise this func will raise an error
        @:arg email: string
        """

        #  1. is email well-formed ?
        if not validate_email(email):
            raise ValueError("recovery email malformed")

        # 2. is email already in our db ? (recovery_email must be unique)
        try:
            UserRecoveryEmail.get(email)
        except NotFound:
            pass
        else:
            raise ValueError("recovery email already used in this instance")

        # 3. is email belonging to one of our domains ?
        #  (recovery_email must be external)
        domain = email.split("@")[1]
        if domain in Configuration("global").get("default_domain"):
            raise ValueError(
                "recovery email must be outside of this domain instance")
Exemple #31
0
def send_messages(user, action, subject, email_column, from_email,
                  cc_email_list, bcc_email_list, send_confirmation, track_read,
                  exclude_values, log_item):
    """
    Sends the emails for the given action and with the
    given subject. The subject will be evaluated also with respect to the
    rows, attributes, and conditions.

    The messages are sent in bursts with a pause in seconds as specified by the
    configuration variables EMAIL_BURST  and EMAIL_BURST_PAUSE

    :param user: User object that executed the action
    :param action: Action from where to take the messages
    :param subject: Email subject
    :param email_column: Name of the column from which to extract emails
    :param from_email: Email of the sender
    :param cc_email_list: List of emails to include in the CC
    :param bcc_email_list: List of emails to include in the BCC
    :param send_confirmation: Boolean to send confirmation to sender
    :param track_read: Should read tracking be included?
    :param exclude_values: List of values to exclude from the mailing
    :param log_item: Log object to store results
    :return: Send the emails
    """

    # Evaluate the action string, evaluate the subject, and get the value of
    # the email column.
    result = evaluate_action(action,
                             extra_string=subject,
                             column_name=email_column,
                             exclude_values=exclude_values)

    # Check the type of the result to see if it was successful
    if not isinstance(result, list):
        # Something went wrong. The result contains a message
        return result

    track_col_name = ''
    data_frame = None
    if track_read:
        data_frame = pandas_db.load_from_db(action.workflow.id)
        # Make sure the column name does not collide with an existing one
        i = 0  # Suffix to rename
        while True:
            i += 1
            track_col_name = 'EmailRead_{0}'.format(i)
            if track_col_name not in data_frame.columns:
                break

        # Get the log item payload to store the tracking column
        log_item.payload['track_column'] = track_col_name
        log_item.save()

    # Update the number of filtered rows if the action has a filter (table
    # might have changed)
    cfilter = action.get_filter()
    if cfilter and cfilter.n_rows_selected != len(result):
        cfilter.n_rows_selected = len(result)
        cfilter.save()

    # Set the cc_email_list and bcc_email_list to the right values
    if not cc_email_list:
        cc_email_list = []
    if not bcc_email_list:
        bcc_email_list = []

    # Check that cc and bcc contain list of valid email addresses
    if not all([validate_email(x) for x in cc_email_list]):
        return _('Invalid email address in cc email')
    if not all([validate_email(x) for x in bcc_email_list]):
        return _('Invalid email address in bcc email')

    # Everything seemed to work to create the messages.
    msgs = []
    track_ids = []
    for msg_body, msg_subject, msg_to in result:

        # If read tracking is on, add suffix for message (or empty)
        if track_read:
            # The track id must identify: action & user
            track_id = {
                'action': action.id,
                'sender': user.email,
                'to': msg_to,
                'column_to': email_column,
                'column_dst': track_col_name
            }

            track_str = \
                """<img src="https://{0}{1}{2}?v={3}" alt="" 
                    style="position:absolute; visibility:hidden"/>""".format(
                    Site.objects.get_current().domain,
                    ontask_settings.BASE_URL,
                    reverse('trck'),
                    signing.dumps(track_id)
                )
        else:
            track_str = ''

        # Get the plain text content and bundle it together with the HTML in
        # a message to be added to the list.
        text_content = html2text.html2text(msg_body)
        msg = EmailMultiAlternatives(msg_subject,
                                     text_content,
                                     from_email, [msg_to],
                                     bcc=bcc_email_list,
                                     cc=cc_email_list)
        msg.attach_alternative(msg_body + track_str, "text/html")
        msgs.append(msg)
        track_ids.append(track_str)

    # Add the column if needed (before the mass email to avoid overload
    if track_read:
        # Create the new column and store
        column = Column(
            name=track_col_name,
            description_text='Emails sent with action {0} on {1}'.format(
                action.name, str(timezone.now())),
            workflow=action.workflow,
            data_type='integer',
            is_key=False,
            position=action.workflow.ncols + 1)
        column.save()

        # Increase the number of columns in the workflow
        action.workflow.ncols += 1
        action.workflow.save()

        # Initial value in the data frame and store the table
        data_frame[track_col_name] = 0
        ops.store_dataframe_in_db(data_frame, action.workflow.id)

    # Partition the list of emails into chunks as per the value of EMAIL_BURST
    chunk_size = len(msgs)
    wait_time = 0
    if ontask_settings.EMAIL_BURST:
        chunk_size = ontask_settings.EMAIL_BURST
        wait_time = ontask_settings.EMAIL_BURST_PAUSE
    msg_chunks = [
        msgs[i:i + chunk_size] for i in range(0, len(msgs), chunk_size)
    ]
    for idx, msg_chunk in enumerate(msg_chunks):
        # Mass mail!
        try:
            connection = mail.get_connection()
            connection.send_messages(msg_chunk)
        except Exception as e:
            # Something went wrong, notify above
            return str(e)

        if idx != len(msg_chunks) - 1:
            logger.info(
                'Email Burst ({0}) reached. Waiting for {1} secs'.format(
                    len(msg_chunk), wait_time))
            sleep(wait_time)

    # Log the events (one per email)
    now = datetime.datetime.now(pytz.timezone(ontask_settings.TIME_ZONE))
    context = {
        'user': user.id,
        'action': action.id,
        'email_sent_datetime': str(now),
    }
    for msg, track_id in zip(msgs, track_ids):
        context['subject'] = msg.subject
        context['body'] = msg.body
        context['from_email'] = msg.from_email
        context['to_email'] = msg.to[0]
        if track_id:
            context['track_id'] = track_id
        Log.objects.register(user, Log.ACTION_EMAIL_SENT, action.workflow,
                             context)

    # Update data in the log item
    log_item.payload['objects_sent'] = len(result)
    log_item.payload['filter_present'] = cfilter is not None
    log_item.payload['datetime'] = str(
        datetime.datetime.now(pytz.timezone(ontask_settings.TIME_ZONE)))
    log_item.save()

    # If no confirmation email is required, done
    if not send_confirmation:
        return None

    # Creating the context for the confirmation email
    context = {
        'user': user,
        'action': action,
        'num_messages': len(msgs),
        'email_sent_datetime': now,
        'filter_present': cfilter is not None,
        'num_rows': action.workflow.nrows,
        'num_selected': cfilter.n_rows_selected if cfilter else -1
    }

    # Create template and render with context
    try:
        html_content = Template(str(getattr(settings,
                                            'NOTIFICATION_TEMPLATE'))).render(
                                                Context(context))
        text_content = strip_tags(html_content)
    except TemplateSyntaxError as e:
        return _('Syntax error detected in OnTask notification template '
                 '({0})').format(e)

    # Log the event
    Log.objects.register(
        user, Log.ACTION_EMAIL_NOTIFY, action.workflow, {
            'user': user.id,
            'action': action.id,
            'num_messages': len(msgs),
            'email_sent_datetime': str(now),
            'filter_present': cfilter is not None,
            'num_rows': action.workflow.nrows,
            'subject': str(getattr(settings, 'NOTIFICATION_SUBJECT')),
            'body': text_content,
            'from_email': str(getattr(settings, 'NOTIFICATION_SENDER')),
            'to_email': [user.email]
        })

    # Send email out
    try:
        send_mail(str(getattr(settings, 'NOTIFICATION_SUBJECT')),
                  text_content,
                  str(getattr(settings, 'NOTIFICATION_SENDER')), [user.email],
                  html_message=html_content)
    except Exception as e:
        return _('An error occurred when sending your notification: '
                 '{0}').format(e)

    return None
 def is_email(cls, email):
     return validate_email(email)
Exemple #33
0
def register(request):
    if request.method == "POST":
        first_name = request.POST['FirstName'].rstrip()
        last_name = request.POST['LastName'].rstrip()
        username = request.POST['username'].rstrip()
        email = request.POST['email'].rstrip()
        password = request.POST['password']
        cpassword = request.POST['cpassword']
        if cpassword == password:
            # This means the passwords match now we check if the username is available
            try:
                is_valid = validate_email(email, verify=True)
                if is_valid is None:
                    messages.error(request,
                                   'Enter an email that really exists')
                    return redirect('register')
            except:
                messages.error(request, 'Enter a Valid Email Address')
                return redirect('register')
            user = User.objects.all().filter(username=username)
            if not user:
                user = User.objects.all().filter(email=email)
                if not user:
                    # We have a perfect registeration scenario
                    u = User.objects.create_user(email=email,
                                                 username=username,
                                                 password=password,
                                                 first_name=first_name,
                                                 last_name=last_name)
                    u.save()

                    # Simultaneously also creating a profile for the person so that we don't get any errors
                    profile_newUser = Profile(user=u)
                    profile_newUser.save()

                    # Send and email to the person
                    send_mail(
                        subject='Successful Registration',
                        message=
                        f"Thankyou {first_name} for registering with us here at BeLabs. Your username is {username}. We hope to see some great content that you put out...Have a great day!!",
                        from_email='*****@*****.**',
                        recipient_list=[email, '*****@*****.**'])

                    messages.success(
                        request,
                        'You\'ve been successfully registered. Login to continue...'
                    )
                    return redirect('login')
                else:
                    messages.error(request,
                                   'Email Id already used for registration')
                    return redirect('register')
            else:
                messages.error(request, 'Username already taken')
                return redirect('register')
        else:
            messages.error(request, 'Passwords don\'t match')
            return redirect('register')
    else:
        if request.user.is_authenticated:
            return redirect('dashboard')
        else:
            return render(request, 'Accounts/register.html')
Exemple #34
0
def val_email(email):
    return validate_email(email, verify=True)
def validate_affiliation_list(l, enumeration_type):
    errors = []
    warnings = []
    primary_count = 0
    max_values = {
        'purpose': 25,
        'affiliation_data_type': 10,
        'endpoint_data_type': 50,
        'affiliation_identifier': 1024,
        'endpoint': 1024,
        'description': 1024,
        'state': 2,
    }

    i = 0

    for d in l:

        affiliation_string = "Affiliation %s: " % (i)

        for k in max_values.keys():
            if d.get(k):
                if max_values[k] < len(
                    d.get(
                        k,
                        "").encode(
                        'ascii',
                        'ignore').decode('ascii')):
                    error = "%s : %s exceeds max allowable length of %s." % (
                        affiliation_string, k, max_values[k])
                    errors.append(error)

        # check for required information
        if d.get('purpose') not in AFFILIATION_PURPOSE:
            error = "%s purpose %s is not a valid value.  Valid values are %s." % (
                affiliation_string, d.get('purpose'), AFFILIATION_PURPOSE)
            errors.append(error)

        if d.get('affiliation_data_type') not in AFFILIATION_DATA_TYPE:
            error = "%s affiliation_data_type %s is not a valid value.  Valid values are %s." % (
                affiliation_string, d.get('affiliation_data_type'), AFFILIATION_DATA_TYPE)
            errors.append(error)

        if not str(d.get('affiliation_data_type')) and \
                d.get('purpose') not in AFFILIATION_PURPOSE:
            error = "%s affiliation_data_type %s is required when purpose is one of these %s" % (
                affiliation_string, d.get('affiliation_data_type'), AFFILIATION_PURPOSE)
            errors.append(error)

        if d.get('endpoint_data_type') and d.get(
                'endpoint_data_type') not in ENDPOINT_DATA_TYPE:
            error = "%s endpoint_data_type %s is not a valid value. Valid values are %s." % (
                affiliation_string, d.get('endpoint_data_type', ''), ENDPOINT_DATA_TYPE)
            errors.append(error)

        if d.get('purpose',
                 '') == "HIE-EXCHANGE" and not d.get('endpoint_data_type',
                                                     ''):
            error = "%s endpoint_data_type is required when the purpose is HIE-EXCHANGE." % \
                (affiliation_string)
            errors.append(error)

        if not d.get('affiliation_identifier', '') and \
                d.get('affiliation_data_type', '') in AFFILIATION_DATA_TYPE:
            error = "%s affiliation_identifier is required when affiliation_data_type is in %s." % (
                affiliation_string, AFFILIATION_DATA_TYPE)
            errors.append(error)

        if not d.get('endpoint') and d.get(
                'purpose') in ("HIE-EXCHANGE", "DOMAIN"):
            error = "%s endpoint is required when purpose is in %s." % \
                (affiliation_string, ("HIE-EXCHANGE", "DOMAIN"))
            errors.append(error)

        if d.get('accepting_new_patients', None) not in (True, False, None):
            error = "%s accepting_new_patients must be boolean. i.e. true or false." % (
                affiliation_string)
            errors.append(error)

        if d.get(
                'for_additional_documentation_request',
                None) not in (
                True,
                False,
                None):
            error = "%s for_additional_documentation_request must be boolean. i.e. true or false." % (
                affiliation_string)
            errors.append(error)

        if d.get('purpose') == "MEDICAID-NETWORK" and not d.get('state'):
            error = "%s state is required when purpose = MEDICIAD-NETWORK." % \
                (affiliation_string)
            errors.append(error)

        if d.get('state') and d.get('state') not in STATES:
            error = "%s state %s is not a valid value. Valid values are %s." % (
                affiliation_string, d.get('state'), STATES)
            errors.append(error)
        if d.get('affiliation_data_type') in ('NPI-1', 'NPI-2'):
            prefixed_number = "%s%s" % (
                LUHN_PREFIX, d['affiliation_identifier'])
            luhn_verified = verify(prefixed_number)
            if not luhn_verified:
                error = "The NPI affiliation_identifier %s did not pass Luhn algorithm check digit sanitiy check." % (d[
                                                                                                                      'affiliation_identifier'])
                errors.append(error)

        if d.get('endpoint_data_type') in (
            'DIRECT-EMAIL-ADDRESS',
                'REGULAR-EMAIL-ADDRESS'):
            is_valid = validate_email(d.get('endpoint'))
            if not is_valid:
                error = "%s %s has and endpoint_data_type of %s and is not a valid email." % (
                    affiliation_string, d.get('endpoint'), d.get('endpoint_data_type'))
                errors.append(error)

        i += 1
    retval = [errors, warnings]
    return retval
Exemple #36
0
    def patch(self):
        """
        ---
        description: Update user preferences
        requestBody:
          content:
            application/json:
              schema:
                type: object
                properties:
                  username:
                    type: string
                    description: |
                      User's preferred user name
                  first_name:
                    type: string
                    description: |
                      User's preferred first name
                  last_name:
                    type: string
                    description: |
                       User's preferred last name
                  contact_email:
                    type: string
                    description: |
                       User's preferred email address
                  contact_phone:
                    type: string
                    description: |
                       User's preferred (international) phone number
                  preferences:
                    schema: UpdateUserPreferencesRequestJSON
                    description: JSON describing updates to user preferences dict
        responses:
          200:
            content:
              application/json:
                schema: Success
          400:
            content:
              application/json:
                schema: Error
        """
        data = self.get_json()
        user = User.get_if_accessible_by(self.associated_user_object.id,
                                         self.current_user,
                                         mode="update")

        if data.get("username") is not None:
            username = data.pop("username").strip()
            if username == "":
                return self.error("Invalid username.")
            if len(username) < 5:
                return self.error(
                    "Username must be at least five characters long.")
            user.username = username

        if data.get("first_name") is not None:
            user.first_name = data.pop("first_name")

        if data.get("last_name") is not None:
            user.last_name = data.pop("last_name")

        if data.get("contact_phone") is not None:
            phone = data.pop("contact_phone")
            if phone not in [None, ""]:
                try:
                    if not phonenumbers.is_possible_number(
                            phonenumbers.parse(phone, "US")):
                        return self.error("Phone number given is not valid")
                except NumberParseException:
                    return self.error(
                        "Could not parse input as a phone number")
                user.contact_phone = phone
            else:
                user.contact_phone = None

        if data.get("contact_email") is not None:
            email = data.pop("contact_email")
            if email not in [None, ""]:
                if not validate_email(
                        email_address=email,
                        check_regex=True,
                        check_mx=False,
                        use_blacklist=True,
                        debug=False,
                ):
                    return self.error("Email does not appear to be valid")
                user.contact_email = email
            else:
                user.contact_email = None

        preferences = data.get("preferences", {})

        # Do not save blank fields (empty strings)
        for k, v in preferences.items():
            if isinstance(v, dict):
                preferences[k] = {
                    key: val
                    for key, val in v.items() if val != ""
                }
        user_prefs = deepcopy(user.preferences)
        if not user_prefs:
            user_prefs = preferences
        else:
            user_prefs = recursive_update(user_prefs, preferences)
        user.preferences = user_prefs

        try:
            self.verify_and_commit()
        except IntegrityError as e:
            if "duplicate key value violates unique constraint" in str(e):
                return self.error(
                    "Username already exists. Please try another username.")
            raise
        if "newsFeed" in preferences:
            self.push(action="skyportal/FETCH_NEWSFEED")
        if "topSources" in preferences:
            self.push(action="skyportal/FETCH_TOP_SOURCES")
        if "recentSources" in preferences:
            self.push(action="skyportal/FETCH_RECENT_SOURCES")
        if "sourceCounts" in preferences:
            self.push(action="skyportal/FETCH_SOURCE_COUNTS")
        return self.success(action="skyportal/FETCH_USER_PROFILE")
Exemple #37
0
async def get_user(request):
    """Protected for the user or superuser

    Request: POST /get_user
        Body :
            - user_token
            - service_token (json)
            - scope
            - user

    Response HTTP 200 in JWT token:
        {
            'roles': {
                'plone.Manager': 1
            },
            'groups': [
                'Group1'
            ],
            'name':
        }

    """
    request_data = await get_validate_request(request)
    scope = request_data.get('scope')
    username = request_data.get('username')

    params = await request.post()
    user = params.get('user', None)
    if user is None:
        raise HTTPBadRequest(reason='user is missing')
    if not validate_email(user):
        raise HTTPBadRequest(reason="user isn't a valid email address")

    if username != user:
        await check_manager(username, scope, request)  # !!important

    ttl = request.app['settings']['ttl_user_info']
    db_token = request.app['settings']['db_token']
    user_scope = '{0}::{1}'.format(user, scope)
    # Search Redis
    with (await db_token) as redis:
        result = await redis.get(user_scope)

    result = None
    if result is not None:
        result = ujson.loads(result)
    else:
        # Search LDAP
        user_manager = request.app['settings']['user_manager']
        result = await user_manager.getUserInfo(user, scope)
        if plone.oauth.is_superuser(user):
            # Add superadmins roles to scope
            result['roles']['plone.Manager'] = 1

        # Cache in redis
        with (await db_token) as redis:
            await redis.set(user_scope, ujson.dumps(result))
            await redis.expire(user_scope, ttl)

    token = jwt_response(request, result)
    return Response(body=token, content_type='text/plain')
Exemple #38
0
async def grant_user_scope_roles(request):
    """Request: POST /grant_scope_roles

        Body :
            - user_token
            - service_token (json)
            - scope
            - user
            - roles

    Response HTTP 200 in JWT token:
        success

    Response HTTP 400 in JWT token:
        entryAlreadyExists

    """
    # Verifiquem que la petició tingui tots els parametres
    request_data = await get_validate_request(request)
    scope = request_data.get('scope')
    username = request_data.get('username')

    # Verifiquem que l'usuari que vol realitzar l'acció és manager
    await check_manager(username, scope, request)  # !!important

    # Obtenim les dades del nou usuari que volem crear
    params = await request.post()
    user = params.get('user', None)
    if user is None:
        raise HTTPBadRequest(reason='user is missing')
    if not validate_email(user):
        raise HTTPBadRequest(reason="user isn't a valid email address")

    roles = params.get('roles', None)
    if roles is None:
        raise HTTPBadRequest(reason='roles is missing')
    if not isinstance(roles, list):
        roles = ast.literal_eval(roles)

    user_manager = request.app['settings']['user_manager']

    # Creem l'usuari al LDAP
    # Add user (only if user aren't exists)
    new_password = generate_password()
    result_user = user_manager.addUser(user, new_password)

    logging.info('Added user %s - %s' % (user, result_user))
    if result_user == 'success':
        pass
        # send mail
        # mailer = request.registry['mailer']
        # text_message = welcome_message.format(
        #     password=new_password,
        #     scope=scope,
        #     user=user)

        # logging.info('Sending mail to %s' % user)
        # message = Message(
        #     subject="[Intranetum] Welcome",
        #     sender="*****@*****.**",
        #     recipients=[user],
        #     body=text_message)
        # mailer.send_immediately(message, fail_silently=False)
    elif result_user != 'entryAlreadyExists':
        raise HTTPBadRequest(reason='user creation')

    # Assign the role to the user
    for role in roles:
        result_role = await user_manager.addScopeRoleUser(scope, user, role)

        if result_role == 'success':
            # Deshabilitem la cache redis per aquest camp
            db_token = request.app['settings']['db_token']
            user_scope = '{0}::{1}'.format(user, scope)
            with (await db_token) as redis:
                result_cache = await redis.delete(user_scope)

            status = 200
        elif result_role == 'attributeOrValueExists':
            status = 400
        else:
            raise HTTPBadRequest(reason='role assignation')

    token = jwt_response(request, result_role)
    return Response(status=status, body=token, content_type='text/plain')
Exemple #39
0
async def add_scope(request):
    """Request: POST /add_scope

        Body :
            - user_token
            - service_token
            - scope
            - admin_user

    Response HTTP 200 in JWT token:
        success

    Response HTTP 400 in JWT token:
        entryAlreadyExists

    """
    request_data = await get_validate_request(request)
    scope = request_data.get('scope')
    username = request_data.get('username')

    check_superuser(username)  # !!important

    # Obtenim el correu del l'administrador(Manager) del site
    params = await request.post()
    admin_user = params.get('admin_user', None)
    if admin_user is None:
        raise HTTPBadRequest(reason='admin_user is missing')
    if not validate_email(admin_user):
        raise HTTPBadRequest(reason="user isn't a valid email address")

    # Add LDAP Scope
    user_manager = request.app['settings']['user_manager']
    result = await user_manager.addScope(scope)

    if result == 'success':
        status = 200
    elif result == 'entryAlreadyExists':
        status = 400
        token = jwt_response(request, result)
        return Response(status=status, body=token, content_type='text/plain')
    else:
        raise HTTPBadRequest(reason='scope creation')

    # Add user (only if user aren't exists)
    new_password = generate_password()
    result_user = user_manager.addUser(admin_user, new_password)

    if result_user == 'success':
        pass
        # send mail
        # mailer = request.registry['mailer']
        # text_message = welcome_message.format(
        #     password=new_password,
        #     scope=scope,
        #     user=admin_user)
        # message = Message(
        #     subject="[Plone] Welcome manager user",
        #     sender="*****@*****.**",
        #     recipients=[admin_user],
        #     body=text_message)
        # mailer.send_immediately(message, fail_silently=False)
    elif result_user != 'entryAlreadyExists':
        raise HTTPBadRequest(reason='user creation')

    # Assign the manager role to the user
    result_role = await user_manager.addScopeRoleUser(scope, admin_user,
                                                      'manager')

    if result_role != 'success':
        raise HTTPBadRequest(reason='role assignation')

    token = jwt_response(request, result)
    return Response(status=status, body=token, content_type='text/plain')
Exemple #40
0
    def process_bind_param(self, value, dialect):
        if value and not validate_email(value):
            raise ValidationError('Email Validation Error {}'.format(value))

        return value
Exemple #41
0
    def post(self, request):
        context = {'data': request.POST, 'has_error': False}
        email = request.POST.get('email')
        password = request.POST.get('password')
        password2 = request.POST.get('password2')
        username = request.POST.get('username')
        firstname = request.POST.get('firstname')
        lastname = request.POST.get('lastname')

        if len(password) < 8:
            messages.add_message(request, messages.ERROR,
                                 'password must be at least 8 chars')
            context['has_error'] = True
        if password != password2:
            messages.add_message(request, messages.ERROR,
                                 'password doesnot match')
            context['has_error'] = True

        if not validate_email(email):
            messages.add_message(request, messages.ERROR,
                                 'provide a valid email')
            context['has_error'] = True

        if User.objects.filter(email=email).exists():
            messages.add_message(request, messages.ERROR,
                                 'Account with this email already exists')
            context['has_error'] = True

        if User.objects.filter(username=username).exists():
            messages.add_message(request, messages.ERROR,
                                 'Username with this email already exists')
            context['has_error'] = True

        if context['has_error']:
            return render(request, 'accounts/register.html', context)

        user = User.objects.create(username=username,
                                   email=email,
                                   first_name=firstname,
                                   last_name=lastname)
        user.set_password(password)
        user.is_active = False
        user.save()

        current_site = get_current_site(request)
        email_subject = 'Activate your account'
        message = render_to_string(
            'accounts/activate.html', {
                'user': user,
                'domain': current_site.domain,
                'uid': urlsafe_base64_encode(force_bytes(user.pk)),
                'token': generate_token.make_token(user)
            })
        email_msg = EmailMessage(
            email_subject,
            message,
            settings.EMAIL_HOST_USER,
            [email],
        )
        email_msg.send()

        return render(request, 'accounts/verify.html')
Exemple #42
0
    df1 = df1[df1["Create Date"] > three_months]
    N_after_removed_createdate = len(df1.index)
    N_createdate_removed = N_file - len(df1.index)

    # remove duplicate based on email address
    df1.sort_values("Email Address", inplace=True)
    df1["Email Address"] = df1["Email Address"].str.title()

    df1.drop_duplicates(subset="Email Address", keep="first", inplace=True)
    N_Duplicates_removed = len(df1.index)
    N_Duplicates = N_after_removed_createdate - N_Duplicates_removed

    # remove wired or invalid email address
    df1 = df1.astype({"Email Address": str})
    df1["is_valid_email"] = df1["Email Address"].apply(
        lambda x: validate_email(x))
    df1 = df1[df1["is_valid_email"]]
    N_Invalidemail_removed = N_Duplicates_removed - len(df1.index)

    # proper formate customers' first name and last name
    df1["Customer’s First Name"] = df1["Customer’s First Name"].str.title()
    df1["Customer’s Last Name"] = df1["Customer’s Last Name"].str.title()
    len(df1.index)

    # vlook up to match up with equipment type
    df2 = pd.read_csv(
        "\\\\adfs01.uhi.amerco\\interdepartment\\storagegroup\\Digital Marketing\\Emails\\One Month Free Email Campaign\\Documentation\\EquipmentCode.csv"
    )
    len(df2.index)

    df3 = df1.merge(df2, on="Equipment Model", how="left")
Exemple #43
0
# In[165]:

# Create new column 'age_on_platform' which has the corresponding value in date type format
user_data_to_clean["age_on_platform"] = user_data_to_clean["last_activity"] - user_data_to_clean["first_login"]



# #### Validate if email i'd is correctly formatted and the email i'd really exists

# In[167]:

from validate_email import validate_email

email_count_invalid = 0
for index, row in user_data_to_clean.iterrows():        
        if not validate_email(row.email): # , verify=True)  for checking if email i'd actually exits
            user_data_to_clean.drop(index, inplace=True)
            email_count_invalid = email_count_invalid + 1
            
print "Number of email-id invalid: %d" % (email_count_invalid)



# ### Remove duplicates

# In[169]:

user_data_to_deDuplicate = user_data_to_clean.copy()


# In[170]:
Exemple #44
0
"""
This is Just email slicer + Validation; That's All :)
"""
from validate_email import validate_email
import re

Email = input('Please Enter Your Email: ')
is_valid = validate_email(Email, verify=True)
if is_valid: print('Email is Correct')
else: print('Not Valid Email')

if is_valid:
    St = input('Do you want me slice it?(y or n) ')
    if St == 'y':
        ls = re.split('@', Email)
        print('Domain: {}'.format(ls[0]))
        print('Server: {}'.format(ls[1]))
Exemple #45
0
def Email(email):
    if email == None or email == "":
        return
    is_valid = validate_email(email)
    msg = "Validate Email: email \"" + email + "\" is valid"
    Util.log.running_logger.logResult("Email", msg, is_valid)
Exemple #46
0
    def post(self, request):
        context = {'data': request.POST, 'has_error': False}

        first_name = request.POST.get('first_name')
        last_name = request.POST.get('last_name')
        email = request.POST.get('email')
        password = request.POST.get('password')
        password2 = request.POST.get('password2')
        if len(password) < 6:
            messages.add_message(
                request, messages.ERROR,
                'passwords should be atleast 6 characters long')
            context['has_error'] = True
        if password != password2:
            messages.add_message(request, messages.ERROR,
                                 'passwords dont match')
            context['has_error'] = True

        if not validate_email(email):
            messages.add_message(request, messages.ERROR,
                                 'Please provide a valid email')
            context['has_error'] = True

        try:
            if User.objects.get(email=email):
                messages.add_message(
                    request, messages.ERROR,
                    'Email already registered by another user')
                context['has_error'] = True

        except Exception as identifier:
            pass

        if context['has_error']:
            return render(request,
                          'accounts/partials/register.html',
                          context,
                          status=400)

        user = User.objects.create_user(email=email, password=password)
        user.set_password(password)
        user.last_name = last_name
        user.is_active = False
        user.save()

        current_site = get_current_site(request)
        subject = 'Active your Account'
        message = render_to_string(
            'accounts/partials/account_activation_email.html', {
                'user': user,
                'domain': current_site.domain,
                'uid': urlsafe_base64_encode(force_bytes(user.pk)),
                'token': account_activation_token.make_token(user)
            })

        to_email = request.POST.get('email')
        email = EmailMessage(subject, message, to=[to_email])

        if not context['has_error']:
            email.send()
            messages.add_message(
                request, messages.SUCCESS,
                'We sent you an email to verify your account')
            #return render(request, 'accounts/partials/account_activation_sent.html')

        return redirect('accounts:login')
                change = True
        
        return (change, fail)

parser = argparse.ArgumentParser()
parser.add_argument('--port', default=ACME_CERT_PORT, help='What port to use to issue certs')
parser.add_argument('--email', default=CERT_EMAIL, help='What email to use to issue certs')
args = parser.parse_args()


if __name__ == '__main__':

    s = SetupSSL(fqdn=CERT_FQDN)

    try:
        if not validate_email(args.email):
            raise Exception()
    except:
        raise SetupSSLException("CERT_EMAIL: The provided email for the certificate, {}, is not valid".format(args.email))


    if CERT_FQDN != None:
        (success, domain, ip, my_ip) = s.points_to_me(CERT_FQDN)
        if not success:
            raise SetupSSLException("CERT_FQDN does not point to me.  CERT_FQDN={}, resolves to {}, my ip is {}".format(CERT_FQDN, ip, my_ip))
        log("")
        (change, fail) = s.get_le_cert(CERT_PATH, cert_email=args.email, expire_cutoff_days=CERT_EXPIRE_CUTOFF_DAYS, acme_cert_http_port=args.port)
    else:
        raise SetupSSLException("ERROR: CERT_FQDN environment variable not set")

     
Exemple #48
0
def verify(email_add):
    if (validate_email(email_add) and validate_email(email_add, check_mx=True)
            and validate_email(email_add, verify=True)):
        return True
    else:
        return False
Exemple #49
0
 def is_email_valid(email):
     return validate_email(email)
Exemple #50
0
 def validate_email_field(self, email):
     is_valid = validate_email(email)
     if not is_valid:
         self.is_valid = False
         self.error_message = f'email: {email} is not valid'
Exemple #51
0
c = 0
if stream:
    print(desc)
    while 1:
        paste = utilsy.get_paste()
        if paste:
            for link in paste:
                req = requests.get(link['scrape_url'])
                ##match = rule.match(data=req.content)
                splitted = req.text.splitlines()[0].split(":")
                print(link['scrape_url'])
                c = c + 1
                print(c)
                try:
                    if validate_email(splitted[0]) and splitted[1]:
                        username_domain_list = splitted[0].split('@')
                        if interactive:
                            interact = Interactive.Interactive()
                            print(Fore.GREEN + "Found email/pass leak")
                            print(link['scrape_url'])
                            print('-----------------------Found email ' +
                                  Fore.GREEN + splitted[0] + Fore.RESET +
                                  " with password " + Fore.RED +
                                  splitted[1].rstrip() + Fore.RESET +
                                  "-----------------------")
                            interactive(username_domain_list[1], splitted[0],
                                        splitted[1], config, elasticsearch)
                        else:
                            if 'google' in modules:
                                utilsy.check_google(splitted[0], splitted[1],
Exemple #52
0
def handle_text_with_payload(u_info, recipient_id, payload, message):
    if payload.startswith('/c'):
        seance_date = Parser.detect_time(message.encode('utf-8'))
        index_of_m, index_of_d = (payload.index('m'), payload.index('d'))
        cinema_id = payload[2:index_of_m]
        movie_id = (payload[index_of_m + 1:index_of_d])
        payloads = display_cinema_seances(recipient_id, cinema_id, movie_id,
                                          seance_date)

        text = _construct_payload(settings.DISCOUNT, recipient_id)
        update_last_callback(recipient_id)
        return [text] + payloads

    elif payload.startswith('seances'):
        if 'num' in payload:
            i_n = payload.index('num')
        else:
            return
        movie_id = payload[len('seances'):i_n]
        city_id = 1
        u_f = get_by_recipient_id(recipient_id)
        if u_f and u_f.cur_lat and u_f.cur_lng:
            l = {'latitude': u_f.cur_lat, 'longitude': u_f.cur_lng}
            city_id = detect_city_id_by_location(l)

        parser = Parser(message.encode('utf-8'), 'cinema', city_id=city_id)

        parser.parse()
        data = parser.data.place
        cinemas = []
        if not data:
            res = _construct_payload('К сожалению, мы ничего не нашли',
                                     recipient_id)
            return res
        for c in data:
            if not isinstance(c, dict):
                c = c.to_dict()

            c_info = _construct_cinema_movie_generic(c, movie_id)
            cinemas.append(c_info)
        payload = contruct_cinemas(recipient_id, cinemas, 10)
        payload = json.dumps(payload)
        update_last_callback(recipient_id)
        return payload

    elif payload.startswith('s_short'):
        seance_date = Parser.detect_time(message.encode('utf-8'))
        i_d = payload.index('d')
        movie_id = payload[len('s_short'):i_d]

        if u_info and u_info.cur_lat and u_info.cur_lng:
            payload = display_cinema_seances_short(recipient_id,
                                                   movie_id,
                                                   lat=u_info.cur_lat,
                                                   lng=u_info.cur_lng,
                                                   date=seance_date.date())
        else:
            payload = display_cinema_seances_short(recipient_id,
                                                   movie_id,
                                                   date=seance_date.date())
        return payload

    elif payload == 'bug':
        if len(message) > 2:
            u_info.bug_description = message
            u_info.last_callback = 'bug_email'
            u_info.put()

            resp = _construct_payload('Введите ваш email', recipient_id)
            return resp

        else:
            resp = _construct_payload('Опишите проблему', recipient_id)
            return resp

    elif validate_email(settings.uncd(message)):
        email = settings.uncd(message)
        u_info = get_by_recipient_id(recipient_id)

        if (u_info.last_callback == NO_AGAIN_CALLBACK
                or u_info.last_callback == NO_MAIL_SENDED_CALLBACK
                or u_info.last_callback == ANOTHER_PAY_ER_CALLBACK):
            last_callback = u_info.last_callback
            deferred.deffer(send_email, email, last_callback)
            our_spec = 'Наш специалист скоро свяжется с Вами'
            payload = _construct_payload(our_spec, recipient_id)

            return payload

        elif u_info.last_callback == 'bug_email':
            deferred.defer(send_email, email, u_info.bug_description)
            our_spec = 'Спасибо :)'
            payload = _construct_payload(our_spec, recipient_id)
            return payload

        else:
            payload = _construct_payload(settings.SORRY_I_DONT_UNDERSTAND,
                                         recipient_id)
            return payload

    else:
        payload = handle_text_message(recipient_id, message)
        return payload
Exemple #53
0
# pip install validate_email
# pip install pyDNS
from validate_email import validate_email

# basic
is_valid = validate_email('*****@*****.**')

# check for smtp server
is_valid2 = validate_email('*****@*****.**', check_mx=True)

# verify email exists
is_valid3 = validate_email('*****@*****.**', verify=True)
Exemple #54
0
    def post(self, request):
        context = {"data": request.POST, "has_error": False}

        email = request.POST.get("email")
        username = request.POST.get("username")
        full_name = request.POST.get("name")
        password = request.POST.get("password")
        password2 = request.POST.get("password2")
        if len(password) < 6:
            messages.add_message(
                request, messages.ERROR,
                "passwords should be atleast 6 characters long")
            context["has_error"] = True
        if password != password2:
            messages.add_message(request, messages.ERROR,
                                 "passwords dont match")
            context["has_error"] = True

        if not validate_email(email):
            messages.add_message(request, messages.ERROR,
                                 "Please provide a valid email")
            context["has_error"] = True

        try:
            if User.objects.get(email=email):
                messages.add_message(request, messages.ERROR, "Email is taken")
                context["has_error"] = True

        except Exception as identifier:
            pass

        try:
            if User.objects.get(username=username):
                messages.add_message(request, messages.ERROR,
                                     "Username is taken")
                context["has_error"] = True

        except Exception as identifier:
            pass

        if context["has_error"]:
            return render(request, "auth/register.html", context, status=400)

        user = User.objects.create_user(username=username, email=email)
        user.set_password(password)
        user.first_name = full_name
        user.last_name = full_name
        user.is_active = False
        user.save()

        current_site = get_current_site(request)
        email_subject = "Activate your Account."
        message = render_to_string(
            "auth/activate.html",
            {
                "user": user,
                "domain": current_site.domain,
                "uid": urlsafe_base64_encode(force_bytes(user.pk)),
                "token": generate_token.make_token(user),
            },
        )
        email_message = EmailMessage(email_subject, message,
                                     settings.EMAIL_HOST_USER, [email])

        email_message.send()

        messages.add_message(request, messages.SUCCESS,
                             "Registered user Successfully.")
        return redirect("login")
Exemple #55
0
from validate_email import validate_email

dataset = ['Valid Email '] = dataset['Email'].appy(lambda x:validate_email(x))
dataset['Verified Email'] = dataset['Email'].appy(lambda x:validate_email(x, verify = True))
Exemple #56
0
 def isEmailValid(self, email):
     return validate_email(str(email))
Exemple #57
0
def isEmailValid(email):
    is_valid = validate_email(email)

    return is_valid
Exemple #58
0
 def check_email(self, email):
     return validate_email(email)
Exemple #59
0
def valid_email(email):
    return validate_email(email)
Exemple #60
0
 def decorator(request, email, *args, **kwargs):
   if not validate_email.validate_email(email):
     raise stethoscope.exceptions.ValidationError("email address", email)
   return func(request, email, *args, **kwargs)