Python secrets.token_urlsafe() Examples
The following are 30
code examples of secrets.token_urlsafe().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
secrets
, or try the search function
.
Example #1
Source File: WfModule.py From cjworkbench with GNU Affero General Public License v3.0 | 6 votes |
def duplicate_into_same_workflow(self, to_tab): # Make sure we're calling this correctly assert to_tab.workflow_id == self.workflow_id # Generate a new slug: 9 bytes, base64-encoded, + and / becoming - and _. # Mimics assets/js/utils.js:generateSlug() slug = "step-" + secrets.token_urlsafe(9) # last_relevant_delta_id is _wrong_, but we need to set it to # something. See DuplicateTabCommand to understand the chicken-and-egg # dilemma. last_relevant_delta_id = self.last_relevant_delta_id return self._duplicate_with_slug_and_delta_id( to_tab, slug, last_relevant_delta_id )
Example #2
Source File: views.py From healthchecks with BSD 3-Clause "New" or "Revised" License | 6 votes |
def add_pushbullet(request, code): project = _get_project_for_user(request, code) redirect_uri = settings.SITE_ROOT + reverse("hc-add-pushbullet-complete") state = token_urlsafe() authorize_url = "https://www.pushbullet.com/authorize?" + urlencode( { "client_id": settings.PUSHBULLET_CLIENT_ID, "redirect_uri": redirect_uri, "response_type": "code", "state": state, } ) ctx = { "page": "channels", "project": project, "authorize_url": authorize_url, } request.session["add_pushbullet"] = (state, str(project.code)) return render(request, "integrations/add_pushbullet.html", ctx)
Example #3
Source File: ch13_ex5.py From Mastering-Object-Oriented-Python-Second-Edition with MIT License | 6 votes |
def create_roll() -> Tuple[Any, HTTPStatus, Dict[str, Any]]: body = request.get_json(force=True) if set(body.keys()) != {"dice"}: raise BadRequest(f"Extra fields in {body!r}") try: n_dice = int(body["dice"]) except ValueError as ex: raise BadRequest(f"Bad 'dice' value in {body!r}") roll = [random.randint(1, 6) for _ in range(n_dice)] identifier = secrets.token_urlsafe(8) SESSIONS[identifier] = roll current_app.logger.info(f"Rolled roll={roll!r}, id={identifier!r}") headers = {"Location": url_for("roll.get_roll", identifier=identifier)} return jsonify( roll=roll, identifier=identifier, status="Created" ), HTTPStatus.CREATED, headers
Example #4
Source File: views.py From healthchecks with BSD 3-Clause "New" or "Revised" License | 6 votes |
def add_slack_btn(request, code): project = _get_project_for_user(request, code) state = token_urlsafe() authorize_url = "https://slack.com/oauth/v2/authorize?" + urlencode( { "scope": "incoming-webhook", "client_id": settings.SLACK_CLIENT_ID, "state": state, } ) ctx = { "project": project, "page": "channels", "authorize_url": authorize_url, } request.session["add_slack"] = (state, str(project.code)) return render(request, "integrations/add_slack_btn.html", ctx)
Example #5
Source File: views.py From bitcart with MIT License | 6 votes |
def on_connect(self, websocket, **kwargs): await websocket.accept() self.channel_name = secrets.token_urlsafe(32) try: self.invoice_id = int(websocket.path_params["model_id"]) except (ValueError, KeyError): await websocket.close(code=WS_1008_POLICY_VIOLATION) return self.invoice = ( await models.Invoice.query.select_from(get_invoice()) .where(models.Invoice.id == self.invoice_id) .gino.first() ) if not self.invoice: await websocket.close(code=WS_1008_POLICY_VIOLATION) return if self.invoice.status != "Pending": await websocket.send_json({"status": self.invoice.status}) await websocket.close() return self.invoice = await crud.get_invoice(self.invoice_id, None, self.invoice) self.subscriber, self.channel = await utils.make_subscriber(self.invoice_id) settings.loop.create_task(self.poll_subs(websocket))
Example #6
Source File: errors_core.py From cape-webservices with Apache License 2.0 | 6 votes |
def _500(request, exception): error_id = secrets.token_urlsafe(32) if exception.__class__ is UserException: debug("User exception: %s" % exception.message, exc_info=True) message = exception.message elif exception.__class__ is json.JSONDecodeError: debug(ERROR_INVALID_JSON, exc_info=True,error_id=error_id) message = ERROR_INVALID_JSON elif exception.__class__ is InvalidUsage : debug(ERROR_INVALID_USAGE, exc_info=True) message = ERROR_INVALID_USAGE else: warning("Exception in API", exc_info=True) message = ERROR_TEXT return jsonify({'success': False, 'result': {'message': message,'errorId':error_id}}, status=500, headers=generate_cors_headers(request))
Example #7
Source File: command.py From botamusique with MIT License | 6 votes |
def cmd_web_access(bot, user, text, command, parameter): auth_method = var.config.get("webinterface", "auth_method") if auth_method == 'token': interface.banned_ip = [] interface.bad_access_count = {} user_info = var.db.get("user", user, fallback='{}') user_dict = json.loads(user_info) if 'token' in user_dict: var.db.remove_option("web_token", user_dict['token']) token = secrets.token_urlsafe(5) user_dict['token'] = token user_dict['token_created'] = str(datetime.datetime.now()) user_dict['last_ip'] = '' var.db.set("web_token", token, user) var.db.set("user", user, json.dumps(user_dict)) access_address = var.config.get("webinterface", "access_address") + "/?token=" + token else: access_address = var.config.get("webinterface", "access_address") bot.send_msg(constants.strings('webpage_address', address=access_address), text)
Example #8
Source File: manager.py From manager with GNU General Public License v3.0 | 6 votes |
def refresh_user_token(user_name): # check user exists first user_exists = mongo_connection.mongo_check_user_exists(user_name) if user_exists is False: return jsonify({"user_name": False}), 403 # get current user data and update the token for him try: new_token = secrets.token_urlsafe() app_exists, user_json = mongo_connection.mongo_get_user(user_name) user_json["token"] = hash_secret(new_token) except: return jsonify({"token_refreshed": False}), 403 # update db user_json = mongo_connection.mongo_update_user(user_name, user_json) return jsonify({"token": new_token}), 200 # create new user
Example #9
Source File: manager.py From manager with GNU General Public License v3.0 | 6 votes |
def create_user(user_name): # check app does't exists first user_exists = mongo_connection.mongo_check_user_exists(user_name) if user_exists is True: return jsonify({"user_exists": True}), 403 else: # check the request is passed with all needed parameters try: user_json = request.json except: return jsonify({"missing_parameters": True}), 400 try: # hash the password & token, if not declared generates them randomly password = hash_secret(return_sane_default_if_not_declared("password", user_json, secrets.token_urlsafe())) token = hash_secret(return_sane_default_if_not_declared("token", user_json, secrets.token_urlsafe())) except: return jsonify({"missing_parameters": True}), 400 # update the db user_json = mongo_connection.mongo_add_user(user_name, password, token) return dumps(user_json), 200 # create new user_group
Example #10
Source File: qutescheme.py From qutebrowser with GNU General Public License v3.0 | 6 votes |
def qute_settings(url: QUrl) -> _HandlerRet: """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
Example #11
Source File: container_init.py From starbelly with MIT License | 6 votes |
def init_config(): ''' If local.ini does not exist, then create it. ''' local_ini_path = get_path('conf/local.ini') if not local_ini_path.exists(): logger.info('Creating conf/local.ini') template_path = get_path('conf/local.ini.template') shutil.copyfile(template_path, local_ini_path) config = configparser.ConfigParser() config.optionxform = str config.read([local_ini_path]) config['database']['host'] = 'db' config['database']['db'] = 'starbelly' config['database']['user'] = 'starbelly-app' config['database']['password'] = secrets.token_urlsafe(nbytes=15) config['database']['super_user'] = 'admin' config['database']['super_password'] = secrets.token_urlsafe(nbytes=15) with open(local_ini_path, 'w') as local_ini: config.write(local_ini)
Example #12
Source File: utils.py From DeepPavlov with Apache License 2.0 | 6 votes |
def _get_download_token() -> str: """Return a download token from ~/.deeppavlov/token file. If token file does not exists, creates the file and writes to it a random URL-safe text string containing 32 random bytes. Returns: 32 byte URL-safe text string from ~/.deeppavlov/token. """ token_file = Path.home() / '.deeppavlov' / 'token' if not token_file.exists(): if token_file.parent.is_file(): token_file.parent.unlink() token_file.parent.mkdir(parents=True, exist_ok=True) token_file.write_text(secrets.token_urlsafe(32), encoding='utf8') return token_file.read_text(encoding='utf8').strip()
Example #13
Source File: test_reloader.py From sanic with MIT License | 6 votes |
def write_app(filename, **runargs): text = secrets.token_urlsafe() with open(filename, "w") as f: f.write( dedent( f"""\ import os from sanic import Sanic app = Sanic(__name__) @app.listener("after_server_start") def complete(*args): print("complete", os.getpid(), {text!r}) if __name__ == "__main__": app.run(**{runargs!r}) """ ) ) return text
Example #14
Source File: auth.py From friendly-telegram with GNU Affero General Public License v3.0 | 5 votes |
def check_code(self, request): code, uid = (await request.text()).split("\n") uid = int(uid) if uid not in self._uid_to_code: return web.Response(status=404) if self._uid_to_code[uid] == code: del self._uid_to_code[uid] secret = secrets.token_urlsafe() asyncio.ensure_future(asyncio.shield(self._clear_secret(secret))) self._secret_to_uid[secret] = uid # If they just signed in, they automatically are authenticated return web.Response(text=secret) else: return web.Response(status=401)
Example #15
Source File: test_protocols.py From shadowproxy with MIT License | 5 votes |
def test_ss2(): cipher = AES256CFB(secrets.token_urlsafe(20)) iv, encrypt = cipher.make_encrypter() parser = ss_reader.parser(cipher) parser.send(iv) assert parser.read_output_bytes() == b"" assert parser.read_output_bytes() == b"" data = os.urandom(20) parser.send(encrypt(data)) assert parser.read_output_bytes() == data
Example #16
Source File: test_protocols.py From shadowproxy with MIT License | 5 votes |
def test_ss(): cipher = AES256CFB(secrets.token_urlsafe(20)) iv, encrypt = cipher.make_encrypter() length = len(iv) // 2 parser = ss_reader.parser(cipher) parser.send(iv[:length]) assert parser.read_output_bytes() == b"" data = os.urandom(20) parser.send(iv[length:] + encrypt(data)) assert parser.read_output_bytes() == data
Example #17
Source File: apikeys.py From amivapi with GNU Affero General Public License v3.0 | 5 votes |
def generate_tokens(items): for item in items: item['token'] = token_urlsafe()
Example #18
Source File: sqlalchemy_socket.py From QCFractal with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _generate_password() -> str: """ Generates a random password e.g. for add_user and modify_user. Returns ------- str An unhashed random password. """ return secrets.token_urlsafe(32)
Example #19
Source File: test_secrets.py From android_universal with MIT License | 5 votes |
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))
Example #20
Source File: test_secrets.py From android_universal with MIT License | 5 votes |
def test_token_defaults(self): # Test that token_* functions handle default size correctly. for func in (secrets.token_bytes, secrets.token_hex, secrets.token_urlsafe): with self.subTest(func=func): name = func.__name__ try: func() except TypeError: self.fail("%s cannot be called with no argument" % name) try: func(None) except TypeError: self.fail("%s cannot be called with None" % name) size = secrets.DEFAULT_ENTROPY self.assertEqual(len(secrets.token_bytes(None)), size) self.assertEqual(len(secrets.token_hex(None)), 2*size)
Example #21
Source File: main.py From Remixatron with Apache License 2.0 | 5 votes |
def whoami(): """ Called first by the client, this sets up the device id and the message and process queues. Returns: flask.Response: the device id for the client """ # if this client doesn't already have a device id configured and # saved in a cookie, then set one up. deviceid = get_userid() if deviceid == None: deviceid = secrets.token_urlsafe(16) resp = make_response(deviceid,200) resp.set_cookie('deviceid',deviceid,max_age=31536000) return resp print( deviceid + ' has connected') # make sure the message queues and process queue is setup # for this client. if deviceid not in messageQueues: messageQueues[deviceid] = collections.deque(maxlen=50) if deviceid not in procMap: procMap[deviceid] = None return deviceid
Example #22
Source File: sessions.py From amivapi with GNU Affero General Public License v3.0 | 5 votes |
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
Example #23
Source File: main.py From Remixatron with Apache License 2.0 | 5 votes |
def on_connect(): """ This gets fired when the client connects (or re-connects) via the socketio library. (See https://www.socket.io for more details) Returns: flask.Response: a Flask Response object """ deviceid = get_userid() print('******** ' + get_userid() + ' has connected. ********') # if there's no device id already set for the client, create one and # store it if deviceid == None: deviceid = secrets.token_urlsafe(16) resp = make_response(deviceid,200) resp.set_cookie('deviceid',deviceid, max_age=31536000) return resp print( deviceid + ' has connected') # make sure there's an entry for this device in the messageQueues dictionary if deviceid not in messageQueues: messageQueues[deviceid] = collections.deque(maxlen=50)
Example #24
Source File: ch15_ex5.py From Functional-Python-Programming-Second-Edition with MIT License | 5 votes |
def make_key_5(size=1): """ Creates a 24*size character key """ return secrets.token_urlsafe(18*size)
Example #25
Source File: ch13_ex3.py From Mastering-Object-Oriented-Python-Second-Edition with MIT License | 5 votes |
def make_dice(n_dice: int) -> Dice: # Could also be a @classmethod return Dice( roll=[random.randint(1, 6) for _ in range(n_dice)], identifier=secrets.token_urlsafe(8), status=Status.CREATED, ) # FLASK Restful Web Service # =========================
Example #26
Source File: models.py From bitcart with MIT License | 5 votes |
def create(cls, **kwargs): kwargs["id"] = secrets.token_urlsafe() return await super().create(**kwargs)
Example #27
Source File: views.py From bitcart with MIT License | 5 votes |
def on_connect(self, websocket, **kwargs): await websocket.accept() self.channel_name = secrets.token_urlsafe(32) try: self.wallet_id = int(websocket.path_params["model_id"]) self.access_token = websocket.query_params["token"] except (ValueError, KeyError): await websocket.close(code=WS_1008_POLICY_VIOLATION) return try: self.user = await utils.AuthDependency(token=self.access_token)( None, SecurityScopes(["wallet_management"]) ) except HTTPException: await websocket.close(code=WS_1008_POLICY_VIOLATION) return self.wallet = ( await models.Wallet.query.select_from(get_wallet()) .where(models.Wallet.id == self.wallet_id) .gino.first() ) if not self.wallet: await websocket.close(code=WS_1008_POLICY_VIOLATION) return self.subscriber, self.channel = await utils.make_subscriber(self.wallet_id) settings.loop.create_task(self.poll_subs(websocket))
Example #28
Source File: wf_module.py From cjworkbench with GNU Affero General Public License v3.0 | 5 votes |
def reset_file_upload_api_token( workflow: Workflow, wf_module: WfModule, **kwargs ): api_token = secrets.token_urlsafe() await _do_set_file_upload_api_token(wf_module, api_token) return {"apiToken": api_token}
Example #29
Source File: utils.py From pokemon-random with GNU Affero General Public License v3.0 | 5 votes |
def randomize(dir, checker): for file in os.listdir(dir): name = file.split(".") if name[0].endswith(checker): pass else: os.rename( f"{dir}/{file}", f"{dir}/{secrets.token_urlsafe(8)}{checker}.{name[1]}" )
Example #30
Source File: list_serializers.py From cccatalog-api with MIT License | 5 votes |
def save(self): title = self.validated_data['title'] images = self.validated_data['images'] auth = secrets.token_urlsafe(48) image_list = ImageList(title=title, auth=auth) image_list.save() image_list.images.add(*images) return image_list