示例#1
0
def lambda_handler(event, context):
    length = event['pathParameters']['proxy'].split('/')[0]
    count = event['pathParameters']['proxy'].split('/')[1]

    if not count:
        passwd = pwgen(
            int(length),
            symbols=False,
        )
    else:
        passwd = pwgen(
            int(length),
            int(count),
            symbols=False,
        )
    return {
        'statusCode': 200,
        'headers': {
            'Content-Type': 'application/json'
        },
        'body': json.dumps({
            'value': passwd,
            'path': event['pathParameters'],
        })
    }
示例#2
0
    def obj_create(self, bundle, **kwargs):
        # Does someone already exist with this email address? We use AAF for auth...
        if User.objects.filter(
                email__iexact=bundle.data['username']).count() > 0:
            bundle.obj = User.objects.get(
                email__iexact=bundle.data['username'])
        else:
            if bundle.data['is_superuser']:
                u = User.objects.create_superuser(
                    bundle.data['username'],
                    bundle.data['username'],
                    pwgen.pwgen(25),
                    first_name=bundle.data['first_name'],
                    last_name=bundle.data['last_name'],
                )
            else:
                u = User.objects.create_user(
                    bundle.data['username'],
                    bundle.data['username'],
                    pwgen.pwgen(25),
                    first_name=bundle.data['first_name'],
                    last_name=bundle.data['last_name'],
                )
            UserProfile(user=u).save()

            bundle.obj = u

        for group in bundle.data['groups']:
            bundle.obj.groups.add(Group.objects.get(pk=group['id']))
            bundle.obj.save()

        return bundle
    def obj_create(self, bundle, **kwargs):
        # Does someone already exist with this email address? We use AAF for auth...
        if User.objects.filter(email__iexact=bundle.data['username']).count() > 0:
            bundle.obj = User.objects.get(email__iexact=bundle.data['username'])
        else:
            if bundle.data['is_superuser']:
                u = User.objects.create_superuser(
                                    bundle.data['username'],
                                    bundle.data['username'],
                                    pwgen.pwgen(25),
                                    first_name=bundle.data['first_name'],
                                    last_name=bundle.data['last_name'],
                                    )
            else:
                u = User.objects.create_user(
                                    bundle.data['username'],
                                    bundle.data['username'],
                                    pwgen.pwgen(25),
                                    first_name=bundle.data['first_name'],
                                    last_name=bundle.data['last_name'],
                                    )
            UserProfile(user=u).save()

            bundle.obj = u

        for group in bundle.data['groups']:
            bundle.obj.groups.add(Group.objects.get(pk=group['id']))
            bundle.obj.save()

        return bundle
示例#4
0
 def bench_set(self):
     bench_id = pwgen(64)
     start_time = time.time()
     for _ in range(self.query_count):
         key = '{}-{}'.format(bench_id, self.key_length)
         self.conn.set(key, pwgen(self.value_length), ex=self.ttl)
     result = round(time.time() - start_time, 2)
     self.results['SET']['time'] = result
     self.results['SET']['qps'] = round(self.query_count / result)
示例#5
0
文件: app.py 项目: boris/pwgen
def generate_string(length, count):
    if count == 1:
        passwd = pwgen(length, no_numerals=True, symbols=False) + "\n"
        str_single_count.inc()
        return Response(passwd.upper(), mimetype="text/plain")
    else:
        passwd = "\n".join(
            pwgen(length, count, no_numerals=True, symbols=False)) + "\n"
        str_multi_count.inc()
        return Response(passwd.upper(), mimetype="text/plain")
示例#6
0
文件: app.py 项目: boris/pwgen
def generate_random(length, count):
    if count == 1:
        passwd = pwgen(length, symbols=True,
                       allowed_symbols=valid_chars) + "\n"
        single_count.inc()
        return Response(passwd, mimetype="text/plain")
    else:
        passwd = "\n".join(
            pwgen(length, count, symbols=True,
                  allowed_symbols=valid_chars)) + "\n"
        multi_count.inc()
        return Response(passwd, mimetype="text/plain")
示例#7
0
 def bench_get(self):
     bench_id = pwgen(64)
     # bench preparation
     for i in range(self.query_count):
         key = '{}-{}'.format(bench_id, i)
         self.conn.set(key, pwgen(self.value_length), ex=60)
     # real bench
     start_time = time.time()
     for i in range(self.query_count):
         key = '{}-{}'.format(bench_id, i)
         self.conn.get(key)
     result = round(time.time() - start_time, 2)
     self.results['GET']['time'] = result
     self.results['GET']['qps'] = round(self.query_count / result)
示例#8
0
    def test_register(self):
        self.driver.get('https://accounts.google.com')
        username = pwgen(15)
        passwd = pwgen(15)

        create_acc_btn = self.driver.find_element_by_xpath(
            '//span[contains(text(), "Создать аккаунт")]'
        )
        create_acc_btn.click()
        
        firstname_input = self.driver.find_element_by_xpath(
            '//input[@name="firstName"]'
        )
        firstname_input.send_keys('selenium')

        lastname_input = self.driver.find_element_by_xpath(
            '//input[@name="lastName"]'
        )
        lastname_input.send_keys('test')
        
        username_input = self.driver.find_element_by_xpath(
            '//input[@name="Username"]'
        )
        username_input.send_keys(username)

        passwd_input = self.driver.find_element_by_xpath(
            '//input[@name="Passwd"]'
        )
        passwd_input.send_keys(passwd)
        
        confirmpasswd_input = self.driver.find_element_by_xpath(
            '//input[@name="ConfirmPasswd"]'
                            
        )
        confirmpasswd_input.send_keys(passwd)

        next_btn = self.driver.find_element_by_xpath(
            '//span[contains(text(), "Далее")]'
        )
        next_btn.click()

        self.assertTrue(
            EC.element_to_be_clickable(
                (
                    By.XPATH,
                    '//h1[contains(text(), "Подтвердите номер телефона")]'
                    )
            ),
            msg="переход на страницу с подтвержденеим телефона"
        )
示例#9
0
def generate_password(credential_id, user):
    """
    Generate a new password credential and add it to the VCCS authentication backend.

    The salt returned needs to be saved for use in subsequent authentications using
    this password. The password is returned so that it can be conveyed to the user.

    :param credential_id: VCCS credential_id as string
    :param user: user data as dict
    :return: (password, salt) both strings
    """
    user_id = str(user.user_id)
    config = current_app.config
    password = pwgen(int(config.get('PASSWORD_LENGTH')),
                     no_capitalize = True, no_symbols = True)
    factor = vccs_client.VCCSPasswordFactor(password, credential_id)
    current_app.logger.info("Adding VCCS password factor for user {}, "
                             "credential_id {!r}".format(user, credential_id))

    vccs = vccs_client.VCCSClient(base_url = config.get('VCCS_URL'))
    try:
        result = vccs.add_credentials(user_id, [factor])
    except vccs_client.VCCSClientHTTPError as e:
        current_app.logger.error('There was an error adding credentials for user {} '
                                 ': {!r}'.format(user, e))
        raise e
    current_app.logger.debug("VCCS password (id {!r}) creation result: "
                             "{!r}".format(credential_id, result))

    return _human_readable(password), factor.salt
示例#10
0
文件: models.py 项目: v-komarov/iss
class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    phone = models.CharField(max_length=10,
                             db_index=True,
                             default="",
                             verbose_name="Внутренний телефонный номер")
    job = models.CharField(max_length=100,
                           default="",
                           verbose_name="Должность")
    surname = models.CharField(max_length=100,
                               default="",
                               verbose_name="Отчество")
    userkiscode = models.CharField(
        max_length=50,
        default=pwgen(24),
        verbose_name="Идентификатор пользователя в системе КИС")
    work_status = models.BooleanField(
        default=False, verbose_name="Статус смены"
    )  ### Для личной карточки учета рабочего времени
    relax_status = models.BooleanField(
        default=False, verbose_name="Статус перевыва в работе"
    )  ### Для личной карточки учета рабочего времени
    settings = JSONField(default={})
    ip = models.CharField(max_length=15, null=True, default=None)

    @receiver(post_save, sender=User)
    def create_user_profile(sender, instance, created, **kwargs):
        if created:
            Profile.objects.create(user=instance)

    @receiver(post_save, sender=User)
    def save_user_profile(sender, instance, **kwargs):
        instance.profile.save()
示例#11
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--passwd', action='store_true', help="processa todos os pedidos de recuperação de senha")
    parser.add_argument('--create', action='store_true', help="processa todos os pedidos de criação de conta")
    args = parser.parse_args()

    if (args.passwd):
        api = criaconta.CriaConta()
        todo = api.password_requests()
        for request in todo:
            request_id = str(request['id'])
            username = request['username']
            request['passwd'] = pwgen.pwgen()
            password(request, 'cpw')
            mail(request, 'Recuperação de senha', 'passwd.txt')
            status = api.password_reset(request_id)
            if (status == 200):
                print("conta "+username+" criada.")
            elif (status == 404):
                print("conta "+username+" fracassou na API.")
            else:
                print("comando inválido.\n")
    elif (args.create):
        api = criaconta.CriaConta()
        todo = api.list()
        for account in todo:
            print(show(account))
            create(account)
    else:
        interactive_mode()
示例#12
0
def create_backend(account):
    group = account['group']
    username = account['username']
    name = unidecode.unidecode(account['name'])
    account['passwd'] = pwgen.pwgen(12)
    home = "/home/%s/%s"%(group, username)
    mail_body = "create.txt"

    if (check(account, noout=True) == 0):
        local_account = pwd.getpwnam(username)
        local_name = local_account.pw_gecos
        local_group = grp.getgrgid(local_account.pw_gid).gr_name

        if (name == local_name and group == local_group):
            return 0
        else:
            print("grupo: %s:%s"%(group, local_group))
            print("%s\n%s"%(name, local_name))
            return 1

    if (add(account) != 0):
        return 1

    setquota(account)
    if (account['type'] == 'institucional'):
        print("Observações: %s"%(account['obs']))
        password(account, 'add')
    else:
        password(account, 'add')
        pykota(account)
    mail(account, 'Pedido de criação de conta', mail_body)

    return 0
示例#13
0
def changetoken(request, next_page):
    logger.debug("user %s" % request.user)
    profile = request.user.profile
    profile.token = pwgen.pwgen(64)
    profile.save()
    messages.warning(request, 'Your secret token is updated. You will not be able to access your running containers until you restart them.')
    return redirect(next_page)
示例#14
0
 def create(self):
     username = None
     for attr in self.args['public_attributes']:
         if attr['attribute'] == 'sAMAccountName':
             username = attr['set_value'].upper()
             break
     dn = "cn=%s,%s" % (username, self.args['dn'])
     attrs = {}
     for attr in self.args['attributes']:
         if attr['attribute'] == 'sAMAccountName':
             attrs[attr['attribute']] = attr['set_value'].upper()
         else:
             attrs[attr['attribute']] = attr['set_value'].encode("utf-8")
     raw_password = pwgen(12, no_symbols=True)
     password = '******' % raw_password
     password = password.encode('utf-16-le')
     attrs['unicodePwd'] = password
     user = arma_models.User.create(attrs=attrs, dn=dn)
     user.attr_replace('userAccountControl', '512')
     user.attr_replace('pwdLastSet', '0')
     for grp in self.args['groups']:
         group = arma_models.Group.open(grp['group_name'])
         user.add_to_group(group)
     au, u = create_user(username=username)
     template = adum_models.Template.objects.get(pk=self.args['id'])
     uc = adum_models.UserCreation(user=au, password=raw_password, template=template)
     uc.save()
     self.create_home_directory(user)
     return {'user': self.serialize(user)}
示例#15
0
def changetoken(request, next_page):
    logger.debug("user %s" % request.user)
    profile = request.user.profile
    profile.token = pwgen.pwgen(64)
    profile.save()
    messages.warning(request, 'Your secret token is updated. You will not be able to access your running containers until you restart them.')
    return redirect(next_page)
示例#16
0
def add(request):

    if request.method == 'POST':
        docE = Document.objects.get(id=request.POST['key'])
        doc = docE.name
        person = Person()
        person.FIO = request.POST['data']
        person.file = docE
        person.save()
        persons = Person.objects.filter(file=docE)

        try:
            with open("static/files/" + doc + ".csv", 'w',
                      newline='') as csvfile:
                spamwriter = csv.writer(csvfile,
                                        delimiter=',',
                                        quoting=csv.QUOTE_MINIMAL)
                for psn in persons:

                    lines = psn.FIO.split("\n")

                    for line in lines:
                        password = pwgen(10, symbols=False)
                        word = line.split()
                        username = doc + translit(word[0].lower())
                        email = username + '@prk.local'
                        spamwriter.writerow([username] + [password] +
                                            [word[0]] + [word[1]] + [email])
        except:
            pass

    return HttpResponseRedirect("/", locals())
示例#17
0
    def create_user(self, user):
        from pwgen import pwgen
        con = self.connection or self._connect()
        cur = con.cursor()
        cur.execute('CREATE SCHEMA {0};'.format(user))
        # self._initialize(schema=schema_name)
        password = pwgen(8)
        cur.execute("CREATE USER {0} with PASSWORD '{0}';".format(
            user, password))
        cur.execute('GRANT ALL PRIVILEGES ON SCHEMA {0} TO {1};'.format(
            user, user))
        cur.execute('GRANT USAGE ON SCHEMA public TO {0};'.format(user))
        cur.execute(
            'GRANT SELECT ON ALL TABLES IN SCHEMA public TO {0};'.format(user))
        cur.execute('ALTER ROLE {0} SET search_path TO {1};'.format(
            user, user))

        con.commit()
        con.close()

        self.schema = user
        self.user = user
        self.password = password
        con = self.connection or self._connect()
        self._initialize(con)

        con.commit()
        con.close()

        self.stdout.write('CREATED USER {0} WITH PASSWORD {1}\n'.format(
            user, password))

        return self
示例#18
0
    def _update_password(self, key):
        # Update password in Card
        new_password = pwgen()
        self.reader.write(new_password)

        # Update password in CSV
        self.data.loc[self.data.Key == key, 'Password'] = new_password
示例#19
0
 def __init__(self):
     self.liked_posts = set()
     self.likes_made = 0
     self.tokens = {}
     self.username = names.get_first_name(
         gender=random.choice(['male', 'female']))
     self.password = pwgen(12)
示例#20
0
def generate_password(credential_id, user):
    """
    Generate a new password credential and add it to the VCCS authentication backend.

    The salt returned needs to be saved for use in subsequent authentications using
    this password. The password is returned so that it can be conveyed to the user.

    :param credential_id: VCCS credential_id as string
    :param user: user data as dict
    :return: (password, salt) both strings
    """
    user_id = str(user.user_id)
    config = current_app.config
    password = pwgen(int(config.get('PASSWORD_LENGTH')),
                     no_capitalize=True,
                     no_symbols=True)
    factor = vccs_client.VCCSPasswordFactor(password, credential_id)
    current_app.logger.info("Adding VCCS password factor for user {}, "
                            "credential_id {!r}".format(user, credential_id))

    vccs = vccs_client.VCCSClient(base_url=config.get('VCCS_URL'))
    try:
        result = vccs.add_credentials(user_id, [factor])
    except vccs_client.VCCSClientHTTPError as e:
        current_app.logger.error(
            'There was an error adding credentials for user {} '
            ': {!r}'.format(user, e))
        raise e
    current_app.logger.debug("VCCS password (id {!r}) creation result: "
                             "{!r}".format(credential_id, result))

    return _human_readable(password), factor.salt
示例#21
0
    def add(self, type, label, login, pwd, description, folder):
        if type == 'item':
            if description:
                description = u'{}'.format(description.replace('\\r\\n', '<br />'))

            if not pwd:
                pwd = pwgen(16, symbols=False, no_ambiguous=True)

            payload_data = ['' if item is None else item for item in [label, pwd, description, folder, login, '', '', '', '1']]
            payload_data = [base64.b64encode(data.encode('utf-8')) for data in payload_data]
            payload = b';'.join(payload_data)

        elif type == 'folder':
            payload = base64.b64encode((';'.join([label, '0', folder, '0', '0']).encode('utf-8')))

        url = '{0}/add/{2}/{3}?apikey={1}'\
              .format(self.api_endpoint,
                      self.api_key,
                      type,
                      payload.decode('utf-8'))
        req = requests.get(url, verify=False)
        if req.status_code != 200:
            if req.json() and 'err' in req.json():
                raise TeampassApiException(req.json()['err'])
            else:
                raise TeampassHttpException(req.status_code, req.text)
        else:
            if 'new_item_id' in req.json():
                return self.get(type, req.json()['new_item_id'])
            elif 'new_folder_id' in req.json():
                return self.get(type, req.json()['new_folder_id'])
            elif 'err' in req.json():
                raise TeampassApiException(req.json()['err'])
示例#22
0
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        logger.info("New user %s" % instance)
        last_uid = Profile.objects.all().aggregate(models.Max('userid'))['userid__max']
        uid = KOOPLEX.get('min_userid', 1000) if last_uid is None else last_uid + 1
        token = pwgen.pwgen(64)
        Profile.objects.create(user = instance, userid = uid, token = token)
示例#23
0
def upload(request):

    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        file = UploadFile()
        file.upload = request.FILES['upload']
        file.download = file.upload.name + ".csv"
        file.save()
    #
    doc = UploadFile.objects.latest('id').upload
    print(doc)
    # with open("static/files/"+doc, 'w', newline='') as csvfile:
    #     spamwriter = csv.writer(csvfile, delimiter=',', quoting=csv.QUOTE_MINIMAL)

    f = open('static/media/' + doc.name)

    with open("static/media/" + doc.name + ".csv", 'w', newline='') as csvfile:
        spamwriter = csv.writer(csvfile,
                                delimiter=',',
                                quoting=csv.QUOTE_MINIMAL)
        for line in f:
            print(line)
            password = pwgen(10, symbols=False)
            word = line.split()
            username = doc.name + translit(word[0].lower())
            email = username + '@prk.local'
            spamwriter.writerow([username] + [password] + [word[0]] +
                                [word[1]] + [email])

    return HttpResponseRedirect("/", locals())
示例#24
0
def new():
    db = get_shelve()
    invalid = validate_new_form(request)
    email = str(request.form['email'])
    username = str(request.form['username'])
    if(not invalid and db.has_key(email)):
        flash(u'La direcció de correu ja existeix.','error')
        invalid = True
    if not invalid and username in [ x['username'] for x in db.values()]:     
        flash(u'El nom d\'usuari ja existeix.','error')
        invalid = True
    if invalid: 
        return redirect(url_for("new_user"))
    pwd = str(pwgen(10, no_symbols=True))
    #TODO: Provar la connexió amb MLDonkey
    if MLDONKEY_ENABLED:
        with mldonkey.MLDonkey(MLDONKEY_HOST,MLDONKEY_PORT) as ml:
            ml.new_user(request.form['username'],request.form['email'],pwd)
    #Afegir el usuari a la BD (fitxer)
    db[email] = {
        'username' : username,
        'password' : md5(pwd),
    } 
    msg = MIMEText(" Usuari: %s \n Password: %s \n " % (username, pwd))
    msg['Subject'] = 'Dades acces burra'
    sendmail([request.form['email']],msg)
    flash(u'Les dades d\'accès s\'han enviat al vostre correu electrònic.','success')
    return redirect(url_for("new_user"))
示例#25
0
def make_secure_token():
    """
    Generate a session token by which the user session will be identified. This
    is tied to the account and allows getting the account from a session cookie.

    :return: a random token
    """
    return pwgen(TOKEN_LENGTH, no_symbols=True)
示例#26
0
 def generatenewpassword(self):
     password = pwgen.pwgen(12)
     self.changepassword(self, password)
     with open(
             SETTINGS.get('user').get('pattern_passwordfile') % self,
             'w') as f:
         f.write(self.password)
     self.changepassword(password)
示例#27
0
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        logger.info("New user %s" % instance)
        last_uid = Profile.objects.all().aggregate(
            models.Max('userid'))['userid__max']
        uid = KOOPLEX.get('min_userid',
                          1000) if last_uid is None else last_uid + 1
        token = pwgen.pwgen(64)
        Profile.objects.create(user=instance, userid=uid, token=token)
    def create_user(self, username: str) -> str:
        """Create user in rabbitmq.

        Return the password for the user.

        :param username: username to create
        :returns: password for username
        """
        api = self._get_admin_api()
        _password = pwgen.pwgen(12)
        api.create_user(username, _password)
        return _password
示例#29
0
    def deploy(cls, session, domain, owner, environment,
               technical_contact, theme=None, default_language=u'it',
               database_password=None, enabled=True):

        if not database_password:
            database_password = pwgen.pwgen(16, no_symbols=True)

        try:
            cls.log.info("Deploying instance for %s in environment %s",
                         domain, environment)
            instance = cls(domain=domain, owner=owner, environment=environment,
                        theme=theme, technical_contact=technical_contact,
                        default_language=default_language,
                        database_password=database_password,
                        enabled=False)
            session.add(instance)
            session.flush()

            instance._create_structure(session)
            instance._create_python_package_paths(session)
            instance._create_database(session)
            instance._populate_database(session)

            # add group and users
            if instance.owner.organization:
                instance_group_parent = instance.owner.organization

            else:
                instance_group_parent = None

            instance_group = Group(name=instance.domain,
                                   parent=instance_group_parent)
            instance.log.info("Created group %s, parent=%s", instance_group,
                              instance_group_parent)
            instance.groups.append(instance_group)
            admins = User.search(session,
                                 User.groups.any(Group.name == u'admin'))

            if instance.owner not in admins:
                instance.log.info("Adding user %s to group %s",
                                  instance.owner, instance_group)
                instance.owner.groups.append(instance_group)

            instance.flush_cache()
            if enabled:
                instance.enabled = True

        except:
            session.rollback()
            raise

        else:
            return instance
示例#30
0
def geniUser():
    #
    # Get the certificate.  POST request data comes in in unicode and this makes the
    # ssl parser very unhappy, so re-encode in ascii.
    certText1 = request.form['cert']
    certText = certText1.encode('ascii')
    try:
        cert = X509.load_cert_string(certText, X509.FORMAT_PEM)
    except Exception as ex:
        return render_template('error.html', message = 'Failed to parse GENI certficate: %s' % str(ex))
    # old and dead -- X509 verifies and Openssl.crypto doesn't.
    # cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, certText)
    # Verify the cert against the GENI Key
    code = cert.verify(geniKey)
    if(code != 1):
        return render_template('error.html', message='Error: signature verifcation code failure %d' % code)
    # get the subject's email address
    issuer = cert.get_issuer()
    subject = cert.get_subject()
    emailAddress = subject.Email

    # get the Subject Alternate Name field and pull the geni user name from that
    userName  = None
    for i in range(0, cert.get_ext_count()):
        ext = cert.get_ext_at(i)
        if (ext.get_name() == 'subjectAltName'):
            userName = getUserName(ext.get_value())
            break
    # If this failed, for whatever reason, make the name from the email address
    if (not userName):
        userName = makeUserName(emailAddress)
    validTil = str(cert.get_not_after())

    userName = addAtGeni(userName)
    #
    # generate a random password
    #
    password=pwgen.pwgen(8, no_symbols=True)

    resultReport = createUser(userName, password, emailAddress, validTil)
    if (not resultReport["Success"]):
        return render_template('report.html', username=userName, emailAddress=emailAddress, message=resultReport['message'], success=False)
    #
    # Send a success email
    #
    userName = resultReport['userName']
    emailSent = sendMailFromSAVI(emailAddress, userName, password)
    if (emailSent):
        emailSuccessMessage = 'email from [email protected] sent to %s with login information' % emailAddress
    else:
        emailSuccessMessage = 'email send failed for %s.  Please log in immediately using user name %s and password %s and change your password.' % (emailAddress, userName, password)
    # Return a success report.
    return render_template('report.html', username=userName, emailAddress=emailAddress, success=True, emailSuccessMessage=emailSuccessMessage)
示例#31
0
文件: parva.py 项目: mrcrilly/Parva
def generatePassword(policy):
	"""
	General purpose password generator. Uses the policy to generate passwords.
	
	Attributes:
		policy	-- The policy to read from; defines password length, symbol usage and perhaps others in the future
		
	Returns:
		Password based on policy as string
	"""
	
	return pwgen(policy['password_length'], no_symbols=policy['no_symbols'])
示例#32
0
def hotspot_page():
    if LISTEN == '127.0.0.1':
        sh.sudo('nginx', '-s', 'stop')

    ssid = "ScreenlyOSE-{}".format(pwgen(4, symbols=False))
    ssid_password = pwgen(8, symbols=False)

    wifi_connect = sh.sudo('wifi-connect',
                           '-s',
                           ssid,
                           '-p',
                           ssid_password,
                           _bg=True,
                           _err_to_out=True)

    while 'Starting HTTP server' not in wifi_connect.process.stdout:
        sleep(1)

    return template('hotspot.html',
                    network=ssid,
                    ssid_pswd=ssid_password,
                    address='screenly.io/wifi')
def _get_user(email):
    if User.objects.filter(username__iexact=email).count() > 0:
        u = User.objects.get(username__iexact=email)
    else:
        u = User.objects.create_user(
                            email,
                            email,
                            pwgen.pwgen(25),
                            first_name='',
                            last_name='',
                            )
        UserProfile(user=u).save()

    return u
示例#34
0
def _get_user(email):
    if User.objects.filter(username__iexact=email).count() > 0:
        u = User.objects.get(username__iexact=email)
    else:
        u = User.objects.create_user(
            email,
            email,
            pwgen.pwgen(25),
            first_name='',
            last_name='',
        )
        UserProfile(user=u).save()

    return u
    def _operator_password(self) -> Union[str, None]:
        """Return the operator password.

        If the operator password does not exist on the peer relation, create a
        new one and update the peer relation. It is necessary to store this on
        the peer relation so that it is not lost on any one unit's local
        storage. If the leader is deposed, the new leader continues to have
        administrative access to the message queue.

        :returns: String password or None
        :rtype: Unition[str, None]
        """
        if not self.peers.operator_password and self.unit.is_leader():
            self.peers.set_operator_password(pwgen.pwgen(12))
        return self.peers.operator_password
示例#36
0
def changeseaftoken(request, next_page):
    #TODO: what if more fs servers present???
    logger.debug("user %s" % request.user)
    try:
        token = FSToken.objects.get(user = request.user)
        token.token = pwgen.pwgen(64)
        token.save()
        messages.warning(request, 'Your seafile secret token is updated. You may experience problem with running file syncronization tasks.')
    except FSToken.DoesNotExist:
        fsserver = FSServer.objects.all()[0]  #FIXME: ugly
        token = FSToken.objects.create(user = request.user, syncserver = fsserver, token = pwgen.pwgen(64))
        token.save()
        messages.info(request, 'New seafile secret token is created for %s' % fsserver)
    seafilepw_update(request.user.username, token.token)
    return redirect(next_page)
示例#37
0
    def handle(self, *args, **options):
        campaign_id = args[0]
        count = args[1]

        if not campaign_id or not count:
            return 'ERROR'

        codes = pwgen(8, int(count), no_symbols=True, no_capitalize=True, no_ambiguous=True)

        for code in codes:
            code = code.upper()
            try:
                DiscountCode.objects.create(campaign_id=campaign_id, code=code)
            except:
                print 'Error creating discount code - %s' % code
示例#38
0
    def on_event(self, event, extension):
        """ Handles event """
        items = []

        if event.get_argument():
            pw_length = int(event.get_argument())
        else:
            pw_length = int(extension.preferences['pw_length'])

        pw_count = int(extension.preferences['pw_count'])

        if pwgen_module:
            passwords = pwgen.pwgen(
                pw_length,
                pw_count,
                False,
                False,
                True,
                True,
                False,
                True,
                '!$.#*+-_~()][?%&@,;',
                True
            )
        elif not pwgen_module and is_exist(program='pwgen'):
            command = 'pwgen -1 -c -n -y {} {}'.format(
                str(pw_length),
                str(pw_count)
            )
            output = check_output(command.split(' '))
            passwords = output.splitlines()
        else:
            passwords = ['Could not find neither pwgen module nor the command!']

        for password in passwords:
            items.append(
                ExtensionResultItem(
                    icon='images/icon.png',
                    name=str(password),
                    description='Press Enter to copy this password to clipboard',
                    highlightable=False,
                    on_enter=CopyToClipboardAction(str(password))
                )
            )

        return RenderResultListAction(items)
示例#39
0
def register(message_array, device, auto_mode):
    """
        Message: register
    """
    pwd = pwgen(10, no_symbols=True)

    if (device.contributor.status == Contributor.UNKNOWN) or (device.contributor.status == Contributor.INACTIVE):
        device.contributor.status = Contributor.ACTIVE
        device.contributor.password = pwd
        device.contributor.channel = SMS
        device.contributor.save()
        increment_refund(device.contributor)
        msg = _("Thanks for texting! You've joined our team. Your password is {0}. Reply HELP for further informations. ").format(pwd)
        if auto_mode:
            save_message(message_array, device, Message.YES)
        send_message(device.phone_number, msg)
        return Message.YES
示例#40
0
    def handle(self, *args, **options):
        campaign_id = args[0]
        count = args[1]

        if not campaign_id or not count:
            return 'ERROR'

        codes = pwgen(8,
                      int(count),
                      no_symbols=True,
                      no_capitalize=True,
                      no_ambiguous=True)

        for code in codes:
            code = code.upper()
            try:
                DiscountCode.objects.create(campaign_id=campaign_id, code=code)
            except:
                print('Error creating discount code - %s' % code)
示例#41
0
def lost():
    db = get_shelve()
    email = str(request.form['email'])
    if not db.has_key(email):
        flash(u'La direcció de correu no existeix al sistema.','error')
        return redirect(url_for("lost_pass"))
    username = db[email]['username']
    pwd = pwgen(10, no_symbols=True)
    #TODO: Provar la connexió amb MLDonkey
    if MLDONKEY_ENABLED:
        with mldonkey.MLDonkey(MLDONKEY_HOST,MLDONKEY_PORT) as ml:
            ml.change_pass(username,pwd)
    user_data = db[email]
    user_data['password'] = md5(pwd)
    db[email] = user_data
    msg = MIMEText(" Usuari: %s \n Password: %s \n " % (username, pwd))
    msg['Subject'] = 'Dades acces burra'
    sendmail([request.form['email']],msg)
    flash(u'Les dades d\'accès s\'han enviat al vostre correu electrònic.','success')
    return redirect(url_for("lost_pass"))
def auth(request):
    if request.method != 'POST': return HttpResponse('nope')

    try:
        # Verifies signature and expiry time
        verified_jwt = jwt.decode(request.POST['assertion'], secret)
     
        print 'verified_jwt:', verified_jwt

        # In a complete app we'd also store and validate the jti value to ensure there is no replay attack
        if verified_jwt['aud'] == config['test.aaf.edu.au']['aud'] and verified_jwt['iss'] == config['test.aaf.edu.au']['iss']:
            request.session['attributes'] = verified_jwt['https://aaf.edu.au/attributes']
            request.session['jwt'] = verified_jwt
            request.session['jws'] = request.POST['assertion']

            good_email = request.session['attributes']['mail']

            if not User.objects.filter(username=good_email).count():
                u = User.objects.create_superuser(good_email, good_email, pwgen.pwgen(20, 1, no_symbols=True))
            else:
                u = User.objects.get(username=good_email)

            # Temporary workaround: http://stackoverflow.com/a/23771930
            u.backend = 'django.contrib.auth.backends.ModelBackend'

            djauth.login(request, u)

            return redirect('welcome')
        else:
            # Not for this audience
            del request.session['attributes']
            djauth.logout(request)
            raise PermissionDenied
    except jwt.ExpiredSignature:
        # Security cookie has expired
        del request.session['attributes']
        djauth.logout(request)
        raise PermissionDenied
示例#43
0
def start_vpn(vm_uuid, host, extaddr, team_id):
    try:
        logging.info("Starting VPN for team %d", team_id)
        password = pwgen(pw_length=20, no_ambiguous=True)
        message = "Run: ./setup-vpn %s %d %s" % (shlex.quote(extaddr),
                                                 team_id,
                                                 shlex.quote(password))
        # Start the container for the specified team
        command = "./deploy_team %d %s" % (team_id,
                                           shlex.quote(password))
        output = ssh_exec(host, command).split()
        status = output[-1].split(':')[0]
        if status == 'vpn_created':
            return ("start_vpn", (vm_uuid, team_id, message))
        elif status == 'vpn_already_exists':
            logging.warn('VPN for team %d was already started' % team_id)
            return None
        logging.error("Unexpected output from start_vpn(%r, %r, %r, %d): %s",
                      vm_uuid, host, extaddr, team_id, '\n'.join(output))
    except:
        logging.exception("Got exception on start_vpn(%r, %r, %r, %d)",
                          vm_uuid, host, extaddr, team_id)
    return None
示例#44
0
def rcauth(request):
    # Only POST is supported on this URL.
    if request.method != 'POST':
        raise PermissionDenied

    # Rapid Connect authorization is disabled, so don't
    # process anything.
    if not settings.RAPID_CONNECT_ENABLED:
        raise PermissionDenied

    try:
        # Verifies signature and expiry time
        verified_jwt = jwt.decode(
            request.POST['assertion'],
            settings.RAPID_CONNECT_CONFIG['secret'],
            audience=settings.RAPID_CONNECT_CONFIG['aud'])

        # Check for a replay attack using the jti value.
        jti = verified_jwt['jti']
        if JTI.objects.filter(jti=jti).exists():
            logger.debug('Replay attack? ' + str(jti))
            request.session.pop('attributes', None)
            request.session.pop('jwt', None)
            request.session.pop('jws', None)
            django_logout(request)
            return redirect('/')
        else:
            JTI(jti=jti).save()

        if verified_jwt['aud'] == settings.RAPID_CONNECT_CONFIG['aud'] and \
           verified_jwt['iss'] == settings.RAPID_CONNECT_CONFIG['iss']:
            request.session['attributes'] = verified_jwt[
                'https://aaf.edu.au/attributes']
            request.session['jwt'] = verified_jwt
            request.session['jws'] = request.POST['assertion']

            institution_email = request.session['attributes']['mail']

            logger.debug('Successfully authenticated %s via Rapid Connect.' %
                         institution_email)

            # Create a user account and profile automatically. In future,
            # support blacklists and whitelists.
            first_name = request.session['attributes']['givenname']
            c_name = request.session['attributes'].get('cn', '').split(' ')
            if not first_name and len(c_name) > 1:
                first_name = c_name[0]
            user_args = {
                'id': institution_email.lower(),
                'email': institution_email.lower(),
                'password': pwgen.pwgen(),
                'first_name': first_name,
                'last_name': request.session['attributes']['surname'],
            }

            # Check for an email collision.
            edupersontargetedid = request.session['attributes'][
                'edupersontargetedid']
            for matching_user in UserProfile.objects.filter(
                    user__email__iexact=user_args['email']):
                if (matching_user.rapidConnectEduPersonTargetedID is not None
                    and matching_user.rapidConnectEduPersonTargetedID !=
                        edupersontargetedid):
                    del request.session['attributes']
                    del request.session['jwt']
                    del request.session['jws']
                    django_logout(request)
                    raise PermissionDenied

            user = auth_service.get_or_create_user(user_args)
            if user is not None:
                user.backend = 'django.contrib.auth.backends.ModelBackend'
                djauth.login(request, user)
                return redirect('/')
        else:
            del request.session['attributes']
            del request.session['jwt']
            del request.session['jws']
            django_logout(request)
            raise PermissionDenied  # Error: Not for this audience
    except jwt.ExpiredSignature:
        del request.session['attributes']
        del request.session['jwt']
        del request.session['jws']
        django_logout(request)
        raise PermissionDenied  # Error: Security cookie has expired

    raise PermissionDenied
示例#45
0
 def generate(self, length='16', no_symbols='true', no_ambiguous='false'):
     length = int(length)
     no_symbols = no_symbols == 'true'
     no_ambiguous = no_ambiguous == 'true'
     return {'password' : pwgen.pwgen(pw_length=length, no_symbols=no_symbols, no_ambiguous=no_ambiguous)}
示例#46
0
def main():
    parser = argparse.ArgumentParser()

    parser.add_argument('--file', help='data file')
    parser.add_argument('--generate-key-to-stdout', action='store_true')
    parser.add_argument('--key', help='AES key file')
    parser.add_argument('--key-from-gpg', help='key file decrypted by GPG')
    parser.add_argument('--key-from-stdin', action='store_true')
    parser.add_argument('--node')
    parser.add_argument('--get-password', action='store_true')
    parser.add_argument('--set-password', action='store_true',
                        help='Interactively set password')
    parser.add_argument('--generate-and-set-password', metavar='length')
    parser.add_argument('--get-username', action='store_true')
    parser.add_argument('--set-username', metavar='username')
    parser.add_argument('--show-note', action='store_true')
    parser.add_argument('--edit-note', action='store_true')
    parser.add_argument('--dump', action='store_true')
    parser.add_argument('--with-header', action='store_true')
    parser.add_argument('--list-nodes', action='store_true')
    parser.add_argument('--decrypt-all', action='store_true')
    parser.add_argument('--verbose', '-v', action='store_true')

    args = parser.parse_args()

    if args.generate_key_to_stdout:
        sys.stdout.write(generate_key())
        return 0

    key = None

    if args.key_from_stdin:
        key = sys.stdin.read()
    elif args.key_from_gpg:
        key = gpg_decrypt(args.key_from_gpg)
    elif args.key:
        if os.path.exists(args.key):
            key = open(args.key).read()
        else:
            sys.stderr.write('no such key file\n')
            return 1

    if key is None:
        parser.print_help()
        return 1

    if args.file is None:
        sys.stderr.write('no file specified\n')
        return 1

    keychain = Keychain()
    keychain.use_key(key)

    if os.path.exists(args.file):
        keychain.load(args.file)

    if args.decrypt_all:
        decrypted_root = keychain.decrypt_all()
        params = {'sort_keys': True, 'indent': 4, 'separators': (',', ': ')}
        print(json.dumps(decrypted_root, **params))
        return 0

    if args.dump:
        if args.with_header:
            print("%s\t%s\t%s" % ("title", "username", "password"))
        for n in sorted(keychain.root.keys()):
            username = keychain.get(n, Keychain.USERNAME_FIELD)
            password = keychain.get(n, Keychain.PASSWORD_FIELD)
            print("%s\t%s\t%s" % (n, username, password))
        return 0

    if args.list_nodes:
        for node_name in sorted(keychain.root.keys()):
            print(node_name)
        return 0

    if args.node is None:
        sys.stderr.write('no node specified\n')
        return 1

    shown = False

    if args.get_username:
        show(keychain.get(args.node, Keychain.USERNAME_FIELD))
        shown = True

    if args.get_password:
        show(keychain.get(args.node, Keychain.PASSWORD_FIELD))
        shown = True

    if args.show_note:
        show(keychain.get(args.node, Keychain.NOTE_FIELD))
        shown = True

    if shown:
        return 0

    if args.generate_and_set_password:
        password = pwgen.pwgen(
            int(args.generate_and_set_password),
            capitalize=True,
            allowed_symbols=',.;!-')
        keychain.set(args.node, Keychain.PASSWORD_FIELD, password)

    if args.set_password:
        # READ FROM CMD LINE
        p1 = getpass.getpass('enter password: '******'repeat password: '******'password does not match\n')
            return 1

        if len(p1) == 0 or len(p2) == 0:
            sys.stderr.write('password must not be empty\n')
            return 1

        keychain.set(args.node, Keychain.PASSWORD_FIELD, p1)

    if args.set_username:
        keychain.set(args.node, Keychain.USERNAME_FIELD, args.set_username)

    if args.edit_note:
        tf = tempfile.NamedTemporaryFile(delete=False, dir=os.getcwd())

        old_note = keychain.get(args.node, Keychain.NOTE_FIELD)
        if old_note is None:
            old_note = ''

        tf.write(old_note.encode())
        tf.close()
        tfn = os.path.join(os.getcwd(), tf.name)
        tf.close()

        editor = os.environ.get("VISUAL") or os.environ.get("EDITOR", "vi")
        p = subprocess.Popen("%s \"%s\"" % (editor, tfn), shell=True)
        p.wait()

        tf = open(tfn)
        new_note = tf.read()
        tf.close()
        os.unlink(tfn)

        if old_note != new_note:
            keychain.set(args.node, Keychain.NOTE_FIELD, new_note)
            sys.stderr.write('note updated\n')
        else:
            sys.stderr.write('no change to note\n')

    if keychain.is_dirty():
        if not os.path.exists(args.file):
            sys.stderr.write('creating new file\n')

        keychain.save(args.file)

    return 0
示例#47
0
def main(data=None):
    parser = argparse.ArgumentParser(description='random PassWord GENerator')

    parser.add_argument('pw_length', default='8', type=int,
                        nargs='?',
                        help="Password length")

    parser.add_argument('--capitalize', '-c', action='store_true',
                        dest="capitalize",
                        help="Include at least one capital letter in "
                             "the password")

    parser.add_argument('--no-capitalize', '-A', action='store_true',
                        dest="no_capitalize",
                        help="Don't include capital letters in the password")

    parser.add_argument('--numerals', '-n', action='store_true',
                        dest='numerals',
                        help="Include at least one number in the password")
    parser.add_argument('--no-numerals', '-0', action='store_true',
                        dest='no_numerals',
                        help="Don't include numbers in the password")

    parser.add_argument('--symbols', '-y', action='store_true', dest='symbols',
                        help="Include at least one special symbol in "
                             "the password")

    # parser.add_argument('--secure', '-s', action='store_true', dest='secure',
    #                     help="Generate completely random passwords")

    parser.add_argument('--ambiguous', '-B', action='store_true',
                        dest='no_ambiguous',
                        help="Don't include ambiguous characters in "
                             "the password")

    # parser.add_argument('-H or --sha1=path/to/file[#seed]
    #                     help="Use sha1 hash of given file as a (not so) "
    #                          "random generator")

    # parser.add_argument('-C', action='store_true', dest='print_in_columns',
    #                     help="Print the generated passwords in columns")

    parser.add_argument('-1', action='store_const', const=1, default='160',
                        dest='num_pw',
                        help="Don't print the generated passwords in columns")

    # parser.add_argument('--no-vowels', '-v', action='store_false',
    #                     dest='vowels',
    #                     help="Do not use any vowels so as to avoid
    #                          "accidental nasty words")

    args = parser.parse_args()

    d = vars(args)

    result = pwgen.pwgen(**d)

    if type(result) == list:
        for y in range(20):
            print(" ".join([result.pop() for x in range(8)]))
    else:
        print(result)
示例#48
0
def rcauth(request):
    logger.debug("rcauth() start!")
    # Only POST is supported on this URL.
    if request.method != "POST":
        raise PermissionDenied

    # Rapid Connect authorization is disabled, so don't process anything.
    if not settings.LOGIN_FRONTENDS["aaf"]["enabled"] and not settings.LOGIN_FRONTENDS["aafe"]["enabled"]:
        raise PermissionDenied

    try:
        # Verifies signature and expiry time
        verified_jwt = jwt.decode(
            request.POST["assertion"],
            settings.RAPID_CONNECT_CONFIG["secret"],
            audience=settings.RAPID_CONNECT_CONFIG["aud"],
        )

        # Check for a replay attack using the jti value.
        jti = verified_jwt["jti"]
        if JTI.objects.filter(jti=jti).exists():
            logger.debug("Replay attack? " + str(jti))
            request.session.pop("attributes", None)
            request.session.pop("jwt", None)
            request.session.pop("jws", None)
            django_logout(request)
            return redirect("/")
        else:
            JTI(jti=jti).save()

        if (
            verified_jwt["aud"] == settings.RAPID_CONNECT_CONFIG["aud"]
            and verified_jwt["iss"] == settings.RAPID_CONNECT_CONFIG["iss"]
        ):
            request.session["attributes"] = verified_jwt["https://aaf.edu.au/attributes"]
            request.session["jwt"] = verified_jwt
            request.session["jws"] = request.POST["assertion"]

            institution_email = request.session["attributes"]["mail"]
            edupersontargetedid = request.session["attributes"]["edupersontargetedid"]
            principalname = request.session["attributes"]["edupersonprincipalname"]

            logger.debug("Successfully authenticated %s via Rapid Connect." % institution_email)

            # Create a user account and profile automatically. In future,
            # support blacklists and whitelists.
            first_name = request.session["attributes"]["givenname"]
            c_name = request.session["attributes"].get("cn", "").split(" ")
            if not first_name and len(c_name) > 1:
                first_name = c_name[0]
            user_args = {
                "id": institution_email.lower(),
                "email": institution_email.lower(),
                "password": pwgen.pwgen(),
                "first_name": first_name,
                "last_name": request.session["attributes"]["surname"],
            }

            # if a principal domain is set strip domain from
            # 'edupersonprincipalname' and use remainder as user id.
            try:
                if settings.LOGIN_HOME_ORGANIZATION:
                    domain = "@" + settings.LOGIN_HOME_ORGANIZATION
                    if ";" not in principalname and principalname.endswith(domain):
                        user_id = principalname.replace(domain, "").lower()
                        user_args["id"] = user_id
            except:
                logger.debug("check principal domain failed with: %s" % sys.exc_info()[0])

            # Check for an email collision.
            for matching_user in UserProfile.objects.filter(user__email__iexact=user_args["email"]):
                if (
                    matching_user.rapidConnectEduPersonTargetedID is not None
                    and matching_user.rapidConnectEduPersonTargetedID != edupersontargetedid
                ):
                    del request.session["attributes"]
                    del request.session["jwt"]
                    del request.session["jws"]
                    django_logout(request)
                    raise PermissionDenied

            user = get_or_create_user(user_args, authMethod="aaf")
            if user is not None:
                user.backend = "django.contrib.auth.backends.ModelBackend"
                djauth.login(request, user)
                return redirect("/")
        else:
            del request.session["attributes"]
            del request.session["jwt"]
            del request.session["jws"]
            django_logout(request)
            raise PermissionDenied  # Error: Not for this audience
    except jwt.ExpiredSignature:
        del request.session["attributes"]
        del request.session["jwt"]
        del request.session["jws"]
        django_logout(request)
        raise PermissionDenied  # Error: Security cookie has expired
    except Exception, e:
        logger.debug("rcauth() failed with: %s" % e)
        raise PermissionDenied
示例#49
0
from os import getenv, path
from pwgen import pwgen
import sh


def generate_page(ssid, pswd, address):
    home = getenv('HOME')
    template_path = path.join(home, 'screenly/templates/hotspot.html')
    with open(template_path) as f:
        template = Template(f.read())

    context = {
        'network': ssid,
        'ssid_pswd': pswd,
        'address': address
    }

    with open('/tmp/hotspot.html', 'w') as out_file:
        out_file.write(template.render(context=context))


if __name__ == "__main__":
    if not gateways().get('default'):
        ssid = 'ScreenlyOSE-{}'.format(pwgen(4, symbols=False))
        ssid_password = pwgen(8, symbols=False)
        generate_page(ssid, ssid_password, 'screenly.io/wifi')

        wifi_connect = sh.sudo('wifi-connect', '-s', ssid, '-p', ssid_password, '-o', '9090')
    else:
        pass
示例#50
0
def main(argv=sys.argv):
    if len(argv) != 3:
        usage(argv)
    config_uri = argv[1]
    try:
        num_users = int(argv[2])
    except ValueError:
        usage(argv)
    setup_logging(config_uri)
    settings = get_appsettings(config_uri)
    config = Configurator(settings=settings)
    config.add_directive('set_password_context', set_password_context)
    db_session = init_sa(config)
    logger = logging.getLogger('speak_friend.createusers')

    if 'speak_friend.password_hasher' in settings:
        config.include(settings['speak_friend.password_hasher'])
    else:
        from passlib.apps import ldap_context
        config.set_password_context(context=ldap_context)
    # makes the password_context available on the registry
    config.commit()

    pass_ctx = config.registry.password_context
    user_num = 1
    buf = StringIO()
    cols = ['username', 'first_name', 'last_name', 'email', 'password_hash',
            'password_salt', 'login_attempts', 'admin_disabled',
            'is_superuser']
    csv_file = csv.DictWriter(buf, cols, delimiter='\t', lineterminator='\n')
    logger.info("Beginning to create %d users,", num_users)
    cxn = db_session.connection()
    cur = cxn.connection.cursor()
    user_num += 0
    user_passwords = {}
    while user_num <= num_users:
        first_name = u'Test'
        last_name = pwgen(num_pw=1, pw_length=10, no_numerals=True,
                          no_symbols=True)
        username = u'%s.%s' % (first_name, last_name)
        password = pwgen(num_pw=1, pw_length=20)
        user_passwords[username] = password
        csv_file.writerow(dict(
            username=username,
            first_name=first_name,
            last_name=last_name,
            email=u'*****@*****.**' % username,
            password_hash=pass_ctx.encrypt(password),
            password_salt='',
            login_attempts=0,
            admin_disabled=False,
            is_superuser=False,
        ))
        logger.info("Created user %s, %04d/%04d.",
                    username, user_num, num_users)
        user_num += 1

    logger.info("Committing...")
    tname = '%s.%s' % (UserProfile.__table__.schema,
                       UserProfile.__table__.name)
    buf.seek(0)
    cur.copy_from(buf, tname, columns=cols)
    cxn.connection.commit()

    for uname, pw in user_passwords.items():
        print uname, pw
示例#51
0
def generate_password(length=12):
    return pwgen(int(length), no_capitalize=True, no_symbols=True)
示例#52
0
def gen_root_pass(pass_length):
    cleartext_pass = pwgen(pass_length, no_symbols=True)
    return cleartext_pass
示例#53
0
文件: views.py 项目: hkarl/svpb
def preparePassword(accountList=None):
    """For the given accounts, prepare the passwords and the PDFs for the letters

    Arguments:
    - `accountList`: List of User objects
    Returns:
    - List of tuples: (user object, PDF file)
    """

    from jinja2 import Template
    import codecs, subprocess

    r = []

    # print "preparing passwords for: ", accountList

    for u in accountList:
        pw = pwgen(6, no_symbols=True, no_ambiguous=True)
        u.set_password(pw)
        u.save()

        r.append({'user': u,
                  'mitglied': u.mitglied,
                  'password': pw,
                  'status': u.mitglied.get_status_display(),
                  'geburtsdatum': u.mitglied.geburtsdatum.strftime('%d.%m.%Y'),
                  })

    # generate the PDF
    # assume the template is in templates

    templateText = EmailTemplate.objects.get(name='newUserLaTeX')
    # print templateText.content

    rendered = Template(templateText.content).render(dicts=r)
    # print rendered

    # and now process this via latex:
    f = codecs.open('letters.tex', 'w', 'utf-8')
    f.write(rendered)
    f.close()

    # TODO: use better file names, protect against race conditions

    retval = subprocess.call (["xelatex",
                                '-interaction=batchmode',
                                "letters.tex"])
    ## retval = subprocess.call (["xelatex",
    ##                                '-interaction=batchmode',
    ##                                "letters.tex"])

    # move this file into a directory where only Vorstand has access!
    # remove an older letter first; ignore errors here
    import shutil, os
    try:
        os.remove (os.path.join (SENDFILE_ROOT, 'letters.pdf'))
    except:
        pass

    shutil.move("letters.pdf", SENDFILE_ROOT)

    return r
def password_generator():
    return pwgen(pw_length=25,no_symbols=True)