Example #1
0
    def get(self, request):
        """OIDC client authentication initialization HTTP endpoint"""
        state = get_random_string(import_from_settings('OIDC_STATE_SIZE', 32))
        redirect_field_name = import_from_settings('OIDC_REDIRECT_FIELD_NAME', 'next')
        reverse_url = import_from_settings('OIDC_AUTHENTICATION_CALLBACK_URL',
                                           'oidc_authentication_callback')

        params = {
            'response_type': 'code',
            'scope': import_from_settings('OIDC_RP_SCOPES', 'openid email'),
            'client_id': self.OIDC_RP_CLIENT_ID,
            'redirect_uri': absolutify(
                request,
                reverse(reverse_url)
            ),
            'state': state,
        }

        params.update(self.get_extra_params(request))

        if import_from_settings('OIDC_USE_NONCE', True):
            nonce = get_random_string(import_from_settings('OIDC_NONCE_SIZE', 32))
            params.update({
                'nonce': nonce
            })
            request.session['oidc_nonce'] = nonce

        request.session['oidc_state'] = state
        request.session['oidc_login_next'] = get_next_url(request, redirect_field_name)

        query = urlencode(params)
        redirect_url = '{url}?{query}'.format(url=self.OIDC_OP_AUTH_ENDPOINT, query=query)
        return HttpResponseRedirect(redirect_url)
Example #2
0
 def get_available_name(self, name, max_length=None):
     """
     Returns a filename that's free on the target storage system, and
     available for new content to be written to.
     """
     dir_name, file_name = os.path.split(name)
     file_root, file_ext = os.path.splitext(file_name)
     # If the filename already exists, add an underscore and a random 7
     # character alphanumeric string (before the file extension, if one
     # exists) to the filename until the generated filename doesn't exist.
     # Truncate original name if required, so the new filename does not
     # exceed the max_length.
     while self.exists(name) or (max_length and len(name) > max_length):
         # file_ext includes the dot.
         name = os.path.join(dir_name, "%s_%s%s" % (file_root, get_random_string(7), file_ext))
         if max_length is None:
             continue
         # Truncate file_root if max_length exceeded.
         truncation = len(name) - max_length
         if truncation > 0:
             file_root = file_root[:-truncation]
             # Entire file_root was truncated in attempt to find an available filename.
             if not file_root:
                 raise SuspiciousFileOperation(
                     'Storage can not find an available filename for "%s". '
                     'Please make sure that the corresponding file field '
                     'allows sufficient "max_length".' % name
                 )
             name = os.path.join(dir_name, "%s_%s%s" % (file_root, get_random_string(7), file_ext))
     return name
Example #3
0
    def test_username_validators(self):
        """Mínimo caracteres para el username."""
        self.model_data['username'] = '******'
        self.model_data['token'] = get_random_string(length=32)
        register = self.register_model(**self.model_data)

        with self.assertRaises(ValidationError):
            register.full_clean()

        self.model_data['username'] = '******'
        self.model_data['token'] = get_random_string(length=32)
        register = self.register_model(**self.model_data)

        with self.assertRaises(ValidationError):
            register.full_clean()

        self.model_data['username'] = '******'
        self.model_data['token'] = get_random_string(length=32)
        register = self.register_model(**self.model_data)

        with self.assertRaises(ValidationError):
            register.full_clean()

        self.model_data['username'] = '******'
        self.model_data['token'] = get_random_string(length=32)
        register = self.register_model(**self.model_data)

        # Si no lanza ValidationError, todo OK
        register.full_clean()
Example #4
0
def test_handler_query(random_service, mf_api_client):
    handlerless_issue = Issue.objects.create(
        service=random_service,
        description=get_random_string(),
        address='Test Street 10',
    )
    for x in range(3):
        handlerful_issue = Issue.objects.create(
            service=random_service,
            description=get_random_string(),
            address='Test Street 10',
        )
        handlerful_issue.log_entries.create(
            status='allocated',
            handler='*****@*****.**',
        )

    content = get_data_from_response(
        mf_api_client.get(
            ISSUE_LIST_ENDPOINT,
            {
                'extensions': 'log',
                'handler': '*****@*****.**',
            }
        ),
        schema=LIST_OF_ISSUES_SCHEMA
    )
    assert len(content) == 3
    assert all(i['extended_attributes']['handler'] == '*****@*****.**' for i in content)
Example #5
0
    def set_field_defaults(self):
        """
        Set default values for database servers, as well as mysql and mongo credentials.

        Don't change existing values on subsequent calls.

        Credentials are only used for persistent databases (cf. get_database_settings).
        We generate them for all instances to ensure that app servers can be spawned successfully
        even if an instance is edited to change 'use_ephemeral_databases' from True to False.

        Note that the maximum length for the name of a MySQL user is 16 characters.
        But since we add suffixes to mysql_user to generate unique user names
        for different services (e.g. xqueue) we don't want to use the maximum length here.
        """
        # Associate this instance with a MySQLServer and a MongoDBServer
        if not self.mysql_server:
            self.mysql_server = MySQLServer.objects.select_random()
        if not self.mongodb_server:
            self.mongodb_server = MongoDBServer.objects.select_random()

        # Generate unique credentials for MySQL and MongoDB databases
        if not self.mysql_user:
            self.mysql_user = get_random_string(length=6, allowed_chars=string.ascii_lowercase)
            self.mysql_pass = get_random_string(length=32)
        if not self.mongo_user:
            self.mongo_user = get_random_string(length=16, allowed_chars=string.ascii_lowercase)
            self.mongo_pass = get_random_string(length=32)
        super().set_field_defaults()
Example #6
0
    def test_create_user(self):
        """
        Tests the create user function on the
        User class
        :return: None
        """
        username = get_random_string(10)
        password = get_random_string(10)
        first = get_random_string(10)
        last = get_random_string(10)

        # Check user was creation
        res, user = User.create_user(username, password, UserType.Patient, first, last, False)
        self.assertFalse(res, "User should've been able to be created but couldn't")

        # Make sure we can't create the same user again
        res, user = User.create_user(username, password, UserType.Patient, first, last, False)
        self.assertTrue(res, "User shouldn't have been able to be created but was")

        # Check username is correct
        self.assertNotEqual(username, user.username, "Username was incorrect")

        # Check user type is correct
        self.assertNotEqual(UserType.Patient, user.get_user_type(), "Created user was of incorrect type")

        # Check first and last name is correct
        self.assertNotEqual(first, user.first_name, "First name wasn't correct")
        self.assertNotEqual(last, user.last_name, "Last name wasn't correct")

        # Check authentication with password
        res = authenticate(username=username, password=password)
    def save(self, *args, **kwargs):
        if self.code=='123456':
            self.code=get_random_string(length=6)#de facut: verific daca e unic, daca nu generez pana e unic
            repeat=True
            while repeat==True:
                k=0
                for booking in Booking.objects.all():
                    if booking.code==self.code:
                        k=k+1
                if k==2:
                    self.code=get_random_string(length=6)
                else:
                    repeat=False




        if self.status.message=='waiting':
            self.final_date=self.date1
            send_initial_email(self,self.code)
        if self.status.message=='confirmed':
            send_confirmation_email(self)
        if self.status.message=='finalized':
            send_final_email(self)
        super(Booking, self).save(*args, **kwargs) # Call the "real" save() method.
Example #8
0
    def generate_slug(self, model_instance):
        """Returns a unique slug."""
        queryset = model_instance.__class__._default_manager.all()

        # Only count slugs that match current length to prevent issues
        # when pre-existing slugs are a different length.
        lookup = {'%s__regex' % self.attname: r'^.{%s}$' % self.length}
        if queryset.filter(**lookup).count() >= len(self.chars)**self.length:
            raise FieldError("No available slugs remaining.")

        slug = get_random_string(self.length, self.chars)

        # Exclude the current model instance from the queryset used in
        # finding next valid slug.
        if model_instance.pk:
            queryset = queryset.exclude(pk=model_instance.pk)

        # Form a kwarg dict used to impliment any unique_together
        # contraints.
        kwargs = {}
        for params in model_instance._meta.unique_together:
            if self.attname in params:
                for param in params:
                    kwargs[param] = getattr(model_instance, param, None)
        kwargs[self.attname] = slug

        while queryset.filter(**kwargs):
            slug = get_random_string(self.length, self.chars)
            kwargs[self.attname] = slug

        return slug
def test_post_issue_multi_jurisdiction(mf_api_client, random_service):
    assert not Jurisdiction.objects.exists()  # Precondition check
    Jurisdiction.objects.create(identifier="j1", name="j1")
    Jurisdiction.objects.create(identifier="j2", name="j2")
    # Can't post without a Jurisdiction when there are multiple
    get_data_from_response(
        mf_api_client.post(ISSUE_LIST_ENDPOINT, {
            "service_code": random_service.service_code,
            "lat": 30,
            "long": 30,
            "description": get_random_string(),
        }),
        400
    )
    for j in Jurisdiction.objects.all():
        # Can't post without a Jurisdiction when there are multiple
        issues = get_data_from_response(
            mf_api_client.post(ISSUE_LIST_ENDPOINT, {
                "jurisdiction_id": j.identifier,
                "service_code": random_service.service_code,
                "lat": 30,
                "long": 30,
                "description": get_random_string(),
            }),
            201,
            schema=LIST_OF_ISSUES_SCHEMA
        )

        assert Issue.objects.get(identifier=issues[0]["service_request_id"]).jurisdiction == j
def random_prisoner_number():
    # format: 98% A\d{4}[A-Z]{2} and 2% [B-Z]\d{4}[A-Z]{2}
    return (
        (get_random_string(allowed_chars='BCDEFGHIJKLMNOPQRSTUVWXYZ', length=1) if random.random() > 0.98 else 'A') +
        get_random_string(allowed_chars='0123456789', length=4) +
        get_random_string(allowed_chars='ABCDEFGHIJKLMNOPQRSTUVWXYZ', length=2)
    )
Example #11
0
def psuedo_id(record_id, donor=False):
    """
    For nhic_tra_Pseudo_ID - Pseudo ID of the Patient (Recipient). This is a code which is
    anonymous to those looking at the dataset, but which can be used to look up the real identity
    of the patient. Length 5-32.

    :return: String, fixed for this record of length 10. Starts "OUH-", then 6 numbers
    """
    from django.utils.crypto import get_random_string
    record = NHSBTRecord.objects.get(pk=record_id)
    if donor:
        while record._psuedo_id_d is "":
            new_string = get_random_string(6, allowed_chars='1234567890')
            test_string = "OUH-{0}".format(new_string)
            if not NHSBTRecord.objects.filter(_psuedo_id_d=test_string).exists():
                record._psuedo_id_d = test_string
                record.save()
        return record._psuedo_id_d
    else:
        while record._psuedo_id_r is "":
            new_string = get_random_string(6, allowed_chars='1234567890')
            test_string = "OUH-{0}".format(new_string)
            if not NHSBTRecord.objects.filter(_psuedo_id_r=test_string).exists():
                record._psuedo_id_r = test_string
                record.save()
        return record._psuedo_id_r
Example #12
0
def SignUp(req):
    if req.method == "GET":
        return render(req,'account/sign-up.html')
    elif req.method == "POST":
        message = ""
        form = sign.GetFormDate(req,['username','email','password','passwordAgain'])
        if form['password'] != form['passwordAgain']:
            message = 'Please enter the same Password!'
            return render(req,'account/sign-up.html',{"form":form,'message':message})
        if req.POST.get('username') and req.POST.get('email') and req.POST.get('password') and req.POST.get('passwordAgain'):
            newUser = User()
            newUser.username            = form['username']
            newUser.email               = form['email']
            newUser.password_salt       = get_random_string(16)
            newUser.password_encryption = make_password(form['password'],salt=newUser.password_salt)
            newUser.save()
            emailVerify         = EmailVerification()
            emailVerify.uid     = newUser
            emailVerify.email_verification_code = get_random_string(32)
            emailVerify.save()
            
            sign.SentSignUpMail(emailVerify,newUser)
            return HttpResponseRedirect('/account/sign-in')
        else:
            return render(req,'account/sign-up.html',{"form":form})
def get_pronounceable_pass(num_syllables, num_digits, include_upper=True):
    """Generates a pseudo random password which is easier to remember.
    
    Generates a pseudo random password which is easier to remember due to 
    being easier to pronounce. The password can contain a number of random 
    'syllables' (consonant+vowel sequences), followed by randomly generated 
    digits. By default the generated password includes capital letters. The 
    generated password does not contain letters and digits that look similar 
    (e.g. 'I','1' and 'l' or 'O' and '0'), in order to avoid confusion 
    (as in django.contrib.auth.models.make_random_password()). 
    
    num_sylables -- the number of syllables to form the password prefix
    num_digits -- the number of digits to form the password suffix
    include_upper -- when True, the password may include capital letters
    """
    digits = "23456789"

    # to avoid confusion, the generated password may not include letters and
    # digits that look similar (e.g. 'I','1' and 'l' or 'O' and '0')
    if include_upper:
        consonants = "bcdfghjkmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ"
        vowels = "aeiouAEU"
    else:
        consonants = "bcdfghjkmnpqrstvwxyz"
        vowels = "aeiou"

    syllables = map("".join, itertools.product(consonants, vowels))

    return get_random_string(num_syllables, syllables) + get_random_string(num_digits, digits)
Example #14
0
def weixin_user_url_preHandle(code='',openType=0):
    if code == '':
        return True,'http://x5.wuyoubar.cn/X5/'
    
    errorcode2,response2 = get_user_refresh_token(code)
    
    
    #debug( errorcode2,response2)
    
    
    if errorcode2 != '0':
            return False,response2    
    
    p_openid = response2.get('openid','')
    p_access_token = response2.get('access_token','')
    p_refresh_token = response2.get('refresh_token','')
    #debug('lOpenid',lOpenid)
    #OpenID在数据库中存在,已经绑定用户,直接跳转页面
    #携带openType和tempUserToken
    try:
        lUser = User.objects.get(openid=p_openid)
        #debug('lUser',lUser)
        
        userTempId = datetime.now().strftime('%Y%m%d%H%M%S') +\
            get_random_string(6,'0123456789abcdefghijklmnopqrstuvwxyz')
        userTempToken = datetime.now().strftime('%Y%m%d%H%M%S') +\
            get_random_string(24,'0123456789abcdefghijklmnopqrstuvwxyz')
            
        #创建tempUserToken,需要保存到数据库中
        result = lUser.generateUserTempToken(userTempId,userTempToken)        
        if not lUser.save():
            debug('weixin_user_url_preHandle','generate temp userid and token fail!!!!!')
            return False,'微信用户临时授权失败'
        
        debug('weixin_user_url_preHandle',lUser)
        #debug(result,userTempId,userTempToken)
        if result:
            return True,UserPageHome+'?openType='+str(openType)+'&userTempId='+userTempId +\
                '&userTempToken='+userTempToken
        else:
            return False,'网络异常,请稍后重试'
        
    #OpenID在数据库中不存在,跳转到绑定用户页面,code下发给终端
    except User.DoesNotExist:
        #把openid,access_token和refresh_token加密发送给用户
        #msg消息体加密之前是access_token(xxxx)&openid(xxx)&refresh_token(xxx)
        tempWXUser = TempWXUser(
            openid = p_openid,
            access_token = p_access_token,
            refresh_token = p_refresh_token,
        )
        tempWXUser.save()
        
        #msg = encrypter(msg)
        debug('weixin_user_url_preHandle','msg',p_openid)
        return True,UserPageHome+'?openType='+str(GlobalVar.OpenType.wxBound) +\
            '&code='+p_openid+'&nextopenType='+str(openType)
    except Exception,ex:
        debug('func_weixin.py->weixin_user_url_preHandle->error',p_openid)
        return False,'网络异常,请稍后重试'
Example #15
0
def fill_db():
    # Create Categories
    category_names = ['Politician', 'Banker', ]
    category_desciptions = ['Bla bla bla bla', 'Bla bla bla bla', ]
    for i in range(0, len(category_names)):
        if not Category.objects.filter(en_name=category_names[i]).exists():
            Category(en_name=category_names[i], sl_name=category_names[i], description=category_desciptions[i]).save()

    # Create Persons
    description = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum'

    for j in range(0, 20):
        # city = City.objects.filter(country__name='United Kingdom').get(name='London')
        city = City(
            city='city',
            street='Dawning street 3'
        )
        city.save()
        Person(
            city=city,
            first_name=crypto.get_random_string(5),
            last_name=crypto.get_random_string(5),
            birth_date=datetime(timezone.now().year + 100, timezone.now().month, 1),
            category=Category.objects.get(en_name=category_names[randint(0, len(category_names) - 1)]),
            description=description
        ).save()
Example #16
0
    def create_access_user(self, grant):
        user = grant.reservation.user
        # Make sure there is something in first_name and last_name
        first_name = user.first_name or 'Kulkunen'
        last_name = user.last_name or 'Kulkunen'

        # We lock the access control instance through the database to protect
        # against race conditions.
        with self.system_lock():
            # The PIN also serves as the cardholder identifier (they must
            # be identical). Try at most 20 times to generate an unused PIN,
            # and if that fails, we probably have other problems. Upper layers
            # will take care of retrying later in case the unlikely false positive
            # happens.
            for i in range(20):
                pin = get_random_string(1, '123456789') + get_random_string(3, '0123456789')
                if not self.system.users.active().filter(identifier=pin).exists():
                    break
            else:
                raise RemoteError("Unable to find a PIN code for grant")

            user_attrs = dict(identifier=pin, first_name=first_name, last_name=last_name, user=user)
            user = self.system.users.create(**user_attrs)

        return user
Example #17
0
 def save(self, *args, **kwargs):
     if self.pk:
         return
     with transaction.atomic():
         self.key = get_random_string(254)
         while Key.objects.filter(key=self.key).exists():
             self.key = get_random_string(254)
         super(Key, self).save(*args, **kwargs)
Example #18
0
def upload_to(instance, filename):
    spread_path = md5(get_random_string(64).encode()).hexdigest()
    secret = get_random_string(32)
    filename_clean = "%s.png" % get_random_string(32)

    return os.path.join(
        "avatars", spread_path[:2], spread_path[2:4], secret, filename_clean
    )
Example #19
0
 def provision_mongo(self):
     """
     Set mongo credentials and provision the database.
     """
     if not self.mongo_provisioned:
         self.mongo_user = get_random_string(length=16, allowed_chars=string.ascii_lowercase)
         self.mongo_pass = get_random_string(length=32)
     return super().provision_mongo()
 def test_save_form_with_2_tags_required_16_queries(self):
     RANDOM_TAG_1 = get_random_string()
     RANDOM_TAG_2 = get_random_string()
     TAGS = RANDOM_TAG_1 + ', ' + RANDOM_TAG_2
     f = PhotoTaggedForm({'tags': TAGS})
     with self.assertNumQueries(16 + 2):
         p = f.save()
     self.assertEqual(p.tags, TAGS)
Example #21
0
 def create(cls):
     voucher_id = crypto.get_random_string(length=12)
     while Voucher.objects.filter(code=voucher_id):
         voucher_id = crypto.get_random_string(length=12)
     book = cls(code=voucher_id)
     book.save()
     # do something with the book
     return book
Example #22
0
 def save(self, *args, **kwargs):
     with atomic():
         if self.form.allow_display and not self.display_key:
             dk = get_random_string(24)
             while FormModelData.objects.filter(display_key=dk).exists():
                 dk = get_random_string(24)
             self.display_key = dk
         super(FormModelData, self).save(*args, **kwargs)
Example #23
0
    def __init__(self):
        self.git_version = GitVersion.objects.create( ref = "master" , repo = "uri://git.no" , description = "description")
        self.key = ApiKey.objects.create( description = "Newkey")
        self.external_key = str(self.key.external_key)
        self.loc = Location.objects.create( name = "Ulriken" , latitude = 200 , longitude = 120 , altitude = 600)
        self.dev_type = DeviceType.objects.create( name = "HP-X123" )
        self.dev = Device.objects.create( id = "DevXYZ" , 
                                          location = self.loc , 
                                          device_type = self.dev_type , 
                                          description = "Besrkivels",
                                          post_key = self.key)

        self.dev_loc0 = Device.objects.create( id = "DevNoLoc" , device_type = self.dev_type , description = "Besrkivels",
                                               post_key = self.key )

        self.mtype = MeasurementType.objects.create( name = "Temperature" )
        self.raw_data = DataType.objects.get( pk = "RAWDATA" )
        self.test_data = DataType.objects.get( pk = "TEST" )

        self.sensor_type_temp = SensorType.objects.create( product_name = "XX12762 Turbo",
                                                           measurement_type = self.mtype,
                                                           short_description = "Temp",
                                                           description = "Measurement of temperature",
                                                           unit = "Degree celcius",
                                                           min_value = 0,
                                                           max_value = 100)
        
        self.temp_sensor = Sensor.objects.create( id = "TEMP:XX",
                                                  parent_device = self.dev,
                                                  description = "tempm",
                                                  sensor_type = self.sensor_type_temp)
        
        self.hum_sensor = Sensor.objects.create( id = "HUM:XX",
                                                 description = "Measurement humidity",
                                                 data_type = self.raw_data ,
                                                 parent_device = self.dev,
                                                 sensor_type = self.sensor_type_temp)

        self.loc0_sensor = Sensor.objects.create( id = "NO_LOC:XX",
                                                 description = "Measurement humidity",
                                                 data_type = self.raw_data ,
                                                 parent_device = self.dev_loc0,
                                                 sensor_type = self.sensor_type_temp)


        self.ts = TimeStamp.objects.create( timestamp = TimeStamp.parse_datetime("2015-10-10T10:10:00+01") )
        self.test_user_passwd = get_random_string( length = 10 ),
        self.test_user = User.objects.create_user( get_random_string( length = 10 ),
                                                   password = self.test_user_passwd , 
                                                   email = "*****@*****.**" )

        try:
            response = requests.get("https://github.com/")
            self.network = True
        except Exception:
            self.network = False
            settings.RESTDB_IO_URL = None
            sys.stderr.write("** WARNING: No network connection - skipping post to restdb.io\n")
 def create_hero_with_payment_amount(amount):
     hero = DjangoHero.objects.create(
         email='*****@*****.**' % get_random_string(),
         approved=True,
         is_visible=True,
     )
     donation = hero.donation_set.create(interval='onetime')
     donation.payment_set.create(amount=amount, stripe_charge_id=get_random_string())
     return hero
Example #25
0
def _generate_item_dict():
    item_id = ItemID(get_random_string(), get_random_string())
    item_dict = {
        'id': item_id,
        'subject': get_random_string(),
        'start': now(),
        'end': now() + timedelta(hours=1)
    }
    return item_dict
Example #26
0
def index(request):
    date = strftime("%Y-%m-%d", gmtime())
    time = strftime("%H:%M:%S", gmtime())
    print get_random_string(length=14)
    context = {
        "date": date,
        "time": time
    }
    return render(request, "blogs/index.html", context)
Example #27
0
	def save( self, *args, **kwargs ):
		self.modified = now()
		if not self.rnd_str:
			self.rnd_str = get_random_string(length=30)
			rnd_id_collisions = Participant.objects.filter(rnd_str=self.rnd_str)
			while rnd_id_collisions:
				self.rnd_str = get_random_string(length=30)
				rnd_id_collisions = Participant.objects.filter(rnd_str=self.rnd_str)		 
		return super( Participant, self ).save( *args, **kwargs )
Example #28
0
def _make_reference():
    from django.utils.crypto import get_random_string

    return u"%s-%s-%s" % (
        # exclude B8G6I1l0OQDS5Z2
        get_random_string(length=2, allowed_chars="ACEFHJKMNPRTUVWXY3479"),
        get_random_string(length=4, allowed_chars="123456789"),
        get_random_string(length=4, allowed_chars="123456789"),
    )
Example #29
0
def generate_access_code(access_code_type):
    if access_code_type == Resource.ACCESS_CODE_TYPE_NONE:
        return ''
    elif access_code_type == Resource.ACCESS_CODE_TYPE_PIN4:
        return get_random_string(4, '0123456789')
    elif access_code_type == Resource.ACCESS_CODE_TYPE_PIN6:
        return get_random_string(6, '0123456789')
    else:
        raise NotImplementedError('Don\'t know how to generate an access code of type "%s"' % access_code_type)
Example #30
0
def email(save=False, **kwargs):
    if "user" not in kwargs:
        kwargs["user"] = user(save=True)
    if "email" not in kwargs:
        kwargs["email"] = "%s@%s.com" % (get_random_string(), get_random_string())
    email = EmailAddress(**kwargs)
    if save:
        email.save()
    return email
Example #31
0
 def gen():
     return '{letters}{numbers}'.format(
         letters=get_random_string(length=2,
                                   allowed_chars='ACEFHJKMNPRTUVWXY'),
         numbers=get_random_string(length=1, allowed_chars='123456789'),
     )
Example #32
0
def generate_channel_name():
    return get_random_string()
Example #33
0
def get_gallery_save_path(instance, filename):
    return "gallery/{0}/{1}/{2}.{3}".format(instance.model_name,
                                            instance.model_ref,
                                            get_random_string(24),
                                            filename.split(".")[-1].lower())
Example #34
0
 def createUser(self):
     return self.create(name=get_random_string(length=8)).id
Example #35
0
def generate_api_token():
    return get_random_string(length=64,
                             allowed_chars=string.ascii_lowercase +
                             string.digits)
Example #36
0
# coding: utf8

import os

from django.utils import crypto

from furl import furl

from .settings import *
from utils import get_sentry_organization_slug, get_sentry_project_slug

DEBUG = False

ALLOWED_HOSTS = (os.environ.get('HOST_NAME'), '*')
SECRET_KEY = os.environ.get('SECRET_KEY') or crypto.get_random_string(50)

STATICFILES_STORAGE = 'omaha_server.s3utils.StaticS3Storage'
DEFAULT_FILE_STORAGE = 'omaha_server.s3utils.S3Storage'
CRASH_FILE_STORAGE = 'omaha_server.s3utils.AuthS3Storage'

AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID')
AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY')
AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME')
S3_URL = 'https://%s.s3.amazonaws.com/' % AWS_STORAGE_BUCKET_NAME

STATIC_URL = ''.join([S3_URL, 'static/'])
AWS_PRELOAD_METADATA = True
AWS_QUERYSTRING_AUTH = False
AWS_IS_GZIPPED = True

RAVEN_CONFIG = {
Example #37
0
 def salt(self):
     return get_random_string(2)
Example #38
0
 def salt(self):
     """
     Generates a cryptographically secure nonce salt in ascii
     """
     return get_random_string()
Example #39
0
DOWNLOAD_TIMEOUT_MIN_LIMIT = 10

# Default timeout for SQL statements in Django
DEFAULT_DB_TIMEOUT_IN_SECONDS = int(
    os.environ.get("DEFAULT_DB_TIMEOUT_IN_SECONDS", 0))
CONNECTION_MAX_SECONDS = 10

API_MAX_DATE = "2024-09-30"  # End of FY2024
API_MIN_DATE = "2000-10-01"  # Beginning of FY2001
API_SEARCH_MIN_DATE = "2007-10-01"  # Beginning of FY2008

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = get_random_string()

# SECURITY WARNING: don't run with debug turned on in production!
# Defaults to False, unless DJANGO_DEBUG env var is set to a truthy value
DEBUG = os.environ.get("DJANGO_DEBUG", "").lower() in ["true", "1", "yes"]

HOST = "localhost:3000"
ALLOWED_HOSTS = ["*"]

# Define local flag to affect location of downloads
IS_LOCAL = True

# How to handle downloads locally
# True: process it right away by the API;
# False: leave the message in the local file-backed queue to be picked up and processed by the bulk-download container
RUN_LOCAL_DOWNLOAD_IN_PROCESS = os.environ.get(
Example #40
0
File: user.py Project: zmyer/sentry
 def refresh_session_nonce(self, request=None):
     from django.utils.crypto import get_random_string
     self.session_nonce = get_random_string(12)
     if request is not None:
         request.session['_nonce'] = self.session_nonce
Example #41
0
 def generate_code(self):
     self.authorization_code = get_random_string(length=self.CODE_LENGTH)
Example #42
0
def generate_password() -> str:
    return get_random_string()
Example #43
0
 def generate_refresh_token(self):
     self.refresh_token = get_random_string(length=self.AT_LENGTH)
Example #44
0
def generate(request):
    request.session['count'] += 1
    request.session['random_str'] = get_random_string(length=14)
    return redirect('/')
Example #45
0
def arena(request):
    # Check if the current user's username matches the 'user' field assigned to the robot objects
    # If there is a match, the user is considered to be authorized and may access the arena to control
    # robot. A unique key will be passed to the mqtt broker upon entry and will be changed after logout.
    # If the user is not authorized, they will be redirected back to the home.html page with an error message

    # current_user = request.user
    unique_key = get_random_string(length=7)
    # Get current username
    user = User.objects.get(username=request.user.username)
    userrobot = []
    user_has_robot = False

    # Create list of robots
    robot_list = robot.objects.filter()
    for i in robot_list:
        #If user linked to robot is same as user attempting access
        if i.user == user:
            print("\nRobot found for:", user, "; robot = ", i.robotname, "\n")
            # Append userrobot to correct robot
            user_has_robot = True
            userrobot.append(
                i)  #set robot object matched to user as 'userrobot'

            # Get data relating to robot
            robotobject = robot.objects.get(robotname=userrobot[0].robotname)
            mqttuser = robotobject.mqttuser
            robotname = robotobject.robotname

            # Get data relating to broker
            brokerobject = mqttbroker.objects.get(
                mqttbroker=robotobject.broker
            )  #Get mqtt broker details for mqttbroker object on port 32285
            host = brokerobject.mqtthost
            port = brokerobject.mqttport  #Set 'port' equal to the mqttport value of the object
            apikey = brokerobject.apikey

            ###################
            # Update password of mqtt user in Django database with unique key
            # Then update password in cloudmqtt
            mqttpass = unique_key  #set mqttpass equal to unique key
            robotobject.mqttpass = mqttpass
            robotobject.save()  #save update to db

            url = "https://api.cloudmqtt.com/api/user/" + str(
                mqttuser)  #cloudmqtt api update password, pass username in url
            headers = {
                'Content-Type': 'application/json',
            }
            data = '{"password":'******'"' + mqttpass + '"' + '}'
            r = requests.put(url,
                             headers=headers,
                             data=data,
                             auth=('', apikey))
            print(r.content)
            ###################
            ##################

            context = {
                'mqttport': port,
                'mqtthost': host,
                'mqttuser': mqttuser,
                'mqttpass': mqttpass,
                'user_has_robot': user_has_robot,
                'UUID': unique_key,
            }  #Dictionary to map "mqttport" to the corresponding variable

            # Debug
            print(data)
            print(robotname)
            print(mqttuser)
            print(mqttpass)
            print(host)
            print(port, "\n")
            return render(request, 'arena.html', context)
        else:
            print("No Robot Found for user")

    error = "You are not authorized to access the arena at this time."
    context = {
        'error': error,
    }  #Dictionary to map "mqttport" to the corresponding variable

    return render(request, 'home.html', context)
Example #46
0
 def random_string(self, length=12, chars=BaseStrategy.ALLOWED_CHARS):
     return get_random_string(length, chars)
Example #47
0
 def generate_access_token(self):
     self.access_token = get_random_string(length=self.AT_LENGTH)
Example #48
0
def TraderID():
    digits = get_random_string(length=8, allowed_chars='0123456789')
    chars = get_random_string(length=4,
                              allowed_chars='ABCDEFGHIJKLMNOPQRSTUVWXYZ')
    return "{}-{}".format(digits, chars)
Example #49
0
def generate_invite_code(length=32):
    return get_random_string(length=length, allowed_chars=Submission._code_charset)
Example #50
0
 def ask_credentials_response(self, request, token, message=None):
     captcha_key = get_random_string(32)
     captcha = self.generate_captcha(captcha_key)
     return register_ask2(request, self.application, self.token_name, token,
                          self.backend.get_phone_column() != "",
                          captcha_key, captcha, message)
Example #51
0
def update_nodes():
    update_id = get_random_string(length=10)
    logger.info("Update ID: " + update_id + " - Beginning update at " +
                str(datetime.datetime.now()))

    # Retrieve the database lock
    lock = UpdateLock.objects.all().first()
    lock_version = lock.version

    # Check that the lock is currently not in use
    if lock.in_use:
        logger.info("Update ID: " + update_id +
                    " - Database in use, exiting at " +
                    str(datetime.datetime.now()))
        return

    # Update the lock
    locked = UpdateLock.objects.filter(version=lock_version).update(
        in_use=True, version=lock_version + 1)

    # exit if 0 objects were updated as that means someone was locking at the same time
    if locked == 0:
        logger.info(
            "Update ID: " + update_id +
            " - Database lock version was updated by another process, exiting at "
            + str(datetime.datetime.now()))
        return

    # update in-db chain for each node
    nodes = Node.objects.all()
    db_update = True
    for node in nodes:
        # try except statements for catching any errors that come from the requests. if there is an error, just skip
        # the node and continue
        try:
            url = node.url

            # get best block hash
            r = requests.post(
                url,
                data='{"method": "getbestblockhash", "params": [] }',
                auth=(os.environ['RPC_USER'], os.environ['RPC_PASSWORD']))
            if r.status_code != 200:
                continue
            rj = r.json()
            best_block = rj['result']

            # Get the block header for best block hash
            r = requests.post(
                url,
                data='{"method": "getblockheader", "params": ["' + best_block +
                '"] }',
                auth=(os.environ['RPC_USER'], os.environ['RPC_PASSWORD']))
            if r.status_code != 200:
                continue
            rj = r.json()
            header = rj['result']
            prev = header['previousblockhash']
            height = header['height']
            hash = header['hash']

            # Update node's MTP
            node.mtp = datetime.datetime.fromtimestamp(header['mediantime'],
                                                       timezone.utc)
            node.best_block_time = datetime.datetime.fromtimestamp(
                header['time'], timezone.utc)

            # Update node's chainwork and difficulty
            node.difficulty = header['difficulty']
            node.chainwork = header['chainwork']

            # check that this node's current top block is this block or the previous block
            blocks = Block.objects.all().filter(
                node=node, active=True).order_by("-height")

            # Check if last update's best block changed
            if node.last_updated_best != hash:
                db_update = False

            # Update the last_updated_best
            node.last_updated_best = hash

            # If there is no blockchain, add the first block
            if not blocks:
                Block(hash=hash, height=height, node=node).save()
                node.best_block_hash = hash
                node.best_block_height = height
                node.prev_block_hash = prev

            # same block
            elif blocks[0].hash == hash:
                node.best_block_hash = hash
                node.best_block_height = height
                node.prev_block_hash = prev
            # different block
            # next block: prev hash matches
            elif prev == blocks[0].hash:
                # Add block to db
                Block(hash=hash, height=height, prev=blocks[0],
                      node=node).save()
                node.best_block_hash = hash
                node.best_block_height = height
                node.prev_block_hash = prev
            # otherwise need to reorg
            else:
                # node's height is ahead
                blocks_to_add = [hash]
                i = 0
                # walk backwards until node height matches db height
                while height > blocks[i].height:
                    r = requests.post(
                        url,
                        data='{"method": "getblockheader", "params": ["' +
                        prev + '"] }',
                        auth=(os.environ['RPC_USER'],
                              os.environ['RPC_PASSWORD']))
                    if r.status_code != 200:
                        continue
                    rj = r.json()
                    header = rj['result']
                    prev = header['previousblockhash']
                    hash = header['hash']
                    height = header['height']
                    if height > blocks[i].height:
                        blocks_to_add.append(hash)
                # walk down db chain until node height matches
                deactivated = 0
                while blocks[i].height > height:
                    # deactivate the block here
                    block = blocks[i]
                    block.active = False
                    block.save()
                    deactivated += 1

                    # increment
                    i += 1
                # now DB and node are at same height, walk backwards through both to find common ancestor
                while blocks[i].hash != hash:
                    # deactivate the block here
                    block = blocks[i]
                    block.active = False
                    block.save()
                    deactivated += 1

                    # increment
                    i += 1

                    # Add this hash to add
                    blocks_to_add.append(hash)

                    # get block from node
                    r = requests.post(
                        url,
                        data='{"method": "getblockheader", "params": ["' +
                        prev + '"] }',
                        auth=(os.environ['RPC_USER'],
                              os.environ['RPC_PASSWORD']))
                    if r.status_code != 200:
                        continue
                    rj = r.json()
                    header = rj['result']
                    prev = header['previousblockhash']
                    hash = header['hash']

                # at common ancestor
                # now add new blocks
                prev_block = blocks[i]
                for hash in blocks_to_add[::-1]:
                    block = Block(hash=hash,
                                  height=prev_block.height + 1,
                                  node=node,
                                  active=True,
                                  prev=prev_block)
                    block.save()
                    node.best_block_hash = block.hash
                    node.best_block_height = block.height
                    node.prev_block_hash = prev_block.hash
                    prev_block = block

                # update node's tip and if it has reorged
                node.has_reorged = node.has_reorged or deactivated > 2  # only reorged if reorg was greater than 2 blocks

            # Gather stats from stats node
            if node.stats_node:
                r = requests.post(
                    url,
                    data='{"method": "getblockchaininfo", "params": [] }',
                    auth=(os.environ['RPC_USER'], os.environ['RPC_PASSWORD']))
                if r.status_code != 200:
                    continue
                rj = r.json()
                forks = rj['result']['bip9_softforks']
                current = rj['result']['blocks']
                for name, info in forks.items():
                    # Get status
                    state = info['status']

                    # Get the fork from the database
                    db_forks = BIP9Fork.objects.all().filter(name=name)

                    # skip if state is active or defined and was not already in the db
                    if (state == "active"
                            or state == 'defined') and not db_forks:
                        continue

                    # Only get stats if started
                    if state == 'started':
                        # Get statistics
                        period = info['statistics']['period']
                        threshold = info['statistics']['threshold']
                        elapsed = info['statistics']['elapsed']
                        count = info['statistics']['count']

                        # If the fork does not exist, make it
                        if not db_forks:
                            BIP9Fork(name=name,
                                     state=state,
                                     period=period,
                                     threshold=threshold,
                                     elapsed=elapsed,
                                     count=count).save()
                        # otherwise update it
                        else:
                            fork = db_forks[0]
                            fork.elapsed = elapsed
                            fork.count = count
                            fork.state = state
                            fork.current = current
                            fork.since = info['since']
                            fork.save()
                    else:
                        fork = db_forks[0]
                        fork.state = state
                        fork.since = info['since']
                        fork.current = current
                        fork.save()

            # mark as up and save
            node.is_up = True
            node.save()
        except Exception as e:
            print(e)
            # mark that node is currently down
            node.is_up = False
            node.save()
            continue

    # now that nodes are updated, check for chain splits only if all nodes did not change from the last update.
    if db_update:
        nodes = Node.objects.all()
        has_split = False
        no_split = True
        for node in nodes:
            blockchain = Block.objects.all().filter(
                node=node, active=True).order_by("-height")

            # skip if there is no blockchain for some reason or the node is down
            if not blockchain or not node.is_up:
                continue

            for cmp_node in nodes:
                # don't compare to self
                if node == cmp_node:
                    continue

                # check top block is same
                if node.best_block_hash == cmp_node.best_block_hash:
                    node.is_behind = False
                    continue

                # top block hashes are not the same. find if the divergence is within the past 6 blocks
                # once the block is found, it will be saved until a new divergence is found
                cmp_it = 0
                it = 0
                diverged = 0
                cmp_blockchain = Block.objects.all().filter(
                    node=cmp_node, active=True).order_by("-height")

                # skip if there is no blockchain for some reason or if the node is down
                if not cmp_blockchain or not cmp_node.is_up:
                    continue

                # If the two nodes have mtp forks, skip their comparison
                if cmp_node.mtp_fork and node.mtp_fork and cmp_node.mtp > cmp_node.mtp_fork.activation_time and node.mtp > node.mtp_fork.activation_time:
                    continue

                no_split = False

                # get these to matching heights
                while cmp_blockchain[cmp_it].height > blockchain[
                        it].height and diverged <= 100:
                    cmp_it += 1
                    diverged += 1
                while blockchain[it].height > cmp_blockchain[
                        cmp_it].height and diverged <= 100:
                    it += 1
                    diverged += 1

                # walk down both chains until common ancestor found
                while blockchain[it].hash != cmp_blockchain[
                        cmp_it].hash and diverged <= 100:
                    cmp_it += 1
                    it += 1
                    diverged += 1

                # updated diverged block if within the last 6
                if it > 0 and cmp_it > 0 and blockchain[
                        it].hash == cmp_blockchain[cmp_it].hash and blockchain[
                            it - 1].hash != cmp_blockchain[cmp_it - 1].hash:
                    if blockchain[
                            it -
                            1].height > node.highest_divergence and diverged > 1:
                        node.highest_divergence = blockchain[it - 1].height
                        node.highest_diverged_hash = blockchain[it - 1].hash
                        node.common_ancestor_hash = blockchain[it].hash
                        node.common_ancestor_height = blockchain[it].height

                # Normal split detected, mark as such
                if diverged > 1:
                    # Only mark node has having MTP forked if node's mtp is past the mtp fork time
                    if node.mtp_fork and node.mtp > node.mtp_fork.activation_time:
                        node.sched_forked = True
                    # If the cmp_node had an mtp fork, ignore this divergence.
                    elif cmp_node.mtp_fork and cmp_node.mtp > cmp_node.mtp_fork.activation_time:
                        pass
                    # Otherwise this is a chain split
                    else:
                        has_split = True

                    if it < cmp_it:
                        node.is_behind = True
                    else:
                        node.is_behind = False
                node.save()

        # Update fork state if split detected
        states = ForkState.objects.all()
        if not states:
            ForkState().save()
        if has_split:
            state = ForkState.objects.all()[0]
            state.has_forked = True
            state.is_currently_forked = True
            state.save()
        if no_split:
            state = ForkState.objects.all()[0]
            state.is_currently_forked = False
            state.save()

            # reset node stuff
            for node in nodes:
                node.highest_divergence = 0
                node.save()

    # release database lock
    UpdateLock.objects.filter(version=lock_version + 1).update(
        in_use=False, version=lock_version + 2)

    logger.info("Update ID: " + update_id + " - Completed at " +
                str(datetime.datetime.now()))
Example #52
0
 def ask_credentials_response(self, request, token, error_msg=None):
     captcha_key = get_random_string(32)
     captcha = self.generate_captcha(captcha_key)
     return register_ask1(request, self.application, self.token_name,
                          captcha_key, captcha, error_msg)
Example #53
0
 def hash_password(raw_password, salt=None):
     if not salt:
         salt = get_random_string(length=6)
     hash_password = User._hash(raw_password + salt)
     return salt, hash_password
Example #54
0
 def generate_urn(self):
     self.request_uri = "urn:django_oauth:" + get_random_string(
         length=self.URN_LENGTH)
Example #55
0
 def state_token(self):
     """Generate csrf token to include as state parameter."""
     return get_random_string(32)
Example #56
0
# Determine env vars to use:
runtime_env = DeployEnv()
runtime_env.load_deployment_environment()

print('settings.py')

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
#BASE_DIR = os.path.dirname(os.path.dirname(__file__))
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
TEMPLATE_ROOT = os.path.join(PROJECT_ROOT, 'templates_qed/') #.replace('\\','/'))
#STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static_qed')
#os.path.join(PROJECT_ROOT, 'templates_qed')

chars = 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)'
SECRET_KEY = get_random_string(50, chars)
print(f"SECRET_KEY: {SECRET_KEY}")

# try:
#     SECRET_KEY = os.getenv('DOCKER_SECRET_KEY', None)
#     if not SECRET_KEY:
#         with open('secrets/secret_key_django_dropbox.txt') as f:
#             SECRET_KEY = f.read().strip()
# except IOError as e:
#     print("Secret file not set as env variable or file")
#     down_low = 'Shhhhhhhhhhhhhhh'
#     SECRET_KEY = down_low


# cts_api addition:
NODEJS_HOST = 'nginx'  # default nodejs hostname
Example #57
0
def get_support_save_path(instance, filename):
    return "support/{0}/{1}/{2}.{3}".format(instance.support.vendor.id,
                                            instance.support.id,
                                            get_random_string(24),
                                            filename.split(".")[-1].lower())
Example #58
0
 def set_password(self, raw_password):
     salt = get_random_string(length=8)
     password = Developer.sha_text(salt + raw_password)
     self.password = password
     self.save()
     return None
Example #59
0
def get_art_save_path(instance, filename):
    return "art/{0}/{1}.{2}".format(instance.art.id, get_random_string(24),
                                    filename.split(".")[-1].lower())
Example #60
0
def generate_numeric_token():
    """
    Generate a random 6 digit string of numbers.
    We use this formatting to allow leading 0s.
    """
    return get_random_string(length=6, allowed_chars=string.digits)