예제 #1
0
def signup_validator(fullname, username, email, password, password2):
    errors = []
    if email and checkers.is_email(email):
        check_email = User.query.filter_by(email=email).first()
        if not check_email:
            pass
        else:
            errors.append("An account is already registred with this email.")
    else:
        errors.append("Email is invalid.")
    if password and is_valid_password(password):
        if password2 is not None and password == password2:
            pass
        else:
            errors.append("Passwords do not match")
    else:
        errors.append("Password is invalid: must be 8 characters minimum and a mixture of both letters and numbers.")
    if fullname and checkers.is_string(fullname) and is_valid_fullname(fullname):
        pass
    else:
        errors.append("Fullname is invalid: must be three characters minimum and cannot have any special characters.")
    if username and checkers.is_string(username) and is_valid_username(username):
        check_username = User.query.filter_by(username=username).first()
        if not check_username:
            pass
        else:
            errors.append("This username is already taken. Please try another.") 
    else:
        errors.append("Username is invalid. Usernames must be 4 characters minimum and must have only letters, numbers, and/ or underscores")
    if len(errors) == 0:
        return True, errors
    if len(errors) > 0:
        return False, errors
예제 #2
0
    def post(self, id=None):
        if(id):
            return format_response("post not allowed", 405) 

        # Retrieve email from request body
        email = request.form.get("email")
        if(not email):
            return format_response("email not supplied", 400)

        # Check email is valid
        if(not is_email(email)):
            return format_response("invalid email", 422)

        # Checks if email is already registered by another user on the Database
        db_user = db.session.query(User).filter(User.email == email).first()
        if(db_user):
            return format_response("email already registered", 403)
        
        # Register new user
        user = User(email)
        db.session.add(user)
        db.session.commit()

        return make_response(
            jsonify({
                "id": user.id,
                "email": user.email
            }), 
            201
        )
예제 #3
0
def validate_user_registration_form(json: dict):
    try:
        username = json['username']
        username_valid = checkers.is_not_empty(
            username) and checkers.is_string(username) and checkers.has_length(
                username, minimum=1, maximum=20)
    except TypeError:
        username_valid = False
    try:
        password = json['password']
        password_valid = checkers.is_not_empty(
            password) and checkers.is_string(password) and checkers.has_length(
                password, minimum=1, maximum=128)
    except TypeError:
        password_valid = False
    try:
        email = json['email']
        email_valid = checkers.is_email(email)
    except TypeError:
        email_valid = False
    invalid_fields = []
    if not username_valid:
        invalid_fields.append(InvalidField('username', 'Invalid username'))
    if not password_valid:
        invalid_fields.append(InvalidField('password', 'Invalid password'))
    if not email_valid:
        invalid_fields.append(InvalidField('email', 'Invalid email'))
    if not (username_valid & password_valid & email_valid):
        raise InvalidForm(invalid_fields)
    return username, email, password
예제 #4
0
 def post(self):
     user_info = request.get_json()
     params = ['name', 'email', 'dateOfBirth']
     for i in user_info.keys():
         if i not in params:
             return {"msg": "invalid request"}
     if checkers.is_string(user_info['name']) == False \
         or checkers.is_email(user_info['email']) == False \
             or checkers.is_date(user_info['dateOfBirth']) == False:
         return {"msg": "invalid request"}, 400
     user_info["isDelete"] = False
     try:
         mongo.db.users.insert(user_info)
     except pymongo.errors.DuplicateKeyError:
         return {"msg": "email already exists"}
     return 'added user'
예제 #5
0
def signin_validator(email, password):
    errors = []
    if email and checkers.is_email(email):
        user_to_login = User.query.filter_by(email=email).first()
        if user_to_login:
            if user_to_login.check_password(password):
                pass
            else:
                errors.append("Password is incorrect.")
        else:
            errors.append("No account with this email exists.")
    else:
        errors.append("Email or password is invalid")
    if len(errors) == 0:
        return True, errors, user_to_login
    if len(errors) > 0:
        return False, errors, None
예제 #6
0
    def patch(self, id):
        user_info = request.get_json()
        if user_info.get('name'):
            if not checkers.is_string(user_info.get('name')):
                return {"msg": "invalid request"}, 400
        if user_info.get('email'):
            if not checkers.is_email(user_info.get('email')):
                return {"msg": "invalid request"}, 400

        if user_info.get('dateOfBirth'):
            if not checkers.is_date(user_info.get('dateOfBirth')):
                return {"msg": "invalid request"}, 400
        try:
            mongo.db.users.update({"_id": ObjectId(id)}, {"$set": user_info})
            return {"msg": 'updated user'}
        except pymongo.errors.DuplicateKeyError:
            return {"msg": "email already exists"}
        except Exception as e:
            return {"error": str(e)}
예제 #7
0
    def put(self, id=None):
        if(not id):
            return format_response("put not allowed", 405)

        # Check if supplied id complains with UUID standards
        if(not is_uuid(id)):
            return format_response("invalid id", 422)

        # Tries to retreive user by id
        user = db.session.query(User).filter(User.id == id).first()
        if(not user):
            return format_response("not found", 404)

        # Retrieve email from request body
        email = request.form.get("email")

        # Check email in body
        if(email):
            # Check email is valid
            if(not is_email(email)):
                return format_response("invalid email", 422)

            # Checks if email is already registered by another user on the Database
            db_user = db.session.query(User).filter(User.email == email).first()
            if(db_user):
                return format_response("email already registered", 403)
            
            # Updates the email
            user.email = email

        # Commit changes to the database
        db.session.commit()

        # Return the lasts state of the user entry
        return make_response(
            jsonify({
                "id": user.id,
                "email": user.email
            }), 
            200
        )
예제 #8
0
def entitlement():
    """
    This should be replaced with matching algorithm with human supervision in near future
    before GA. Currently this assumes manual input of entitlement data (from BD and sales team)
    before each POC.
    :return: list of matched "shop" along with potential commission information (to be consumed)
    """
    uid = flask.session['uid']
    user = auth.get_user(uid)
    influencer_email = user.email
    if not influencer_email or not checkers.is_email(influencer_email):
        logging.warning(f'Influencer {user} does not have valid email')
        response = flask.jsonify({'Status': 'Need valid email'})
        response.status_code = 422
        return response
    shops = sql_handler.get_campaign_entitlement(influencer_email)
    res = {
        individual_shop['shop']: individual_shop
        for individual_shop in shops
    }
    response = flask.jsonify(res)
    response.status_code = 200
    return response
예제 #9
0
def signup_validator(username, email, password):
    errors = list()
    if email and checkers.is_email(email):
        check_email = User.query.filter_by(email=email).first()
        if not check_email:
            pass
        else:
            errors.append("An account is already registred with this email.")
    else:
        errors.append("Email is invalid.")
    if username and checkers.is_string(username):
        user = User.query.filter(User.username==username).first()
        if user:
            errors.append("An account is already registered with this username.")
    if password and is_valid_password(password):
        pass
    else:
        errors.append("Password is invalid: must be 8 characters \
            minimum and a mixture of both letters and numbers.")
    if len(errors) == 0:
        return True, errors, user
    if len(errors) > 0:
        return False, errors, None
예제 #10
0
 def needs_tokenization(word):
     return "." in word and len(word) > 1 and not checkers.is_url(
         word) and not checkers.is_email(word)
예제 #11
0
 def validate_email(cls, v):
     if not checkers.is_email(v):
         raise TypeError('invalid email')
     return v
예제 #12
0
 def is_valid_email(self, input):
     return checkers.is_email(input)
예제 #13
0
def get_emails_for_company_name(mswitch, hostx, linkedin_username,
                                linkedin_password, company_name, company_id):
    exit = False
    cookies = authenticate(linkedin_username,
                           linkedin_password)  # perform authentication
    if company_id is 0:  # Don't find company id, use provided id from -cid or --companyid flag
        # code to get company ID based on name
        url = "https://www.linkedin.com/voyager/api/typeahead/hits?q=blended&query=%s" % company_name
        headers = {
            'Csrf-Token': 'ajax:0397788525211216808',
            'X-RestLi-Protocol-Version': '2.0.0'
        }
        cookies['JSESSIONID'] = 'ajax:0397788525211216808'
        r = requests.get(url, cookies=cookies, headers=headers)
        content = json.loads(r.text)
        firstID = 0
        for i in range(0, len(content['elements'])):
            try:
                company_id = content['elements'][i]['hitInfo'][
                    'com.linkedin.voyager.typeahead.TypeaheadCompany']['id']
                if firstID == 0:
                    firstID = company_id
                if mswitch.verbose is True:
                    print("[!] Found company ID: %s for %s" %
                          (company_id, company_name))
            except:
                continue
        company_id = firstID
        if company_id is 0:
            asm.cprint(
                "error",
                "No valid Company ID found, please provide a company ID instead.",
                1)
            return

    asm.cprint("info", "  [i] Using company ID: " + str(company_id), 1)
    url = "https://www.linkedin.com/voyager/api/search/cluster?count=40&guides=List(v->PEOPLE,facetCurrentCompany->%s)&origin=OTHER&q=guided&start=0" % (
        company_id)
    headers = {
        'Csrf-Token': 'ajax:0397788525211216808',
        'X-RestLi-Protocol-Version': '2.0.0'
    }
    cookies['JSESSIONID'] = 'ajax:0397788525211216808'
    r = requests.get(url, cookies=cookies, headers=headers)
    content = json.loads(r.text)
    data_total = content['elements'][0]['total']

    # Calculate pages off final results at 40 results/page
    pages = math.ceil(data_total / 40)
    if pages == 0:
        pages = 1
    if data_total % 40 == 0:
        # Because we count 0... Subtract a page if there are no left over results on the last page
        pages = pages - 1
    if pages == 0:
        if mswitch.verbose is True:
            asm.cprint(
                "info",
                "  [i] No employees for" + company_name + " " + company_id, 1)
        return

    print(Fore.WHITE + "  [" + Fore.GREEN + Style.BRIGHT + "!" +
          Style.RESET_ALL + Fore.WHITE + "] " + Fore.YELLOW + str(data_total) +
          " Employees Found")
    if data_total > 1000:
        pages = 25
        # print("[*] LinkedIn is capped to allow 1000 employees. More may be manually enumerated.")
    if mswitch.verbose is True:
        asm.cprint("info", "  [i] Fetching %s Pages" % str(pages), 1)

    for p in range(pages):
        url = "https://www.linkedin.com/voyager/api/search/cluster?count=40&guides=List(v->PEOPLE,facetCurrentCompany->%s)&origin=OTHER&q=guided&start=%i" % (
            company_id, p * 40)
        r = requests.get(url, cookies=cookies, headers=headers)
        content = r.text.encode('UTF-8')
        content = json.loads(content)

        if mswitch.verbose is True:
            sys.stdout.write(
                "\r[i] Fetching page %i/%i with %i results..." %
                ((p), pages, len(content['elements'][0]['elements'])))
            sys.stdout.flush()
        # code to get users, for each user with a picture create a person
        for c in content['elements'][0]['elements']:
            if 'com.linkedin.voyager.search.SearchProfile' in c['hitInfo'] and \
                    c['hitInfo']['com.linkedin.voyager.search.SearchProfile']['headless'] == False:
                try:
                    # Profile pic Link, LinkedIn profile Link and  Full Name
                    first_name = c['hitInfo'][
                        'com.linkedin.voyager.search.SearchProfile'][
                            'miniProfile']['firstName']
                    first_name = trans(first_name)
                    first_name = first_name.lower()
                    last_name = c['hitInfo'][
                        'com.linkedin.voyager.search.SearchProfile'][
                            'miniProfile']['lastName']
                    last_name = trans(last_name)
                    last_name = last_name.lower()

                    # Around 30% of people keep putting Certs in last name, so strip these out.
                    last_name = last_name.split(' ', 1)[0]
                    full_name = first_name + " " + last_name

                    # rooturl = c['hitInfo']['com.linkedin.voyager.search.SearchProfile']['miniProfile']['picture']['com.linkedin.common.VectorImage']['rootUrl']
                    # artifact = c['hitInfo']['com.linkedin.voyager.search.SearchProfile']['miniProfile']['picture']['com.linkedin.common.VectorImage']['artifacts'][3]['fileIdentifyingUrlPathSegment']
                    # person_image = rooturl + artifact
                    # person_image = trans(person_image)

                    linkedin = "https://www.linkedin.com/in/%s" % \
                               c['hitInfo']['com.linkedin.voyager.search.SearchProfile']['miniProfile'][
                                   'publicIdentifier']
                    linkedin = trans(linkedin)

                    email_syntax = hostx.pattern.replace(
                        "{f}",
                        first_name[0]).replace("{first}", first_name).replace(
                            "{l}", last_name[0]).replace("{last}", last_name)
                    user_email = email_syntax + "@" + hostx.primary_domain

                    hostx.employees.append((user_email, full_name, first_name,
                                            last_name, linkedin))

                    if checkers.is_email(user_email) and (user_email
                                                          not in hostx.emails):
                        hostx.guessed_emails.append(user_email)

                except Exception as e:
                    # This triggers when a profile doesn't have an image associated with it
                    continue
    print("\n")
    return 0