def post(self): if any(f for f in ('email', 'password', 'name') if f not in self.data): raise APIError('Missing parameter(s)') if not utils.is_valid_email(self.data['email']): raise APIError('Invalid email address') if len(self.data['password']) < 8: raise APIError('Invalid password') if len(self.data['name']) < 3: raise APIError('Invalid name') try: models.get_active_account(email=self.data['email']) raise APIError('Email already registered') except models.Account.DoesNotExist: account = models.Account(name=self.data['name'], email=self.data['email'], password=generate_password_hash(self.data['password']), calories_goal=settings['default_calories_goal']) account.save() # make this account a user models.AccountRole(account=account, role=models.Role.get(code='user')).save() update_token = urlserializer.dumps({'id': account.id, 'active': True}, salt='account-update') url = url_for('public', path='apply-account-changes', account_id=account.id, token=update_token, _external=True) tasks.send_activation_email.delay(account.id, url, update_token) return created_response('account', account_id=account.id)
def do_migration(): cpf = utils.env.get("admin", "cpf") password = utils.env.get("admin", "password") display_name = utils.env.get("admin", "display_name") email = utils.env.get("admin", "email") if not isinstance(cpf, str): raise Exception("Invalid cpf") # TODO InvalidCPFError. if not utils.is_valid_cpf(cpf): raise Exception("Invalid cpf") # TODO InvalidCPFError. if not isinstance(password, str): raise Exception("Invalid password") # TODO InvalidPasswordError. if not isinstance(display_name, str): raise Exception("Invalid display_name") # TODO InvaliDisplayNameError. if email is not None and not isinstance(email, str): raise Exception("Invalid email") # TODO InvalidEmailError. if email is not None and not utils.is_valid_email(email): raise Exception("Invalid email") # TODO InvalidEmailError. user = auth.User.create( cpf=cpf, password=bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()).decode( "utf-8" ), display_name=display_name, email=email, is_verified=None if email is None else False, ) user_group = auth.Group.get(name="admin") auth.UserGroups.create(user=user, group=user_group)
def _validate_kwargs(self, **kwargs): valid_kwargs = {"cpf", "password", "display_name", "phone", "email"} for kwarg in kwargs.keys(): if kwarg not in valid_kwargs: # This is indeed an internal server error. raise TypeError(f"{kwarg} is not a valid keyword argument") if "cpf" in kwargs: if not utils.is_valid_cpf(kwargs["cpf"]): raise BadRequest("invalid cpf") if "phone" in kwargs: if not kwargs["phone"].isdigit(): raise BadRequest("invalid phone") if "email" in kwargs: if kwargs["email"] is not None and not utils.is_valid_email( kwargs["email"]): raise BadRequest("invalid email")
def getUserStatus(self, mail): status = 1 if utils.is_valid_email(mail): status = self.users[mail]['status'] return status
def isSMSNumber(self, phone): return not utils.is_valid_email(phone)
def parse_profile(uid, num_post_scroll): try: url = urllib.parse.urljoin(URL_FACEBOOK_ROOT, uid) driver = get_driver() driver.get(url) soup = BeautifulSoup(driver.page_source, 'lxml') current_url = driver.current_url except Exception as e: driver.quit() raise e try: user_data = dict() user_data['uid'] = uid user_data['profile_url'] = current_url # get username user_data['username'] = current_url.replace(URL_FACEBOOK_ROOT, '').replace('/', '') # Get user's name # user_name_h1 = soup.find("h1", id="seo_h1_tag") user_name_div = soup.find("div", id="u_0_0") user_data['name'] = user_name_div.a.span.string # Get follower number follower_count = soup.find('div', string=re.compile('people follow this')) if follower_count: res = re.findall('[0-9,]+', follower_count.string) if res: user_data['followers'] = res[0].replace(',', '') else: user_data['followers'] = '0' # Get likes number likes_count = soup.find('div', string=re.compile('people like this')) if likes_count: res = re.findall('[0-9,]+', likes_count.string) if res: user_data['likes'] = res[0].replace(',', '') else: user_data['likes'] = '0' # Click about tab for contact details. about_page = driver.find_element(By.CSS_SELECTOR, "[data-key=tab_about]") about_page.click() WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.ID, "PagesProfileAboutInfoPagelet_"+str(uid)))) # CONTACT DETAILS soup = BeautifulSoup(driver.page_source, 'lxml') contact_details = [] cd_div_child = soup.find("div", string='CONTACT DETAILS') if cd_div_child: for sibling in cd_div_child.next_siblings: if type(sibling) is Tag: text_div = sibling.find("div", class_="_50f4") if text_div: if is_valid_email(text_div.string) or is_url(text_div.string): contact_details.append(text_div.string) elif text_div.string.startswith('Call '): contact_details.append(text_div.string.replace('Call', '').strip()) elif text_div.parent.name == "a": contact_details.append(text_div.parent['href']) user_data['contact_details'] = contact_details driver.quit() except Exception as e: driver.quit() logging.log(logging.CRITICAL, f"Parse profile failed : {user_data['profile_url']}") raise e m_connection = MongoClient(MONGODB_URI) with m_connection: m_connection.aggero_fb.user_details.find_one_and_replace({'uid': user_data['uid']}, user_data, upsert=True) logging.log(logging.INFO, f"User Data : {user_data}") with faktory.connection(faktory=URL_FACTORY) as client: client.queue('parse_posts', args=[user_data['uid'], user_data['username'], num_post_scroll], queue='busy')
def valid_email(ctx, param, value): if not is_valid_email(value): raise click.BadParameter('Invalid Email Address.') return value
def put(self, account_id): # if the account is being updated through the update_token, then we don't need to authenticate # the user (they may not even be able to log in) if 'update_token' in self.data: return self.update_account(account_id) # verify authorization account_id, token = verify_token_get_account(['user', 'user-manager', 'admin'], ['user-manager', 'admin'], kwargs={'account_id': account_id}) try: account = models.get_active_account(id=account_id) except models.Account.DoesNotExist: raise APIError('Account not found', 404) # perform updates if 'roles' in self.data: if not isinstance(self.data['roles'], list) or any(r for r in self.data['roles'] if not isinstance(r, basestring)): raise APIError('Invalid roles value') final_roles = models.Role.select().where(models.Role.code << self.data['roles']) if len(final_roles) != len(self.data['roles']): raise APIError('Invalid roles value') current_roles = models.Role.select().join(models.AccountRole).where(models.AccountRole.account == account) # changing roles is something only an admin can do if any(r for r in current_roles if r not in final_roles) or any(r for r in final_roles if r not in current_roles): verify_token_get_account(['admin'], ['admin'], kwargs={'account_id': account_id}) # handle deletions for role in [r for r in current_roles if r not in final_roles]: models.AccountRole.get(models.AccountRole.account == account, models.AccountRole.role == role).delete_instance() # handle additions for role in [r for r in final_roles if r not in current_roles]: models.AccountRole(account=account, role=role).save() if 'name' in self.data: if not isinstance(self.data['name'], basestring): raise APIError('Invalid name') account.name = self.data['name'] if 'email' in self.data and self.data['email'] != account.email: if not utils.is_valid_email(self.data['email']): raise APIError('Invalid email') try: models.get_active_account(email=self.data['email']) raise APIError('Email already used') except models.Account.DoesNotExist: pass if any(r for r in token['roles'] if r in ('user-manager', 'admin')): account.email = self.data['email'] else: # verify the current password and send a link to update the email if 'current_password' not in self.data: raise APIError('Missing current password') if not check_password_hash(account.password, self.data['current_password']): raise APIError('Invalid current password') update_token = urlserializer.dumps({'id': account.id, 'email': self.data['email']}, salt='account-update') url = url_for('public', path='apply-account-changes', account_id=account.id, token=update_token, _external=True) tasks.send_account_update_email.delay(account.id, url, update_token, email=self.data['email']) if 'password' in self.data: if len(self.data['password']) < 8: raise APIError('Invalid password') if not any(r for r in token['roles'] if r in ('user-manager', 'admin')): if 'current_password' not in self.data: raise APIError('Missing current password') if not check_password_hash(account.password, self.data['current_password']): raise APIError('Invalid current password') account.password = generate_password_hash(self.data['password']) if 'calories_goal' in self.data: try: account.calories_goal = int(self.data['calories_goal']) except: raise APIError('Invalid calories amount') account.save() return '', 204