Best Python code snippet using robotframework-pageobjects_python
main.py
Source:main.py
...9 return gratient.green(text).strip()10 def log_success(self, text):11 print(f'[{self.green_gratient("*")}] | %s' % (text))12 print13 def log_invalid(self, text):14 print(f'[{self.red_gratient("*")}] | %s' % (text))15 print16 17class Medal:18 def __init__(self) -> None:19 pass20 def deleteAccount(self, userAgent, userId, medalToken, proxy = None):21 return requests.delete(22 'https://medal.tv/api/users/%s' % (userId),23 headers = {24 'Accept' : 'application/json', 25 'Content-Type' : 'application/json',26 'User-Agent' : userAgent,27 'Medal-User-Agent' : userAgent,28 'X-Authentication' : medalToken, 29 }, proxies = {30 'http' : f'http://{proxy}' , 31 'https' : f'http://{proxy}'32 } if proxy != None else None33 ).json()34 35 def getConnections(self, userAgent, medalToken, proxy = None):36 return requests.post(37 'https://medal.tv/social-api/connections',38 headers = {39 'Accept' : 'application/json', 40 'Content-Type' : 'application/json',41 'User-Agent' : userAgent,42 'Medal-User-Agent' : userAgent,43 'X-Authentication' : medalToken,44 }, json = {'provider' : 'discord'},45 proxies = {'http' : f'http://{proxy}' , 'https' : f'http://{proxy}'} if proxy != None else None46 ).json()47 def sendWebhook(self, webhookUrl, userAgent, userToken, nitroCode, tokenUsed):48 requests.post(49 webhookUrl,50 json = {51 'embeds': [52 {53 'title' : 'Promotion Code Generated',54 'color' : 3092790,55 'fields' : [56 {57 'name' : 'Nitro Link',58 'value' : '**%s**' % (nitroCode),59 'inline' : True60 }, {61 'name' : 'Medal.TV Token',62 'value' : '`%s`' % (userToken),63 'inline' : True64 }, {'name' : 'Discord Token', 'value': '`%s**`' % (tokenUsed[:29]), 'inline': True}, {65 'name' : 'User Agent Used',66 'value' : '```\n%s```' % (userAgent),67 'inline' : False68 }69 ], 'footer' : {70 'text': 'PromoCreator V 1.0.1'71 }72 }73 ]74 }75 )76 def createAuthentication(self, userEmail, userPassword, proxy = None):77 if True:78 userAgent = user_agent.generate_user_agent()79 userAgent80 81 return requests.post(82 'https://medal.tv/api/authentication',83 headers = {84 'Accept' : 'application/json', 85 'Content-Type' : 'application/json',86 'User-Agent' : userAgent,87 'Medal-User-Agent' : userAgent,88 }, json = {'email' : userEmail , 'password' : userPassword},89 proxies = {'http' : f'http://{proxy}' , 'https' : f'http://{proxy}'} if proxy != None else None90 ).json()91 92 def createAccount(self, authorizationToken, deleteAfter = False, proxy = None, webhookUrl = None):93 if True:94 if True:95 accountGenerated = False96 accountAttempts = 097 accountUserAgent = user_agent.generate_user_agent()98 while accountGenerated == False:99 email = ''.join(random.choice(string.ascii_letters) for x in range(7)) + random.choice(['@gmail.com', '@yahoo.com'])100 username = ''.join(random.choice(string.ascii_letters) for x in range(7))101 password = ''.join(random.choice(string.ascii_letters) for x in range(10))102 if accountAttempts == 5:103 return None104 break105 106 if accountAttempts != 5:107 resp = requests.post(108 'https://medal.tv/api/users',109 headers = {110 'Accept' : 'application/json',111 'User-Agent' : '%s' % (accountUserAgent),112 'Medal-User-Agent' : '%s' % (accountUserAgent),113 }, json = {114 'email' : '%s' % (email),115 'userName' : '%s' % (username), 116 'password' : '%s' % (password),117 }, proxies = {118 'http' : f'http://{proxy}' , 119 'https' : f'http://{proxy}'120 } if proxy != None else None121 )122 if resp.ok:123 accountGenerated = True124 break125 126 accountAttempts += 1127 accountAttempts, Color().log_invalid(text = 'Failed Attempt | %s' % (accountAttempts))128 if accountGenerated == True:129 try:130 if True:131 if True:132 authenticationResponse = self.createAuthentication(email, password, proxy if proxy != None else None)133 authenticationResponse134 135 userId = authenticationResponse['userId']136 key = authenticationResponse['key']137 Color().log_success('Account Created | %s' % (f'{userId},{key}'[:18]))138 discordData = self.getConnections(accountUserAgent, f'{userId},{key}', proxy if proxy != None else None)139 discordAuthUrl = discordData['loginUrl'] 140 discordAuthResp = requests.post(141 discordAuthUrl,142 headers = {143 'Authorization' : authorizationToken,144 }, json = {'permissions' : 0, 'authorize' : True}145 )146 if discordAuthResp.ok:147 if True:148 if True:149 medalToken = f'{userId},{key}'150 medalToken151 oAuthRedirect = discordAuthResp.json()['location']152 oAuthRedirect153 oAuthVerification = requests.get(oAuthRedirect)154 oAuthVerification155 if oAuthVerification.ok:156 if True:157 Color().log_success('Successfully Authenticated Account')158 Color159 nitroCodeResponse = requests.get(160 'https://medal.tv/api/social/discord/nitroCode',161 headers = {162 'Accept' : 'application/json',163 'User-Agent' : '%s' % (accountUserAgent),164 'Medal-User-Agent' : '%s' % (accountUserAgent),165 'X-Authentication' : '%s' % (medalToken),166 }, proxies = {167 'http' : f'http://{proxy}' , 168 'https' : f'http://{proxy}'169 } if proxy != None else None170 ).json()171 if True:172 try:173 Color().log_success('Nitro Code Created | %s' % (nitroCodeResponse['url']))174 open('medal/output/nitro_codes.txt' , 'a+').write('%s\n' % (nitroCodeResponse['url']))175 open('medal/output/medal_tokens.txt' , 'a+').write('%s\n' % (medalToken))176 if webhookUrl != None:177 self.sendWebhook(webhookUrl, accountUserAgent, medalToken, nitroCodeResponse['url'], authorizationToken)178 self179 if deleteAfter == True:180 self.deleteAccount(accountUserAgent, userId, medalToken, proxy if proxy != None else None)181 self182 except:183 if True:184 try:185 Color().log_invalid(text = '"%s"' % (nitroCodeResponse['errorMessage']))186 except:187 Color().log_invalid(text = 'Undefinable Error')188 else:189 Color().log_invalid(text = 'Authentication Error')190 except Exception as E:191 if True:192 print(E)193 print194 195 Color.log_invalid(text = 'Exception During Account Creation')196 Color197class Menu:198 def printLogo():199 print(art.text2art('PromoCreator'))200 print201 202 def printOptions():203 print(f'[{Color().green_gratient(text = "1")}] - Promo Generator')204 print(f'[{Color().green_gratient(text = "2")}] - Token Dump')205 def getOption():206 return input('[$] > ')207 208 def startMenu():209 while True:...
config.py
Source:config.py
1#!/usr/bin/env python32from BruteLoops.jitter import Jitter3from BruteLoops import sql4from BruteLoops.callback import Callback5from BruteLoops import logging as BL6from sqlalchemy import create_engine7from sqlalchemy.orm import sessionmaker8from pathlib import Path9from sys import stdout,stderr10import inspect11import logging12class Config:13 '''14 Configuration object that is consumed by BruteForce objects. Configurations15 specified here dictate various aspects of the brute force attack, as well16 as logging and exception handling.17 # Attack Configuration Parameters18 - `process_count` - `integer` value - The number of child processes to spawn to support19 the attack. Each process will be used to make distinct calls to the20 authentication_callback.21 ` `authentication_callback` - `function`, `callable` - A function or objection22 implementing `__call__` that is expected to received two arguments: `username`23 and `password`. The callback should return a three-item tuple in the form of:24 `(outcome, username, password)`, where `outcome` should be an integer value25 that determines if authentication was successful -- `0` for unsuccessful and26 `1` for successful.27 - `authentication_jitter`- `Jitter` object - A `Jitter'28 object that determines how long a child process should sleep after running the29 `authentication_callback`. See the jitter documentation for information on30 proper formatting.31 - `max_auth_jitter` - `Jitter` object - A `Jitter` object that32 determines how long a period of time should pass before attempting further33 authentication attempts. Follows the same format as `Jitter`.34 - `max_auth_tries` - Number of simultaneous authentication attempts to perform for35 a given user before sleeping for a period of time indicated by `Jitter`.36 Should a standard horizontal brute force attack be desired, set this value to `1`.37 # Logging Configuration Parameters38 These configurations are optional.39 ## Log Destinations40 The following parameters can be used to configure where log records are sent. These values41 are not mutually exclusive, i.e. it is possible to log to a `log_file` and `log_stdout`42 simultaneously.43 - `log_file` - `string` value - Log records to a file named at this parameter. Records are44 appended to the log file.45 - `log_stdout' - `boolean` value - Log events to `stdout`. 46 - `log_stderr` - `boolean` value - Log events to `stderr`.47 ## Logging Level Specification48 - `log_valid` - `boolean` value - Log valid records to each destination.49 - `log_invalid` - `boolean` value - Log all authentication records, i.e. both valid and invalid.50 - `log_general` - `boolean` value - Log all relevant events to each destination.51 '''52 def __init__(self,53 process_count=1, # NUMBER OF CHILD PROCESSES TO RUN54 authentication_callback=None, # AUTHENTICATION CALLBACK55 authentication_jitter=None, # JITTER AFTER EACH AUTHENTICATION ATTEMPT56 max_auth_jitter=None, # JITTER AFTER EACH PASSWORD ITERATION57 max_auth_tries=1, # JITTER ONLY AFTER A THRESHOLD58 stop_on_valid=False, # STOP AFTER A SINGLE CREDENTIAL IS RECOVERED59 db_file=None, # SQLITE DATABASE FILE60 log_valid=False, # ALERT TO STDOUT ON VALID CREDENTIALS61 log_invalid=False, # ALERT TO STDOUT ON INVALID CREDENTIALS62 log_general=False, # GENERAL BRUTEFORCE ALERTS63 log_file=False, # FILE TO RECEIVE ADDITIONAL LOGS64 log_stdout=False, # LOG EVENTS TO STDOUT65 log_stderr=False, # LOG EVENTS TO STDERR66 exception_handlers={}): # DICTIONARY OF EXCEPTION HANDLERS: {class:exception_handler}67 self.process_count = process_count68 self.authentication_callback = authentication_callback69 self.authentication_jitter = authentication_jitter70 self.max_auth_jitter = max_auth_jitter71 self.max_auth_tries = max_auth_tries72 self.stop_on_valid = stop_on_valid73 self.db_file = db_file74 self.log_valid = log_valid75 self.log_invalid = log_invalid76 self.log_general = log_general77 self.log_file = log_file78 self.log_stdout = log_stdout79 self.log_stderr = log_stderr80 self.exception_handlers = exception_handlers81 self.log_level = 9082 self.validated = False83 def configure_logging(self):84 'Configure a logger for the library'85 86 logger = logging.getLogger('brute_logger')87 if self.log_valid or self.log_invalid or self.log_general:88 89 if self.log_valid: self.log_level = BL.VALID_CREDENTIALS90 if self.log_invalid: self.log_level = BL.CREDENTIAL_EVENTS91 if self.log_general: self.log_level = BL.GENERAL_EVENTS92 if self.log_file or self.log_stdout or self.log_stderr:93 handlers = []94 if self.log_file:95 handlers.append(logging.FileHandler(self.log_file))96 if self.log_stdout:97 handlers.append(logging.StreamHandler(stdout))98 if self.log_stderr:99 handlers.append(logging.StreamHandler(stderr))100 for handler in handlers:101 handler.setFormatter(BL.LOG_FORMAT)102 handler.setLevel(self.log_level)103 logger.addHandler(handler)104 else:105 sh = logging.StreamHandler(stdout)106 sh.setFormatter(BL.LOG_FORMAT)107 logger.addHandler(sh)108 logger.setLevel(self.log_level)109 else:110 # DISABLE LOGGING111 logger.setLevel(self.log_level)112 def validate(self):113 # ==========================114 # ASSERT REQUIRED PARAMETERS115 # ==========================116 assert self.process_count, 'A Config object requires a process_count'117 assert self.process_count.__class__ == int, (118 'Process count must be an integer value'119 )120 assert self.db_file, 'A path to a SQLite database is required. '\121 'Library will create one should the file itself not yet exist.'122 assert self.authentication_callback, (123 'A callback must be set on the Config object'124 )125 if self.exception_handlers:126 assert type(self.exception_handlers) == dict, (127 'exception_handlers is intended to be a dictionary, where\n'\128 'each key is an exception class and the value a function\n'\129 'which the exception will execute. The current brute object\n'\130 'will be passed to the function as an argument.\n'\131 f'Current type: {type(self.exception_handlers)}'132 )133 # ===============================134 # SET THE AUTHENTICATION_CALLBACK135 # ===============================136 self.authentication_callback = Callback(137 self.authentication_callback,138 self.authentication_jitter139 )140 # =====================141 # SQLITE INITIALIZATION142 # =====================143 engine = create_engine('sqlite:///'+self.db_file)144 Session = sessionmaker()145 Session.configure(bind=engine)146 # Create the database if required147 if not Path(self.db_file).exists():148 sql.Base.metadata.create_all(engine)149 self.session_maker = Session150 self.configure_logging()151 # UPDATE THE OBJECT TO REFLECT VALIDATED STATE...
decorator.py
Source:decorator.py
1"""Middleware decorator for auth"""2from typing import Callable3def needs_auth(4 require_user: bool = True,5 owner_only: bool = False,6 allow_banned: bool = False,7 log_invalid: bool = False) -> Callable:8 """Decorator for a request handler for authentication"""9 # pylint: disable=invalid-name10 def decorator(f: Callable) -> Callable:11 f.use_auth = True12 f.require_user = require_user or owner_only13 f.owner_only = owner_only14 f.allow_banned = allow_banned15 f.log_invalid = log_invalid16 return f...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!