def create_report(request: Request) -> Response: serializer = ReportSerializer(data=request.data) serializer.is_valid(raise_exception=True) file_id = secrets.token_urlsafe(16) generate_report(file_id=file_id, request_params=request.data) return Response({"url": report_url(file_id)})
def create_secret(self, url): secret = token_urlsafe() self.db.table(self.TABLE_NAME).insert({ "id" : secret, "url" : url }, conflict="error").run() return secret
def shorten(url: str, nbytes: int=5) -> str: ext = token_urlsafe(nbytes=nbytes) if ext in DATABASE: return shorten(url, nbytes=nbytes) else: DATABASE.update({ext: url}) return f'short.ly/{ext}'
def qute_settings(url): """Handler for qute://settings. View/change qute configuration.""" global csrf_token if url.path() == '/set': if url.password() != csrf_token: message.error("Invalid CSRF token for qute://settings!") raise RequestDeniedError("Invalid CSRF token!") return _qute_settings_set(url) # Requests to qute://settings/set should only be allowed from # qute://settings. As an additional security precaution, we generate a CSRF # token to use here. if secrets: csrf_token = secrets.token_urlsafe() else: # On Python < 3.6, from secrets.py token = base64.urlsafe_b64encode(os.urandom(32)) csrf_token = token.rstrip(b'=').decode('ascii') src = jinja.render('settings.html', title='settings', configdata=configdata, confget=config.instance.get_str, csrf_token=csrf_token) return 'text/html', src
def setUp(self): self.directory = os.path.join(tempfile.gettempdir(), secrets.token_urlsafe(10)) if not os.path.exists(self.directory): os.mkdir(self.directory) self.config_dir = os.path.join(self.directory, "config") self.data_dir = os.path.join(self.directory, "data") if not os.path.exists(self.config_dir): os.mkdir(self.config_dir) if not os.path.exists(self.data_dir): os.mkdir(self.data_dir) current_dir = os.path.dirname(__file__) tests_dir = os.path.join(current_dir, "../../") shutil.copy(os.path.join(tests_dir, "files/test.toml"), os.path.join(self.data_dir, "test.toml")) self.manager = StorageManager( ultros=None, config_location=self.config_dir, data_location=self.data_dir )
def generate_random_id(): try_count = 0 while True: try_count += 1 assert try_count < 100 s = token_urlsafe(9) if s.isalnum(): return s
def test_token_urlsafe(self): # Test token_urlsafe. legal = string.ascii_letters + string.digits + '-_' for n in (1, 11, 28, 76): with self.subTest(n=n): s = secrets.token_urlsafe(n) self.assertIsInstance(s, str) self.assertTrue(all(c in legal for c in s))
def _prepare_token(item, user_id): token = token_urlsafe() # Remove user and password from document del item['username'] del item['password'] # Add token (str) and user_id (ObejctId) item['user'] = user_id item['token'] = token
def create_token_secret_on_startup(app): """Create a token secret in the database if it doesn't exist. The secret key is stored in the database to ensure consistency. The database collection holding this key is called `config`. """ with app.app_context(): # Context for db connection config = app.data.driver.db['config'] result = config.find_one( {'TOKEN_SECRET': {'$exists': True, '$nin': [None, '']}}) if result is None: config.insert_one({'TOKEN_SECRET': token_urlsafe()})
async def register(req): stmt = await shared.postgres.prepare("SELECT create_user($1, $2, $3, $4);") userid = uuid4() await stmt.fetch(userid, req.json["nickname"], req.json["email"], bcrypt.hashpw(req.json["password"].encode(), bcrypt.gensalt())) validation_token = token_urlsafe() await shared.redis.set(f"users:{userid}:validation_token", validation_token) await shared.redis.expire(f"users:{userid}:validation_token", TOKEN_EXPIRATION_TIME) # TODO # send an email return json({"id": str(userid), "token": validation_token})
def api_config(self): """ Sets api version for /:version, cors and makes api json only """ self.app.config['API_VERSION'] = __version__.split(".")[0] self.app.config['X_DOMAINS'] = environ.get('CORS_DOMAINS', '*') self.app.config['RENDERERS'] = ['eve.render.JSONRenderer'] self.app.config['VERSIONING'] = True self.app.config['OPLOG'] = True self.app.config['OPLOG_ENDPOINT'] = '/oplog' self.app.config['SCHEMA_ENDPOINT'] = '/schema' self.app.config['SOFT_DELETE'] = True self.app.config['OPTIMIZE_PAGINATION_FOR_SPEED'] = True self.app.config['JWT_SECRET'] = environ.get('JWT_SECRET', sha1(token_urlsafe(32))) self.app.config['JWT_ISSUER'] = environ.get('JWT_ISSUER', getfqdn().lower())
def random_alphanumeric_underscore(length): if sys.version_info[0] >= 3: import secrets # Ensure the string is the right length byte_length = math.ceil((length * 3) / 4) return secrets.token_urlsafe(byte_length).replace("-", "_")[:length] else: import random import string return "".join( random.SystemRandom().choice( "_" + string.ascii_uppercase + string.ascii_lowercase + string.digits ) for _ in range(length) )
async def forget(req): stmt = await shared.postgres.prepare("SELECT userid, email, is_verified FROM get_user_by_login($1)") user = await stmt.fetchrow(req.json["login"]) if all(map(lambda v: v is None, user.values())): logger.warning(f"User \'{req.json['login']}\' not found") raise Forbidden("User not found") if not user["is_verified"]: logger.warning(f'User \'{req.json["login"]}\' is not verified yet') raise Forbidden("You must verify your email first") reset_token = token_urlsafe() await shared.redis.set(f"users:{user['userid']}:reset_token", reset_token) await shared.redis.expire(f"users:{user['userid']}:reset_token", TOKEN_EXPIRATION_TIME) # TODO # send an email return json({"userid": str(user["userid"]), "token": reset_token})
def user_login(request): data = request.json_body rand_token = secrets.token_urlsafe(50) result = { "status": 1, "message": "Success", "data": { "id": "1", "email": data['email'], "password": data['password'], "name": "Tester Name", "login_token": rand_token, "first_name": "Le", "last_name": "Tuan", "CDL": "?", "license": "98454513262", "drive_phone_number": "0984345062", "picture": "http://api.drive-qa.uat.pgtest.co/upload/resource/profile/avatar.jpg", "carier_name": "DEV", "main_office_address": "HN", "carier_office_phone_number": "0984345062", "usdot_number": "120694", "truck_number": "123456", "license_plate_number": "159753", "odometer_unit": "Miles", "pick_duty_cycle": "1", "vehicle_type": "2", "30_minute_break_exempt": "true", "24h_cycle_reset": "true", "oilfield_waiting_time": "true", "100_air": "true", "16h_short_haul": "true", "tank_vehicle": "true", "150_air_mile": "true" } } return { "status": 1, "message": "Success", "data": result }
def create_record(record): client = boto3.client('dynamodb') record_id = secrets.token_urlsafe(12) client.put_item( TableName = app.config['DDB_TABLE_NAME'], Item = { 'id': { 'S': record_id }, 'form_key': { 'S': record['form_key'] }, 'date': { 'N': str(record['date']) }, 'form_data': { 'S': record['form_data'] }, }, ) return get_record(record_id)
def setUp(self): self.loop = asyncio.new_event_loop() asyncio.set_event_loop(None) self.directory = os.path.join(tempfile.gettempdir(), secrets.token_urlsafe(10)) if not os.path.exists(self.directory): os.mkdir(self.directory) self.config_dir = os.path.join(self.directory, "config") self.data_dir = os.path.join(self.directory, "data") if not os.path.exists(self.config_dir): os.mkdir(self.config_dir) if not os.path.exists(self.data_dir): os.mkdir(self.data_dir) self.manager = StorageManager( ultros=None, config_location=self.config_dir, data_location=self.data_dir )
def get(self, request, **kwargs): invoice_token = kwargs.pop('invoice_token', None) person_token = kwargs.pop('person_token', None) if invoice_token: invoice = detokenise(invoice_token, Invoice) person = invoice.person else: person = detokenise(person_token, Person) description = "CWLTC Mandate" session_token = secrets.token_urlsafe(20) url = request.build_absolute_uri(reverse('cardless_redirect_flow')) flow = cardless_client().redirect_flows.create( params={ "description": description, "session_token": session_token, "success_redirect_url": url, "prefilled_customer": { "given_name": person.first_name, "family_name": person.last_name, "email": person.email, "address_line1": person.address.address1, "address_line2": person.address.address2, "address_line3": "", "city": person.address.town, "postal_code": person.address.post_code } } ) # Store data in table because session can disappear session = Session() session.flow_id = flow.id session.token = session_token session.person_id = person.id session.invoice_token = invoice_token session.save() return redirect(flow.redirect_url)
def generate_token(): return token_urlsafe(20)
def make_bearer(privilege_nums=(1, )): thetoken = secrets.token_urlsafe(128) db.bearer_tokens.insert({"token": thetoken, "privs": privilege_nums}) return thetoken
import random import string import os import secrets # DIGITS, 0-32768 print(random.randrange(0, 32768)) # DIGITS, 1-10 print(random.randrange(0, 10)) # Random character print(random.choice(string.ascii_letters)) # BASE64, 48 alphanumeric characters print(secrets.token_urlsafe(48)) # Hex, 16 characters print(''.join([random.choice('ABCDEF1234567890') for i in range(32)])) # Hex, 16 characters print(os.urandom(16).hex()) # Hex, 16 characters print(secrets.token_hex(16)) # Random characters, beyond basic Latin alphabet print(os.urandom(16).decode('utf-16')) # BASE64, 12 alphanumeric characters print(''.join(
def _new_key(nbytes=24): while True: candidate = token_urlsafe(nbytes) if candidate[0] not in "-_" and candidate[-1] not in "-_": return candidate
def save(self, *args, **kwargs): if not self.key: self.key = secrets.token_urlsafe() return super().save(*args, **kwargs)
def __generate_token(self): return secrets.token_urlsafe()
def define_all(): for d in definitions.params: PlantDefault(name=d["name"], default_image=d["default_image"], default_water_level=d["default_water_level"]) for plant in d["species"]: PlantSubDefault(subname=plant, plant_default=PlantDefault.get(name=d["name"])) u1 = User(nickname="superszpital", password=hashlib.sha3_256(b"valerie").hexdigest(), token=secrets.token_urlsafe(32), authorized=True, email="20300") u2 = User(nickname="niesuperjarek", password=hashlib.sha3_256(b"penis").hexdigest(), token=secrets.token_urlsafe(32), authorized=True, email="2000") d1 = Device( device_name="RK9", url="https://webhook.site/026a4573-65c6-4b1e-8740-6c8a12a67a31", max_plants=3) d2 = Device( device_name="1337", url="https://webhook.site/026a4573-65c6-4b1e-8740-6c8a12a67a31", max_plants=2) d3 = Device( device_name="Choinka", url="https://webhook.site/026a4573-65c6-4b1e-8740-6c8a12a67a31", max_plants=2) d4 = Device( device_name="Presto", url="https://webhook.site/026a4573-65c6-4b1e-8740-6c8a12a67a31", max_plants=1) p1 = Plant(device=d1, name="puszka", water_level=0, plant_category=PlantSubDefault.get(id=3), water_time="21:30", water_days="134") p2 = Plant(device=d1, name="balkon", water_level=0, plant_category=PlantSubDefault.get(id=1), water_time="21:30", water_days="134") p3 = Plant(device=d2, name="piwnica", water_level=0, plant_category=PlantSubDefault.get(id=2), water_time="21:30", water_days="152") p4 = Plant(device=d1, name="jezioro", water_level=0, plant_category=PlantSubDefault.get(id=4), water_time="21:30", water_days="14") WatchEvent(device=d1, user=u1, privilege_level=0) WatchEvent(device=d2, user=u1, privilege_level=0) WatchEvent(device=d3, user=u2, privilege_level=0) WatchEvent(device=d4, user=u2, privilege_level=0) print("woop")
def browser_session_setting_section(): return { "secret_key": secrets.token_urlsafe(64), "cookie_secure": True, }
class Settings(BaseSettings): API_V1_STR: str = "/api/v1" DOMAIN_NAME: HttpUrl SECRET_KEY: str = secrets.token_urlsafe(32) # 60 minutes * 24 hours * 8 days = 8 days ACCESS_TOKEN_EXPIRE_MINUTES: int = 60 * 24 * 8 # BACKEND_CORS_ORIGINS is a JSON-formatted list of origins # e.g: '["http://localhost", "http://*****:*****@validator("BACKEND_CORS_ORIGINS", pre=True) def assemble_cors_origins(cls, v: Union[str, List[str]]) -> Union[List[str], str]: if isinstance(v, str) and not v.startswith("["): return [i.strip() for i in v.split(",")] elif isinstance(v, (list, str)): return v raise ValueError(v) PROJECT_NAME: str POSTGRES_SERVER: str POSTGRES_USER: str POSTGRES_PASSWORD: str POSTGRES_DB: str SQLALCHEMY_DATABASE_URI: Optional[PostgresDsn] = None # TEST DB is hardcoded here for now SQLALCHEMY_DATABASE_TEST_URI: PostgresDsn = PostgresDsn.build( scheme="postgresql", user="******", password="******", host="db", path="/sedotra_test", ) @validator("SQLALCHEMY_DATABASE_URI", pre=True) def assemble_db_connection(cls, v: Optional[str], values: Dict[str, Any]) -> Any: if isinstance(v, str): return v return PostgresDsn.build( scheme="postgresql", user=values.get("POSTGRES_USER"), password=values.get("POSTGRES_PASSWORD"), host=values.get("POSTGRES_SERVER"), path=f"/{values.get('POSTGRES_DB') or ''}", ) SMTP_TLS: bool = True SMTP_PORT: Optional[int] = None SMTP_HOST: Optional[str] = None SMTP_USER: Optional[str] = None SMTP_PASSWORD: Optional[str] = None EMAILS_FROM_EMAIL: Optional[EmailStr] = None EMAILS_FROM_NAME: Optional[str] = None @validator("EMAILS_FROM_NAME") def get_project_name(cls, v: Optional[str], values: Dict[str, Any]) -> str: if not v: return values["PROJECT_NAME"] return v EMAIL_RESET_TOKEN_EXPIRE_HOURS: int = 48 EMAIL_TEMPLATES_DIR: str = "/app/app/email-templates/build" EMAILS_ENABLED: bool = True @validator("EMAILS_ENABLED", pre=True) def get_emails_enabled(cls, v: bool, values: Dict[str, Any]) -> bool: return bool( values.get("SMTP_HOST") and values.get("SMTP_PORT") and values.get("EMAILS_FROM_EMAIL") ) EMAIL_TEST_USER: EmailStr = "*****@*****.**" # type: ignore USERS_OPEN_REGISTRATION: bool = False # OBJECT STORAGE ACCESS OBJECT_ACCESS_KEY: str OBJECT_SECRET_KEY: str OBJECT_BUCKET: str OBJECT_ENDPOINT: AnyHttpUrl class Config: case_sensitive = True
''' async def index(request): ip = request.headers.get('X-Real-IP', '127.0.0.1') if (answer := request.query_params.get('answer')) is None: prefix, time_remain = powser.get_challenge(ip) return HTMLResponse(config.pow_html.render(dict( prefix=prefix, difficulty=powser.difficulty, ip=ip, time_remain=time_remain, min_refresh_time=powser.min_refresh_time, ))) res, msg = powser.verify_client(ip, str(answer), with_msg=True) if not res: return HTMLResponse(msg) user = await db.create_user(token_urlsafe(16), config.user_init_balance) return RedirectResponse(url='/' + user.uid, status_code=HTTP_303_SEE_OTHER) @login_required async def home(request, user): if user.balance >= 10000: msg = config.flag elif bool(user.bankrupt): msg = 'You are bankrupt ¯\_(ツ)_/¯' else: msg = "Once you have >= $10,000, you'll see the flag in this page." task = None if request.method == 'POST': if user.balance <= 0: return HTMLResponse('Not enough balance')
def set_hashid(self): self.hashid = secrets.token_urlsafe(8)[:8]
import secrets from imbox import Imbox config = {} try: with open("config.json", "r") as configF: config = json.load(configF) except FileNotFoundError: with open("config.json", "w") as configF: config = {"username": "", "password": "", "server": ""} print(json.dumps(config), file=configF) quit(0) with smtplib.SMTP_SSL(config['server'] + ':465') as server_out: server_out.login(config['username'], config['password']) with Imbox(config['server'], username=config['username'], password=config['password'], ssl=True) as inbox: inbox_messages = inbox.messages() for uid, messageIn in inbox_messages: password = secrets.token_urlsafe(16) text = "We created a password for you! Its very secure, but we do not recommend to use it. \n Here it is\n" + password message = 'From: Passwords (not) very secure <' + config[ 'username'] + '>\nSubject: {}\n\n{}'.format( "Your new Password", text) server_out.sendmail(config['username'], messageIn.sent_from[0]['email'], message) inbox.delete(uid)
def _setupSSHDImpl(ngrok_token, ngrok_region, is_VNC): #apt-get update #apt-get upgrade my_apt = _MyApt() #Following packages are useless because nvidia kernel modules are already loaded and I cannot remove or update it. #Uninstall them because upgrading them take long time. my_apt.deleteInstalledPkg("nvidia-dkms", "nvidia-kernel-common", "nvidia-kernel-source") my_apt.commit() my_apt.update_upgrade() my_apt.commit() subprocess.run(["unminimize"], input="y\n", check=True, universal_newlines=True) my_apt.installPkg("openssh-server") my_apt.commit() my_apt.close() #Reset host keys for i in pathlib.Path("/etc/ssh").glob("ssh_host_*_key"): i.unlink() subprocess.run(["ssh-keygen", "-A"], check=True) #Prevent ssh session disconnection. with open("/etc/ssh/sshd_config", "a") as f: f.write("\n\nClientAliveInterval 120\n") msg = "" msg += "ECDSA key fingerprint of host:\n" ret = subprocess.run( ["ssh-keygen", "-lvf", "/etc/ssh/ssh_host_ecdsa_key.pub"], stdout=subprocess.PIPE, check=True, universal_newlines=True) msg += ret.stdout + "\n" _download( "https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-linux-amd64.zip", "ngrok.zip") shutil.unpack_archive("ngrok.zip") pathlib.Path("ngrok").chmod(stat.S_IXUSR) root_password = secrets.token_urlsafe() user_password = secrets.token_urlsafe() user_name = "colab" msg += "✂️" * 24 + "\n" msg += f"root password: {root_password}\n" msg += f"{user_name} password: {user_password}\n" msg += "✂️" * 24 + "\n" subprocess.run(["useradd", "-s", "/bin/bash", "-m", user_name]) subprocess.run(["adduser", user_name, "sudo"], check=True) subprocess.run(["chpasswd"], input=f"root:{root_password}", universal_newlines=True) subprocess.run(["chpasswd"], input=f"{user_name}:{user_password}", universal_newlines=True) subprocess.run(["service", "ssh", "restart"]) if not pathlib.Path('/root/.ngrok2/ngrok.yml').exists(): subprocess.run(["./ngrok", "authtoken", ngrok_token]) ngrok_proc = subprocess.Popen( ["./ngrok", "tcp", "-region", ngrok_region, "22"]) time.sleep(2) if ngrok_proc.poll() != None: raise RuntimeError("Failed to run ngrok. Return code:" + str(ngrok_proc.returncode) + "\nSee runtime log for more info.") with urllib.request.urlopen( "http://*****:*****@{hostname}\n" else: msg += "Command to connect to the ssh server:\n" msg += "✂️" * 24 + "\n" msg += f"ssh {ssh_common_options} -p {port} {user_name}@{hostname}\n" msg += "✂️" * 24 + "\n" return msg
def write_file(filename): text = secrets.token_urlsafe() with open(filename, "w") as f: f.write(f"""{{"FOO": "{text}"}}""") return text
# django-environ initialization root = environ.Path(__file__) - 2 # type: Callable[[*str], str] env = environ.Env() environ.Env.read_env(root(".env")) # SECURITY WARNING: don't run with debug turned on in production! DEBUG = env.bool("DEBUG", default=False) # SECURITY WARNING: keep the secret key used in production secret! if DEBUG: # For DEBUG environment only, allow not specifying secret key SECRET_KEY = env("SECRET_KEY", default=None) if SECRET_KEY is None: # If not specified, use an ephemeral random 128-bit value # This will invalidate signatures on restarts SECRET_KEY = secrets.token_urlsafe(16) warnings.warn( "SECRET_KEY is not set! An ephemeral random value will be used.") else: # Specifying secret key is mandatory when DEBUG is disabled SECRET_KEY = env("SECRET_KEY") ALLOWED_HOSTS = env.list("ALLOWED_HOSTS", default=[]) # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ SECURE_CONTENT_TYPE_NOSNIFF = True SECURE_BROWSER_XSS_FILTER = True X_FRAME_OPTIONS = "DENY" # Quick switch that tells if site is TLS-secured or not if env.bool("USE_SSL", default=not DEBUG):
def get_download_token(): token_file = Path.home() / '.deeppavlov' if not token_file.exists(): token_file.write_text(secrets.token_urlsafe(32), encoding='utf8') return token_file.read_text(encoding='utf8').strip()
from flask import Flask, render_template, url_for, request, jsonify, redirect,\ session, flash from flask_socketio import SocketIO, emit import datetime import secrets from functools import wraps app = Flask(__name__) # Initilize socketio app.config["SECRET_KEY"] = secrets.token_urlsafe(16) socketio = SocketIO(app) def login_required(f): @wraps(f) def decorated_function(*args, **kwargs): if session.get("id") is None: return redirect("/login") return f(*args, **kwargs) return decorated_function @app.route("/") @login_required def index(): return render_template("index.html") # store data first_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M")
def generate_token(): return secrets.token_urlsafe(NBYTES)
def getSysCode(): return secrets.token_urlsafe(42)
from flask import Flask, redirect, request, flash, session, url_for, g, jsonify, json from flask_sqlalchemy import SQLAlchemy from flask import render_template import secrets import random import jdatetime from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user app = Flask(__name__) secret = secrets.token_urlsafe(32) app.secret_key = secret app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///devices.sqlite3' app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False jdatetime.set_locale('fa_IR') app.config['WHOOSH_BASE'] = 'whoosh' Login_manager = LoginManager() Login_manager.init_app(app) db = SQLAlchemy(app) class devices(db.Model): # __searchable__ =['tracking_number','customer_name','customer_phone','device_model','serial_number','property_number','address'] _id = db.Column("id", db.Integer, primary_key=True) tracking_number = db.Column(db.String(100), nullable=False, unique=True) customer_name = db.Column(db.String(100), nullable=False) customer_phone = db.Column(db.String(20)) device_type = db.Column(db.String(100))
def save(self, *args, **kwargs): self.sku = secrets.token_urlsafe(5) super(RulesCategory, self).save(*args, **kwargs)
def generate_rand_id(): """ Return a base64 url safe id of 12 char """ return token_urlsafe(9)
def __init__(self, *args, **kwargs): """Set the join date on initialization.""" super().__init__(*args, **kwargs) self.date_joined = datetime.now() self.token = secrets.token_urlsafe(64)
def credential_pre_save(sender, instance, **kwargs): if not instance.pk: if not instance.ssh_passwd: instance.ssh_passwd = token_urlsafe(15)
def generate_tokens(items): for item in items: item['token'] = token_urlsafe()
def service(): service_data = {"name": fake.first_name(), "description": fake.text(100)} service = Service.create(**service_data, token=secrets.token_urlsafe(31)) yield service service.delete()
def __init__(self, **kwargs): attributes = super().defaults(dict(kwargs)) attributes["secret"] = secrets.token_urlsafe() attributes["api_key"] = secrets.token_urlsafe() attributes.update(kwargs) super().__init__(**attributes)
def create_app(test_config=None): app = Flask(__name__) setup_db(app) CORS(app) oauth = OAuth(app) secret = secrets.token_urlsafe(32) app.secret_key = secret auth0 = oauth.register( 'auth0', client_id=os.environ.get('CLIENT_ID'), client_secret=os.environ.get('CLIENT_SECRET'), api_base_url=os.environ.get('API_BASE_URL'), access_token_url=os.environ.get('ACCESS_TOKEN_URL'), authorize_url=os.environ.get('AUTHORIZE_URL'), client_kwargs={ 'scope': 'openid profile email', }, ) AUTH0_URL = os.environ.get('AUTH0_LOGIN_URL') CORS(app, resources={r"/api/*": {"origins": "*"}}) # ROUTES @app.after_request def after_request(response): response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization,true') response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS') return response # main page @app.route('/') def index(): return 'Hello, friend !' # login page @app.route('/login') def login(): return render_template('login.html', AUTH0_AUTHORIZE_URL=AUTH0_URL) # logout @app.route('/logout') def logout(): # Clear session stored data session.clear() # Redirect user to logout endpoint params = {'returnTo': url_for( 'index', _external=True), 'client_id': '5FmE550Gvrv7iLRl1WxYleKWZx44su3a'} return redirect(auth0.api_base_url + '/v2/logout?' + urlencode(params)) # GET endpoints ################################################################## # retrieves all the actors @app.route('/actors', methods=['GET']) @requires_auth('get:actors') def show_actors(jwt): actors = Actor.query.all() if actors is None: abort(404) actors_list = [] for actor in actors: actors_list.append({ 'actor_id': actor.id, 'actor_name': actor.name, 'actor_age': actor.age, 'actor_gender': actor.gender }) return jsonify({ 'success': True, 'actors': actors_list }) # retrieves all the movies @app.route('/movies', methods=['GET']) @requires_auth('get:movies') def show_movies(jwt): movies = Movie.query.all() if movies is None: abort(404) movies_list = [] for movie in movies: movies_list.append({ 'movie_id': movie.id, 'movie_title': movie.title, 'movie_release_date': movie.release_date }) return jsonify({ 'success': True, 'movies': movies_list }) # retrieves a certain actor @app.route('/actors/<int:actor_id>', methods=['GET']) @requires_auth('get:actor') def show_actor(jwt, actor_id): actor = Actor.query.filter(Actor.id == actor_id).one_or_none() if actor is None: abort(404) return jsonify({ 'success': True, 'name': actor.name, 'age': actor.age, 'gender': actor.gender }) # retrieves a certain movie @app.route('/movies/<int:movie_id>', methods=['GET']) @requires_auth('get:movie') def show_movie(jwt, movie_id): movie = Movie.query.filter(Movie.id == movie_id).one_or_none() if movie is None: abort(404) return jsonify({ 'success': True, 'title': movie.title, 'release_date': movie.release_date }) # Delete endpoints ################################################################## # deletes a certain actor @app.route('/actors/<int:actor_id>', methods=['DELETE']) @requires_auth('delete:actor') def delete_actor(jwt, actor_id): try: actor = Actor.query.filter(Actor.id == actor_id).one_or_none() if actor is None: abort(404) actor.delete() return jsonify({ "success": True, "deleted": actor_id }) except Exception: abort(422) # retrieves a certain movie @app.route('/movies/<int:movie_id>', methods=['DELETE']) @requires_auth('delete:movie') def delete_movie(jwt, movie_id): try: movie = Movie.query.filter(Movie.id == movie_id).one_or_none() if movie is None: abort(404) movie.delete() return jsonify({ "success": True, "deleted": movie_id }) except Exception: abort(422) # POST endpoints ################################################################## # adds a new actor @app.route('/actors', methods=['POST']) @requires_auth('post:actor') def add_actor(jwt): body = request.get_json() if body is None: abort(400) new_name = body.get('name', None) new_age = body.get('age', None) new_gender = body.get('gender', None) try: if new_name and new_age and new_gender: new_actor = Actor( name=new_name, age=new_age, gender=new_gender ) new_actor.insert() return jsonify({ 'success': True, 'created_id': new_actor.id, 'actors': [actor.format() for actor in Actor.query.all()] }) else: abort(422) except Exception: abort(422) # adds a new movie @app.route('/movies', methods=['POST']) @requires_auth('post:movie') def add_movie(jwt): body = request.get_json() if body is None: abort(400) new_title = body.get('title', None) release_date_str = body.get('release_date', None) y, m, d = release_date_str.split('-') new_release_date = datetime(int(y), int(m), int(d)).date() try: if new_title and release_date_str: new_movie = Movie( title=new_title, release_date=new_release_date) new_movie.insert() return jsonify({ 'success': True, 'created_id': new_movie.id, 'movies': [movie.format() for movie in Movie.query.all()] }) else: abort(422) except Exception: abort(422) # PATCH endpoints ################################################################## # updates an existing actor @app.route('/actors/<int:actor_id>', methods=['PATCH']) @requires_auth('patch:actor') def update_actor(jwt, actor_id): actor = Actor.query.filter(Actor.id == actor_id).one_or_none() if actor is None: abort(404) body = request.get_json() if body is None: abort(400) new_name = body.get('name', None) new_age = body.get('age', None) new_gender = body.get('gender', None) try: if new_name: actor.name = new_name if new_age: actor.age = new_age if new_gender: actor.gender = new_gender actor.update() return jsonify({ "success": True, "actor": [actor.format() for actor in Actor.query.all()] }) except Exception: abort(422) # updates an existing movie @app.route('/movies/<int:movie_id>', methods=['PATCH']) @requires_auth('patch:movie') def update_movie(jwt, movie_id): movie = Movie.query.filter(Movie.id == movie_id).one_or_none() if movie is None: abort(404) body = request.get_json() if body is None: abort(400) new_title = body.get('title', None) new_release_date_str = body.get('release_date', None) try: if new_title: movie.title = new_title if new_release_date_str: y, m, d = new_release_date_str.split('-') new_release_date = datetime(int(y), int(m), int(d)).date() movie.release_date = new_release_date movie.update() return jsonify({ "success": True, "movies": [movie.format() for movie in Movie.query.all()] }) except Exception: abort(422) # Error Handling @app.errorhandler(422) def unprocessable(error): return jsonify({ "success": False, "error": 422, "message": "unprocessable" }), 422 @app.errorhandler(404) def not_found(error): return jsonify({ "success": False, "error": 404, "message": "resource not found" }), 404 @app.errorhandler(AuthError) def authentication_error(error): return jsonify({ "success": False, "error": 401, "message": "AuthError" }), 401 @app.errorhandler(400) def bad_request(error): return jsonify({ "success": False, "error": 400, "message": 'bad request' }), 400 return app
def dispatch(self, request, *args, **kwargs): if request.openid_access_token and \ request.openid_access_token.token_type != OpenIDToken.TOKEN_TYPE_CLIENT_DYNAMIC_REGISTRATION: return HttpResponseForbidden( 'Can not use this token to access dynamic registration view') if request.method != 'POST': return HttpResponseBadRequest('Only POST is allowed') try: self.parse_request_parameters(request, DynamicClientRegistrationParameters) try: self.request_parameters.check_errors() except AttributeError as e: raise OAuthError(error=self.attribute_parsing_error, error_description=str(e)) pairwise_key = None if self.request_parameters.sector_identifier_uri: try: redirect_uris = requests.get( self.request_parameters.sector_identifier_uri) redirect_uris = redirect_uris.json() for ru in self.request_parameters.redirect_uris: if ru not in redirect_uris: raise OAuthError( 'invalid_request', 'Redirect URI not in json document pointed by sector_identifier_uri' ) except OAuthError: raise except BaseException as e: raise OAuthError( 'invalid_request', 'Error fetching/parsing sector_identifier_uri at %s: %s' % (self.request_parameters.sector_identifier_uri, str(e))) pairwise_key = urlparse( self.request_parameters.sector_identifier_uri).hostname else: for ru in self.request_parameters.redirect_uris: hostname = urlparse(ru).hostname if pairwise_key and pairwise_key != hostname: raise OAuthError( 'invalid_request', 'In case that redirect_uris do not share the same host, ' 'sector_identifier_uri parameter is required') pairwise_key = hostname if 'pairwise' in self.request_parameters.subject_type: pairwise_key = hashlib.sha256( (pairwise_key + settings.SECRET_KEY).encode('utf-8')).hexdigest() else: pairwise_key = None client_id = secrets.token_urlsafe(32) client_secret = secrets.token_urlsafe(32) client_data = json.loads(request.body.decode('utf-8')) if 'jwks_uri' in client_data: jwks = requests.get(client_data['jwks_uri']).json() elif 'jwks' in client_data: jwks = client_data['jwks'] else: jwks = {'keys': []} jwks = json.dumps(jwks, indent=True) print("registered jwks", jwks) client = OpenIDClient.objects.create( client_id=client_id, redirect_uris='\n'.join(self.request_parameters.redirect_uris), client_auth_type=self.get_auth_type( self.request_parameters.token_endpoint_auth_method), client_name=self.request_parameters.client_name, sub_hash=pairwise_key, client_registration_data=client_data, jwks=jwks) client.set_client_secret(client_secret) client.save() resp = self.make_registration_response(request, client, client_secret) return JsonResponse(resp, status=201) except OAuthError as err: return self.oauth_send_answer( request, { 'error': err.error, 'error_description': err.error_description })
def generate_challenge(): nonce = secrets.token_urlsafe(20) return esp_signer.sign(nonce).decode('ascii')
def generate_password(): return secrets.token_urlsafe(32)
def __init__(self): self.key = secrets.token_urlsafe(self.url_len) self.set_free() self.chat_id = None
from flask import Flask from flask import render_template, redirect, request, session, url_for import secrets, urllib.parse, base64, requests app = Flask(__name__) # need a secret key for session variables app.secret_key = secrets.token_urlsafe(16) # authorization server information auth_server = { 'authorization_endpoint': 'http://localhost:5001/authorize', 'token_endpoint': 'http://localhost:5001/token', 'revocation_endpoint': 'http://localhost:5001/revoke', 'registration_endpoint': 'http://localhost:50001/register', 'userinfo_endpoint': 'http://localhost:5001/userinfo' } rsa_key = { 'alg': 'RS256', 'e': 'AQAB', 'n': 'p8eP5gL1H_H9UNzCuQS-vNRVz3NWxZTHYk1tG9VpkfFjWNKG3MFTNZJ1l5g_COMm2_2i_YhQNH8MJ_nQ4exKMXrWJB4tyVZohovUxfw-eLgu1XQ8oYcVYW8ym6Um-BkqwwWL6CXZ70X81YyIMrnsGTyTV6M8gBPun8g2L8KbDbXR1lDfOOWiZ2ss1CRLrmNM-GRp3Gj-ECG7_3Nx9n_s5to2ZtwJ1GS1maGjrSZ9GRAYLrHhndrL_8ie_9DS2T-ML7QNQtNkg2RvLv4f0dpjRYI23djxVtAylYK4oiT_uEMgSkc4dxwKwGuBxSO0g9JOobgfy0--FUHHYtRi0dOFZw', 'kty': 'RSA', 'kid': 'authserver' } # client information client = { 'client_id': 'oauth-client-1', 'client_secret': 'oauth-client-secret-1', 'redirect_uris': ['http://localhost:5000/callback'],
def _setupSSHDImpl(ngrok_token, ngrok_region): #apt-get update #apt-get upgrade cache = apt.Cache() cache.update() cache.open(None) cache.upgrade() cache.commit() subprocess.run(["unminimize"], input="y\n", check=True, universal_newlines=True) subprocess.run( ["add-apt-repository", "ppa:qbittorrent-team/qbittorrent-stable"]) subprocess.run(["apt-get", "update"]) subprocess.run(["apt-get", "install", "qbittorrent"]) with open("/etc/apt/sources.list.d/mkvtoolnix.download.list", "a") as f: f.write( "\n\ndeb https://mkvtoolnix.download/ubuntu/ bionic main\ndeb-src https://mkvtoolnix.download/ubuntu/ bionic main\n" ) _installPkg(cache, "openssh-server") cache.commit() _installPkg(cache, "mediainfo-gui") cache.commit() #Reset host keys for i in pathlib.Path("/etc/ssh").glob("ssh_host_*_key"): i.unlink() subprocess.run(["ssh-keygen", "-A"], check=True) #Prevent ssh session disconnection. with open("/etc/ssh/sshd_config", "a") as f: f.write("\n\nClientAliveInterval 120\n") msg = "" msg += "Sunucunun ECDSA anahtar parmakizi:\n" ret = subprocess.run( ["ssh-keygen", "-lvf", "/etc/ssh/ssh_host_ecdsa_key.pub"], stdout=subprocess.PIPE, check=True, universal_newlines=True) msg += ret.stdout + "\n" _download( "https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-linux-amd64.zip", "ngrok.zip") shutil.unpack_archive("ngrok.zip") pathlib.Path("ngrok").chmod(stat.S_IXUSR) root_password = secrets.token_urlsafe() user_password = "******" user_name = "bitturk" msg += "✂️" * 24 + "\n" msg += f"root şifresi: {root_password}\n" msg += f"{user_name} şifresi: {user_password}\n" msg += "✂️" * 24 + "\n" subprocess.run(["useradd", "-s", "/bin/bash", "-m", user_name]) subprocess.run(["adduser", user_name, "sudo"], check=True) subprocess.run(["chpasswd"], input=f"root:{root_password}", universal_newlines=True) subprocess.run(["chpasswd"], input=f"{user_name}:{user_password}", universal_newlines=True) subprocess.run(["service", "ssh", "restart"]) if not pathlib.Path('/root/.ngrok2/ngrok.yml').exists(): subprocess.run(["./ngrok", "authtoken", ngrok_token]) ngrok_proc = subprocess.Popen( ["./ngrok", "tcp", "-region", ngrok_region, "22"]) time.sleep(2) if ngrok_proc.poll() != None: raise RuntimeError("Failed to run ngrok. Return code:" + str(ngrok_proc.returncode) + "\nSee runtime log for more info.") with urllib.request.urlopen( "http://*****:*****@{hostname}\n" msg += "✂️" * 24 + "\n" msg += "---\n" msg += "VNC ile bağlanmak için gerekli olan komut:\n" msg += "✂️" * 24 + "\n" msg += f"ssh {ssh_common_options} -L 5901:localhost:5901 -p {port} {user_name}@{hostname}\n" msg += "✂️" * 24 + "\n" return msg
def _generate_token(self): """Generates a secure random token.""" return secrets.token_urlsafe(48)
class Settings(BaseSettings): API_V1_STR: str = "/api/v1" SECRET_KEY: str = secrets.token_urlsafe(32) # 60 minutes * 24 hours * 8 days = 8 days ACCESS_TOKEN_EXPIRE_MINUTES: int = 60 * 24 * 8 SERVER_NAME: str = "server_name" SERVER_HOST: AnyHttpUrl = "http://127.0.0.1" # BACKEND_CORS_ORIGINS is a JSON-formatted list of origins # e.g: '["http://localhost", "http://*****:*****@validator("BACKEND_CORS_ORIGINS", pre=True) def assemble_cors_origins( cls, v: Union[str, List[str]]) -> Union[List[str], str]: if isinstance(v, str) and not v.startswith("["): return [i.strip() for i in v.split(",")] elif isinstance(v, (list, str)): return v raise ValueError(v) PROJECT_NAME: str = "balanced-dex-api" SENTRY_DSN: Optional[HttpUrl] = "http://127.0.0.1" # None @validator("SENTRY_DSN", pre=True) def sentry_dsn_can_be_blank(cls, v: str) -> Optional[str]: if len(v) == 0: return None return v # POSTGRES_SERVER: str # POSTGRES_USER: str # POSTGRES_PASSWORD: str # POSTGRES_DB: str # SQLALCHEMY_DATABASE_URI: Optional[PostgresDsn] = None # @validator("SQLALCHEMY_DATABASE_URI", pre=True) # def assemble_db_connection(cls, v: Optional[str], values: Dict[str, Any]) -> Any: # if isinstance(v, str): # return v # return PostgresDsn.build( # scheme="postgresql", # user=values.get("POSTGRES_USER"), # password=values.get("POSTGRES_PASSWORD"), # host=values.get("POSTGRES_SERVER"), # path=f"/{values.get('POSTGRES_DB') or ''}", # ) SMTP_TLS: bool = True SMTP_PORT: Optional[int] = None SMTP_HOST: Optional[str] = None SMTP_USER: Optional[str] = None SMTP_PASSWORD: Optional[str] = None EMAILS_FROM_EMAIL: Optional[EmailStr] = None EMAILS_FROM_NAME: Optional[str] = None @validator("EMAILS_FROM_NAME") def get_project_name(cls, v: Optional[str], values: Dict[str, Any]) -> str: # print("get_project_name:::::::") # print(values) if not v: return values["PROJECT_NAME"] return v EMAIL_RESET_TOKEN_EXPIRE_HOURS: int = 48 EMAIL_TEMPLATES_DIR: str = "/app/app/email-templates/build" EMAILS_ENABLED: bool = False @validator("EMAILS_ENABLED", pre=True) def get_emails_enabled(cls, v: bool, values: Dict[str, Any]) -> bool: return bool( values.get("SMTP_HOST") and values.get("SMTP_PORT") and values.get("EMAILS_FROM_EMAIL")) EMAIL_TEST_USER: EmailStr = "*****@*****.**" # type: ignore # FIRST_SUPERUSER: EmailStr # FIRST_SUPERUSER_PASSWORD: str USERS_OPEN_REGISTRATION: bool = False REDIS_CONNECTION: str = "redis://redis:6379" MONGODB_HOST: str = "mongodb" MONGODB_PORT: int = 27017 KAFKA_INTERNAL_HOST_PORT: str = "kafka:19092" class Config: case_sensitive = True
def generate_reset_code(): """ Generates a random reset code """ return secrets.token_urlsafe(16)
class Settings(BaseSettings): DATABASE_URL: str = "postgresql://postgres@localhost/market_api" SECRET_KEY: str = secrets.token_urlsafe(32)
def naive_update(): for _ in range(OBJECTS): object = DataModel.objects.get(id=random_id()) object.text = token_urlsafe(75) object.description = token_urlsafe(150) object.save()