def create_room(request): new_room = None while not new_room: with transaction.atomic(): label = Haikunator().haikunate() nickname = request.GET.get('nickname') if nickname: name = nickname else: name = Haikunator().haikunate(token_length=0, delimiter=' ') if Room.objects.filter(label=label).exists(): continue new_room = Room.objects.create(label=label, name=name) if request.user.is_authenticated(): new_room.owner = request.user new_room.save() token = request.GET.get('token') if token: try: widget = Widget.objects.as_token(token) except Widget.DoesNotExist: return new_room new_room.widget = widget new_room.save() logger.debug('created room with label=%s from widget_token=%s', new_room.label, widget.token) context = {'email': widget.owner.email} NewRoomNotifyMailer(request).send(context) return new_room
def test_return_same_with_seed(self): seed = 'definitively random seed' h1 = Haikunator(seed=seed) h2 = Haikunator(seed=seed) self.assertNotEqual(h1.haikunate(), h2.haikunate()) self.assertNotEqual(h1.haikunate(), h2.haikunate())
def test_empty_adjectives_nouns(self): haikunator = Haikunator(adjectives=[], nouns=[], qualities=[], persons=[]) self.assertEqual(haikunator.haikunate(token_chars=''), '')
def new_post(request, pk): board = get_object_or_404(Board, pk=pk) if request.method == 'POST': form = NewPostForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.board = board post.original_poster = request.user new_room = None while not new_room: with transaction.atomic(): haikunator = Haikunator() label = haikunator.haikunate() if Room.objects.filter(label=label).exists(): continue new_room = Room.objects.create( name=form.cleaned_data.get('title'), poster=request.user, label=label) post.room = new_room post.save() return redirect(chat_room, label=label) else: form = NewPostForm() return render(request, 'new_post.html', {'board': board, 'form': form})
def set_cookie(cookie_key): cookie_val = Haikunator().haikunate() rsp_text = 'Cookie "' + cookie_key + '" set to <b>' + cookie_val + '</b>' rsp_text += get_endpoints_description(cookie_key) response = app.make_response(rsp_text) response.set_cookie(cookie_key, value=cookie_val) return response
def upload_file(bill_id): """ Upload File to S3 Bucket """ # First check if bill id attempted to be attached to exists and belongs to user bill = BillModel.get_one_bill(bill_id) if not bill: return custom_response({'error': 'Bill Not Found'}, 404) email_address_in_auth_header = request.authorization.username user_object = UserModel.get_user_by_email(email_address_in_auth_header) user_id = user_object.id if (user_id != bill.owner_id): return custom_response({'error': 'Unauthorized Access to Bill'}, 401) bill_data = bill_schema.dump(bill) # bill exists and belongs to user attempting to post file if 'file' not in request.files: # check if the post request has an attached file custom_response({'error': 'No file part in the request'}, 400) file = request.files['file'] if file.filename == '': custom_response({'error': 'No file selected for uploading'}, 400) if file and allowed_file(file.filename): # check if destination bill already exists in the file models bill_in_question = FileModel.select_file_by_bill_id(bill_id) # since each bill can only have 1 attachment, don't proceed if bill already exists if bill_in_question: # if bill in question exists, can't add another file attachment return custom_response("bill already has file attached, please delete attachment!", 400) s3_resource = boto3.resource('s3') bucketname = "" for bucket in s3_resource.buckets.all(): bucketname = bucket.name content_type = request.mimetype s3_client = boto3.client('s3', region_name='us-east-2', aws_access_key_id=os.environ['ACCESS_KEY'], aws_secret_access_key=os.environ['SECRET_KEY']) file_id = str(uuid.uuid4()) # bill does not contain an attachment so continue to build file metadata filename = secure_filename(file.filename) # This is convenient to validate your filename, otherwise just use file.filename s3_client.put_object(Body=file, Bucket=bucketname, Key=filename, ContentType=content_type) file_size = s3_client.head_object(Bucket=bucketname, Key=filename).get('ContentLength') url = Haikunator().haikunate(delimiter = '.', token_hex = True, token_length = 6) upload_date = str(s3_client.head_object(Bucket=bucketname, Key=filename).get('LastModified')) hash_digest = s3_client.head_object(Bucket=bucketname, Key='filename').get('ETag') file_dict = {'id': file_id, 'url': url, 'hash_digest': hash_digest, 'file_size': file_size, 'upload_date': upload_date, 'file_name': filename, 'file_owner': user_id, 'bill_attached_to': bill_id} file_data = file_schema.load(file_dict) file_object = FileModel(file_data) # save file object to postgresql file table file_object.save() file_http_response = file_schema.dump(file_object) return custom_response(file_http_response, 201) else: return custom_response('Allowed file types are pdf, png, jpg, jpeg', 400)
def create_league(user, name=None, users=None, notify=True): if name is None: haikunator = Haikunator() name = haikunator.haikunate(token_length=0) new_league = League(id=str(ObjectId()), created=datetime.utcnow(), name=name, owner_id=user.id, status=LeagueStatus.CREATED) new_league.owner = user insert_league(new_league) members = [user] if users is not None: members = list(set(members + users)) for member in members: insert_membership(new_league, member) if notify and member.id != user.id: user_added_to_league_notification(member, new_league) return new_league
def test_custom_adjectives_nouns(self): haikunator = Haikunator( adjectives=['adjective'], nouns=['noun'] ) self.assertRegexp(haikunator.haikunate(), 'adjective-noun-\d{4}$')
def setUp(self): # Load Azure app defaults try: with open('azurermconfig.json') as configFile: configData = json.load(configFile) except FileNotFoundError: print("Error: Expecting vmssConfig.json in current folder") sys.exit() tenant_id = configData['tenantId'] app_id = configData['appId'] app_secret = configData['appSecret'] self.subscription_id = configData['subscriptionId'] self.access_token = azurerm.get_access_token(tenant_id, app_id, app_secret) self.location = configData['location'] # create resource names h = Haikunator() self.rgname = h.haikunate() self.service_name = h.haikunate(delimiter='') self.agent_dns = h.haikunate(delimiter='') self.master_dns = h.haikunate(delimiter='') # generate RSA Key for container service key = rsa.generate_private_key(backend=default_backend(), public_exponent=65537, \ key_size=2048) self.public_key = key.public_key().public_bytes(serialization.Encoding.OpenSSH, \ serialization.PublicFormat.OpenSSH).decode('utf-8') # create resource group print('Creating resource group: ' + self.rgname) response = azurerm.create_resource_group(self.access_token, self.subscription_id, \ self.rgname, self.location) self.assertEqual(response.status_code, 201)
def main(): # general purpose objects name_generator = Haikunator() # azure objects proxy_gen = AzureProxyGen() LOCATION = 'eastus' # ask user for inputs proxy_count = int(input("How many proxies would you like to be created? ")) proxy_username = input( "What do you want the proxy authentication username to be? ") proxy_password = input( "What do you want the proxy authentication password to be? ") print("Now creating " + str(proxy_count) + " proxies") ip_list = proxy_gen.create_proxies(proxy_count, LOCATION, 'proxystartupscript', False, proxy_username, proxy_password) proxy_list = [] # test proxies for x in range(len(ip_list)): while proxytester.test_proxy(ip_list[x], proxy_username, proxy_password, "80") == False: print(ip_list[x] + " not yet ready. waiting 5 seconds before testing again") time.sleep(5) proxy_list.append(ip_list[x] + ":80:" + proxy_username + ":" + proxy_password) print("All proxies ready.") print('\n'.join(map(str, proxy_list)))
def setUp(self): # Load Azure app defaults try: with open('azurermconfig.json') as configFile: configData = json.load(configFile) except FileNotFoundError: print("Error: Expecting vmssConfig.json in current folder") sys.exit() tenant_id = configData['tenantId'] app_id = configData['appId'] app_secret = configData['appSecret'] self.subscription_id = configData['subscriptionId'] self.access_token = azurerm.get_access_token(tenant_id, app_id, app_secret) self.location = configData['location'] # generate resource group name self.h = Haikunator() self.rgname = self.h.haikunate() # create resource group print('Creating resource group: ' + self.rgname) response = azurerm.create_resource_group(self.access_token, self.subscription_id, \ self.rgname, self.location) self.assertEqual(response.status_code, 201) # generate vnet name self.vnet = self.h.haikunate(delimiter='') # generate public ip address names self.ipname = self.vnet + 'ip' self.lbipname = self.vnet + 'lbip'
def new_game(request): context = {} context['searchForm'] = SearchUser() user = request.user # edit here if request.method == 'GET': return render(request, 'new_game.html', context) else: # new a game # validate input ??? entry_funds = request.POST['entry_funds'] no_players = request.POST['no_players'] haikunator = Haikunator() game_no = haikunator.haikunate() new_game = Game(creator=request.user, player_num=no_players, entry_funds=entry_funds, game_no=game_no) new_game.save() # new socket here? return render( request, 'game_init_success.html', { "game_no": game_no, "entry_funds": entry_funds, "players": no_players, "email_form": EmailPassword(), "searchForm": SearchUser() })
def test_custom_adjectives_nouns(self): haikunator = Haikunator() haikunator.adjectives = ['red'] haikunator.nouns = ['reindeer'] self.assertRegexp(haikunator.haikunate(), '(red)(-)(reindeer)(-)(\\d{4})$')
def setUp(self): # Load Azure app defaults try: with open('azurermconfig.json') as config_data: config_data = json.load(config_data) except FileNotFoundError: sys.exit("Error: Expecting azurermconfig.json in current folder") self.tenant_id = config_data['tenantId'] self.app_id = config_data['appId'] app_secret = config_data['appSecret'] self.subscription_id = config_data['subscriptionId'] self.access_token = azurerm.get_access_token(self.tenant_id, self.app_id, app_secret) self.location = config_data['location'] h = Haikunator() self.rgname = h.haikunate() self.vault_name = h.haikunate() self.secret_name = h.haikunate() self.secret_value = h.haikunate() # create resource group print('Creating resource group: ' + self.rgname) response = azurerm.create_resource_group(self.access_token, self.subscription_id, \ self.rgname, self.location) self.assertEqual(response.status_code, 201)
def new_game(request): game = Game.objects.filter(in_game='1')[:1] if game.exists(): # non-empty # need to check id as well for i in range(1): label = game[i].label print("new_game_guess", label) in_game = 1 return redirect(guess, label=label, in_game=in_game) # if every game is full, create a new game # the first person who go into the game print("draw") new_game = None while not new_game: with transaction.atomic(): h = Haikunator() label = h.haikunate(delimiter='_') if Game.objects.filter(label=label).exists(): continue new_game = Game.objects.create(label=label, in_game='1') target_list = [ "box", "house", "star", "rocket", "glasses", "tree", "boat", "flower", "bee", "rabbit", "car", "airplane", "lamp", "bonbon", "cat", "bird", "eye", "cloud", "guitar", "castle", "mushroom", "bottle", "bed", "chair", "key", "gun", "phone", "shoe", "book", "train", "pen", "ice cream", "dog", "sun", "moon", "fish", "cheese", "money", "hat", "computer", "squirrel" ] new_game.target_word = random.choice(target_list) new_game.save() print(new_game.target_word) in_game = 1 return redirect(draw, label=label, in_game=in_game)
def test_empty_adjectives_nouns(self): haikunator = Haikunator() haikunator.adjectives = [] haikunator.nouns = [] haiku = haikunator.haikunate(token_chars='') self.assertEqual(haiku, '')
def setUp(self): # Load Azure app defaults try: with open('azurermconfig.json') as config_file: config_data = json.load(config_file) except FileNotFoundError: print("Error: Expecting vmssConfig.json in current folder") sys.exit() tenant_id = config_data['tenantId'] app_id = config_data['appId'] app_secret = config_data['appSecret'] self.subscription_id = config_data['subscriptionId'] self.access_token = azurerm.get_access_token( tenant_id, app_id, app_secret) # self.location = config_data['location'] # comment out during preview self.location = 'westus' # create resource names haik = Haikunator() self.rgname = haik.haikunate() self.container_name = haik.haikunate(delimiter='') self.container_name2 = haik.haikunate(delimiter='') self.container_group_name = haik.haikunate(delimiter='') # create resource group print('Creating resource group: ' + self.rgname) response = azurerm.create_resource_group(self.access_token, self.subscription_id, self.rgname, self.location) self.assertEqual(response.status_code, 201)
def test_general_functionality(self): tests = [ [{}, '[a-z]+-[a-z]+-[0-9]{4}$'], [{ 'token_hex': True }, '[a-z]+-[a-z]+-[0-f]{4}$'], [{ 'token_length': 9 }, '[a-z]+-[a-z]+-[0-9]{9}$'], [{ 'token_length': 9, 'token_hex': True }, '[a-z]+-[a-z]+-[0-f]{9}$'], [{ 'token_length': 0 }, '[a-z]+-[a-z]+$'], [{ 'delimiter': '.' }, '[a-z]+.[a-z]+.[0-9]{4}$'], [{ 'token_length': 0, 'delimiter': ' ' }, '[a-z]+ [a-z]+'], [{ 'token_length': 0, 'delimiter': '' }, '[a-z]+$'], [{ 'token_chars': 'xyz' }, '[a-z]+-[a-z]+-[x-z]{4}$'], ] haikunator = Haikunator() for test in tests: self.assertRegexp(haikunator.haikunate(**test[0]), test[1])
class Deployer(object): """ Initialize the deployer class with subscription, resource group and public key. :raises IOError: If the public key path cannot be read (access or not exists) :raises KeyError: If AZURE_CLIENT_ID, AZURE_CLIENT_SECRET or AZURE_TENANT_ID env variables or not defined """ name_generator = Haikunator() def __init__(self, subscription_id, resource_group, pub_ssh_key_path='~/.ssh/id_rsa.pub'): self.subscription_id = subscription_id self.resource_group = resource_group self.dns_label_prefix = self.name_generator.haikunate() pub_ssh_key_path = os.path.expanduser(pub_ssh_key_path) # Will raise if file not exists or not enough permission with open(pub_ssh_key_path, 'r') as pub_ssh_file_fd: self.pub_ssh_key = pub_ssh_file_fd.read() self.credentials = ServicePrincipalCredentials( client_id=os.environ['AZURE_CLIENT_ID'], secret=os.environ['AZURE_CLIENT_SECRET'], tenant=os.environ['AZURE_TENANT_ID']) self.client = ResourceManagementClient(self.credentials, self.subscription_id) def deploy(self): """Deploy the template to a resource group.""" self.client.resource_groups.create_or_update(self.resource_group, {'location': 'westus'}) template_path = os.path.join(os.path.dirname(__file__), 'templates', 'template.json') with open(template_path, 'r') as template_file_fd: template = json.load(template_file_fd) parameters = { 'sshKeyData': self.pub_ssh_key, 'vmName': 'azure-deployment-sample-vm', 'dnsLabelPrefix': self.dns_label_prefix } parameters = {k: {'value': v} for k, v in parameters.items()} deployment_properties = { 'mode': DeploymentMode.incremental, 'template': template, 'parameters': parameters } deployment_async_operation = self.client.deployments.create_or_update( self.resource_group, 'azure-sample', deployment_properties) deployment_async_operation.wait() def destroy(self): """Destroy the given resource group""" self.client.resource_groups.delete(self.resource_group)
def __init__(self): self.config = KeyVaultSampleConfig() self.credentials = None self.keyvault_data_client = None self.keyvault_mgmt_client = None self.resource_mgmt_client = None self._setup_complete = False self._haikunator = Haikunator()
def generate_id(): haikunator = Haikunator() ids = get_cluster_ids_in_authorized_keys() while True: cluster_id = haikunator.haikunate(token_length=6, token_hex=True) if cluster_id not in ids: break return cluster_id
def set_unique_ballot_code(self): haikunator = Haikunator() code = haikunator.haikunate(token_length=0) while Judge.objects.filter(ballot_code=code).first(): code = haikunator.haikunate(token_length=0) self.ballot_code = code
def save(self, *args, **kwargs): if self.pk is None: haikunator = Haikunator() self.username = haikunator.haikunate(token_length=0, delimiter='') while User.objects.filter(username=self.username).exists(): self.username = haikunator.haikunate(token_length=0, delimiter='') super().save(*args, **kwargs)
def main(): '''Main routine.''' # validate command line arguments arg_parser = argparse.ArgumentParser() arg_parser.add_argument('--uri', '-u', required=True, action='store', help='Template URI') arg_parser.add_argument('--params', '-p', required=True, action='store', help='Parameters json file') arg_parser.add_argument('--rg', '-g', required=True, action='store', help='Resource Group name') arg_parser.add_argument('--sub', '-s', required=False, action='store', help='subscription id (optional)') args = arg_parser.parse_args() template_uri = args.uri params = args.params rgname = args.rg subscription_id = args.sub # load parameters file try: with open(params) as params_file: param_data = json.load(params_file) except FileNotFoundError: print('Error: Expecting ' + params + ' in current folder') sys.exit() access_token = azurerm.get_access_token_from_cli() if subscription_id is None: subscription_id = azurerm.get_subscription_from_cli() deployment_name = Haikunator().haikunate() print('Deployment name:' + deployment_name) deploy_return = azurerm.deploy_template_uri(access_token, subscription_id, rgname, deployment_name, template_uri, param_data) print( json.dumps(deploy_return.json(), sort_keys=False, indent=2, separators=(',', ': ')))
class Deployer(object): """ Initialize the deployer class with subscription, resource group and public key. :raises IOError: If the public key path cannot be read (access or not exists) :raises KeyError: If AZURE_CLIENT_ID, AZURE_CLIENT_SECRET or AZURE_TENANT_ID env variables or not defined """ name_generator = Haikunator() def __init__(self, user, passwd, subscription_id, resource_group): self.subscription_id = subscription_id self.resource_group = resource_group self.dns_label_prefix = self.name_generator.haikunate() self.credentials = UserPassCredentials(user, passwd) self.client = ResourceManagementClient(self.credentials, self.subscription_id) def deploy(self): """Deploy the template to a resource group.""" self.client.resource_groups.create_or_update( self.resource_group, {'location': 'westeurope'}) template_path = os.path.join(os.path.dirname(__file__), 'config', 'azuredeploy.json') with open(template_path, 'r') as tpl_file: template = json.load(tpl_file) tpl_file.close() # parameters_path = os.path.join(os.path.dirname(__file__), 'config', 'azuredeploy.parameters.json') # with open(parameters_path, 'r') as param_file: # # params = json.load(param_file) # params = json.loads(param_file) # param_file.close() params = { 'adminUsername': '', 'adminPassword': '', 'vmName': 'elastic' } params = {k: {'value': v} for k, v in params.items()} # params must be a dictionnary deployment_properties = { 'mode': DeploymentMode.incremental, 'template': template, 'parameters': params } deployment_async_operation = self.client.deployments.create_or_update( self.resource_group, 'Invivoo-elastic-deployment', deployment_properties) deployment_async_operation.wait() def destroy(self): """Destroy the given resource group""" self.client.resource_groups.delete(self.resource_group)
def __init__(self, data): self.id = data.get('id') self.file_name = data.get('file_name') self.url = Haikunator().haikunate(delimiter = '.', token_hex = True, token_length = 6) self.upload_date = datetime.datetime.utcnow() self.file_size = data.get('file_size') self.file_origin = data.get('file_origin') self.hash_digest = data.get('hash_digest') self.file_owner = data.get('file_owner') self.bill_attached_to = data.get('bill_attached_to')
def init_trips(trips): from haikunator import Haikunator h = Haikunator() origin_cities = [ 'San Francisco, USA', 'New York City, USA', 'Chicago, USA' ] dest_cities = [ 'San José - Juan Santamaría', 'San José - Tobías Bolaños', 'Limón International', 'Liberia - Daniel Oduber Quirós' ] for i in range(trips): # create user user_id = uuid4() password = '******' username = h.haikunate() salt = crypto.salt() user = { 'user_id': user_id.__str__(), 'user': username, 'email': '*****@*****.**', 'salt': salt, 'hash': crypto.hash(password, username, salt) } db['users'].insert(user) user = db['users'].find_one(user_id=user_id.__str__()) departure_date = datetime.datetime(2017, random.choice(range(3,7)), random.choice(range(1,30)), \ random.choice(range(1,24)), random.choice(range(1,60)),1 ) incremented_day = departure_date.day + 1 arrival_date = datetime.datetime(departure_date.year, departure_date.month, incremented_day, random.choice(range(1, 24)), random.choice(range(1, 60)), 1) # create trip db['trips'].insert({ 'origin': random.choice(origin_cities), 'traveller_id': user['id'], 'destination': random.choice(dest_cities), 'departure_date': departure_date, 'arrival_date': arrival_date, 'flight_number': 'FA-{}'.format(random.choice(range(100, 300))), 'size': random.choice(['small', 'medium', 'large']), 'created_at': datetime.datetime.now() })
def main(): '''Main routine.''' # validate command line arguments arg_parser = argparse.ArgumentParser() arg_parser.add_argument('--uri', '-u', required=True, action='store', help='Template URI') arg_parser.add_argument('--params', '-p', required=True, action='store', help='Parameters json file') arg_parser.add_argument('--rg', '-g', required=True, action='store', help='Resource Group name') args = arg_parser.parse_args() template_uri = args.uri params = args.params rgname = args.rg # Load Azure app defaults try: with open('azurermconfig.json') as config_file: config_data = json.load(config_file) except FileNotFoundError: print('Error: Expecting azurermconfig.json in current folder') sys.exit() tenant_id = config_data['tenantId'] app_id = config_data['appId'] app_secret = config_data['appSecret'] subscription_id = config_data['subscriptionId'] # load parameters file try: with open(params) as params_file: param_data = json.load(params_file) except FileNotFoundError: print('Error: Expecting ' + params + ' in current folder') sys.exit() access_token = azurerm.get_access_token(tenant_id, app_id, app_secret) deployment_name = Haikunator().haikunate() print('Deployment name:' + deployment_name) deploy_return = azurerm.deploy_template_uri(access_token, subscription_id, rgname, deployment_name, template_uri, param_data) print(deploy_return)
def get_or_create_guest_account(self, user, request): custom_user, username = LazyUser.objects.create_lazy_user() haikunator = Haikunator() usernames = [user.username for user in CustomUser.objects.all()] guest_name = haikunator.haikunate(token_length=0) while guest_name in usernames: guest_name = haikunator.haikunate(token_length=0) custom_user.nickname = guest_name custom_user.save() new_lazy_user = LazyUser.objects.get(user__username=username) return new_lazy_user
def set_cookie(cookie_key): cookie_val = Haikunator().haikunate() rsp_text = 'Cookie "' + cookie_key + '" set to <b>' + cookie_val + '</b>' rsp_text += get_endpoints_description(cookie_key) response = app.make_response(rsp_text) # set the cookie with an expirty date / "max-age" / "expires" param per this SO answer # https://stackoverflow.com/questions/46569570/sfauthenticationsession-isnt-sharing-cookies-on-the-real-devices expire_date = datetime.datetime.now() expire_date = expire_date + datetime.timedelta(days=90) response.set_cookie(cookie_key, value=cookie_val, expires=expire_date) return response