示例#1
0
def signup_user():
    pwd = genword(length=16)
    uid = genword(length=8)
    hashes.insert_one({
        "hash":
        pbkdf2_sha256.encrypt(pwd, rounds=2000, salt_size=16),
        "uid":
        uid
    })
    new_user = {"uid": uid, "balance": "10000", "portfolio": {}}
    users.insert_one(new_user)
    return f"Registered! Set these headers on your requests to authenticate:\nuid: {uid}\nauthorization_key: {pwd}"
示例#2
0
    def test_charset(self):
        """'charset' & 'chars' options"""
        # charset option
        results = genword(charset="hex", returns=5000)
        self.assertResultContents(results, 5000, hex)

        # chars option
        # there are 3**3=27 possible combinations
        results = genword(length=3, chars="abc", returns=5000)
        self.assertResultContents(results, 5000, "abc", unique=27)

        # chars + charset
        self.assertRaises(TypeError, genword, chars='abc', charset='hex')
示例#3
0
文件: setup.py 项目: kuwv/spades
def start(ctx, certs_path='./nginx/certs'):
    '''Start all services.'''
    certs.setup(ctx)
    filesystem.mkdir(ctx, certs_path)
    certs.generate(ctx,
                   name=['spades.local', 'localhost'],
                   key=f"{certs_path}/spades.key",
                   cert=f"{certs_path}/spades.crt")
    env = {
        'POSTGRESQL_PASSWORD': genword(entropy=56, length=128),
        'REDIS_PASSWORD': genword(entropy=56, length=128)
    }
    compose.start(ctx, files=[], env=env)
示例#4
0
    def test_returns(self):
        """'returns' keyword"""
        # returns=int option
        results = genword(returns=5000)
        self.assertResultContents(results, 5000, ascii_62)

        # returns=iter option
        gen = genword(returns=iter)
        results = [next(gen) for _ in range(5000)]
        self.assertResultContents(results, 5000, ascii_62)

        # invalid returns option
        self.assertRaises(TypeError, genword, returns='invalid-type')
示例#5
0
    def test_charset(self):
        """'charset' & 'chars' options"""
        # charset option
        results = genword(charset="hex", returns=5000)
        self.assertResultContents(results, 5000, hex)

        # chars option
        # there are 3**3=27 possible combinations
        results = genword(length=3, chars="abc", returns=5000)
        self.assertResultContents(results, 5000, "abc", unique=27)

        # chars + charset
        self.assertRaises(TypeError, genword, chars='abc', charset='hex')
示例#6
0
    def test_returns(self):
        """'returns' keyword"""
        # returns=int option
        results = genword(returns=5000)
        self.assertResultContents(results, 5000, ascii_62)

        # returns=iter option
        gen = genword(returns=iter)
        results = [next(gen) for _ in range(5000)]
        self.assertResultContents(results, 5000, ascii_62)

        # invalid returns option
        self.assertRaises(TypeError, genword, returns='invalid-type')
示例#7
0
文件: crypto.py 项目: wobsta/moin
def generate_token(key=None, stamp=None):
    """
    generate a pair of a secret key and a crypto token.

    you can use this to implement a password recovery functionality by
    calling generate_token() and transmitting the returned token to the
    (correct) user (e.g. by email) and storing the returned (secret) key
    into the user's profile on the server side.

    after the user received the token, he returns to the wiki, gives his
    user name or email address and the token he received. read the (secret)
    key from the user profile and call valid_token(key, token) to verify
    if the token is valid. if it is, consider the user authenticated, remove
    the secret key from his profile and let him reset his password.

    :param key: give it to recompute some specific token for verification
    :param stamp: give it to recompute some specific token for verification
    :rtype: 2-tuple
    :returns: key, token (both unicode)
    """
    if key is None:
        key = genword(length=32)
    if stamp is None:
        stamp = int(time.time())
    h = hmac.new(str(key), str(stamp), digestmod=hashlib.sha256).hexdigest()
    token = u"{0}-{1}".format(stamp, h)
    return unicode(key), token
示例#8
0
    def create_user(self, user_kwargs, _commit=True):
        """Create a new user record and optionally persist to the database.

        :param user_kwargs: dict of values to construct the User record. Special arg is
            `mail_enabled`, which will be popped out.
        :param _commit: option for persisting record to database. Default True.
        """
        mail_enabled = user_kwargs.pop('mail_enabled', True)
        from passlib.pwd import genword
        user_kwargs.setdefault('password', genword(entropy='secure'))
        user_class = self.entity_registry.user_cls
        user = user_class(**user_kwargs)
        db.session.add(user)
        db.session.flush()

        # generate the token AFTER flush, because the token may depend on things like timestamps
        # which may not be available earlier
        user.token_generate()

        if mail_enabled and self.mail_manager:
            self.mail_manager.send_new_user(user)

        # use add + commit here instead of user_class.add() above so the user isn't actually
        # committed if mail isn't sent.
        if _commit:
            db.session.commit()
        return user
示例#9
0
    def generate_token(cls) -> str:
        """Generate a random token for the invitation.

        Returns:
            Random token.
        """
        return genword(length=64)
示例#10
0
async def main(config, loop=None):
    if loop is None:
        loop = asyncio.get_event_loop()

    dsn = "postgres://{}:{}@{}:{}/{}".format(config["username"],
                                             config["password"],
                                             config["host"], config["port"],
                                             config["database"])
    conn = await asyncpg.connect(dsn)

    # create a dummy repo for creating the admin
    repo_id = await conn.fetchval(
        "INSERT INTO repository (name, opened) VALUES ($1, $2) RETURNING id",
        "Dummy", False)

    admin_password = genword(length=8, charset="ascii_50")
    print("Admin password = {}".format(admin_password))

    # super user
    await conn.execute(
        ("INSERT INTO client (login, password_hash, confirmed, super_user, "
         "first_name, last_name, email_address, repository_id) "
         "VALUES ($1, $2, $3, $4, $5, $6, $7, $8)"), "admin",
        sha256_crypt.hash(admin_password), True, True, "Admin", "Admin",
        "*****@*****.**", repo_id)
示例#11
0
 def send_recover_mail(cls, email, create_user, privacy=False):
     if create_user:
         user = User()
         user.email = email
         user.password = pwd.genword(length=16)
         user.active = False
     else:
         user = User.query.filter_by(email=email)
         if user.count() != 1:
             return False
         user = user.first()
     if privacy:
         user.privacy = True
     db.session.add(user)
     db.session.commit()
     recover_serializer = URLSafeTimedSerializer(
         current_app.config['SECRET_KEY'])
     recover_url = "%s/recover-check?id=%s" % (
         current_app.config['PROJECT_URL'],
         recover_serializer.dumps(
             [user.id,
              sha256(str.encode(user.password)).hexdigest()],
             salt=current_app.config['SECURITY_PASSWORD_SALT']))
     msg = Message(
         "Account zur Konfiguration des Feinstaubsensors erstellen",
         sender=current_app.config['MAILS_FROM'],
         recipients=[email],
         body=render_template('emails/register-existing.txt'
                              if create_user else 'emails/recover.txt',
                              recover_url=recover_url))
     mail.send(msg)
     return True
示例#12
0
 def create_auth0_user(self, full_name, user_email):
     user_id = str(uuid.uuid4())
     users = Users(domain, self.mgmt_api_token)
     generated_password = pwd.genword(entropy=56, charset="ascii_62")
     user_res = users.create({
         "email":
         user_email,
         "user_metadata": {
             "was_invite": True
         },
         "blocked":
         False,
         "email_verified":
         False,
         "app_metadata": {},
         "nickname":
         full_name,
         "picture":
         "https://secure.gravatar.com/avatar/15626c5e0c749cb912f9d1ad48dba440?s=480&r=pg&d=https%3A%2F%2Fssl"
         ".gstatic.com%2Fs2%2Fprofiles%2Fimages%2Fsilhouette80.png",
         "user_id":
         user_id,
         "connection":
         "Username-Password-Authentication",
         "password":
         generated_password,
         "verify_email":
         True,
     })
     LOG.info(
         f"Created user in auth0 for email {user_email} with user_id {user_id}"
     )
     return user_res
示例#13
0
def _generate_password():
    """
    Returns a randomly generated string of up to 32 characters
    :return: str
    """

    return pwd.genword(entropy=48)
示例#14
0
def register_device():
    if 'loggedin' not in session:
        return redirect(url_for('ui.login', r=url_for('ui.register_device')))

    msg = ''
    if request.method == 'POST':
        identifier = request.form['identifier']

        exists = None
        if not identifier:
            flash('An identifier is required')
        else:
            try:
                secret_key = pwd.genword(entropy=56, charset='hex', length=32)
                cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
                cursor.execute(
                    'SELECT identifier FROM devices WHERE identifier = %s',
                    (identifier, ))
                exists = cursor.fetchone()
                if exists:
                    msg = 'An device with that identifier already exists'
                else:
                    cursor.execute(
                        'INSERT INTO devices (identifier, secret_key) VALUES (%s, %s)',
                        (identifier, secret_key))
                    mysql.connection.commit()
            finally:
                cursor.close()
            if not exists:
                return redirect(
                    url_for('ui.device_details', device_id=identifier))
    return render_template('register_device.html', msg=msg)
示例#15
0
def getSecretPassword():
    if (current_user.is_authenticated and current_user.id == 1):
        password = pwd.genword(entropy=52, length=48, charset="ascii_72")
        current_user.edit_name(
            password_encode(password))  #Update new secret password to database
        return password
    else:
        return redirect(url_for('logout'))
示例#16
0
def device_ios10_profile(device):
	password = pwd.genword()
	return flask.Response(
		response=flask.render_template('frontend/devices/ios10_profile.xml', 
			device=device,
			b64encode=lambda s: b64encode(s).decode('US-ASCII'),
			password=password), 
		mimetype='application/octet-stream')
示例#17
0
    def test_general(self):
        """general behavior"""

        # basic usage
        result = genword()
        self.assertEqual(len(result), 9)

        # malformed keyword should have useful error.
        self.assertRaisesRegex(TypeError, "(?i)unexpected keyword.*badkwd", genword, badkwd=True)
示例#18
0
    def test_general(self):
        """general behavior"""

        # basic usage
        result = genword()
        self.assertEqual(len(result), 9)

        # malformed keyword should have useful error.
        self.assertRaisesRegex(TypeError, "(?i)unexpected keyword.*badkwd", genword, badkwd=True)
示例#19
0
def _compute_clear_passwordlist(count):
    """internal unique routine to compute passwords"""
    return pwd.genword(
        length=16,
        entropy=56,
        chars=
        "aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ0123456789&~\#{[|^@]}$%*,?.;/:!=+)(-'",
        returns=count,
    )
示例#20
0
def reset_password(id):
    if not session['user']['admin']: return redirect('/profile')

    user = User.query.get(id)

    user.temp_pw = pwd.genword(length=12, charset='ascii_50')
    user.password = None
    db.session.commit()

    return redirect('/users')
示例#21
0
 def get_user(name):
     if name in user_cache:
         return user_cache[name]
     user = User.query.filter_by(name=name).first()
     if user is not None:
         return user
     user_pass = pwd.genword(128, charset='ascii_50')
     user = User(name=name, pass_hash=bcrypt.hash(user_pass))
     print(f"Generated user={name} pass={user_pass}")
     db.session.add(user)
     return user
示例#22
0
def generate_password(length: int) -> str:
    """Generate a password of a certain length.

    The password is generated as :param:`length` independent choices
    of a certain charset.  The charset does not include ambiguous
    characters like ``l``, ``1``, ``0`` and ``O``.
    """
    # without hard to distinguish characters l/1 0/O
    charset = "abcdefghijkmnopqrstuvwxyz!$%&()=.," \
              ":;-_#+23456789ABCDEFGHIJKLMNPQRSTUVWXYZ"
    return genword(length=length, chars=charset)
示例#23
0
def dashboard():
    if 'loggedin' in session:
        if request.method == 'POST':
            if 'device_form' in request.form:
                #for later
                pass
            if 'api_key_form' in request.form:
                print("it's api key form")
                identifier = request.form['identifier']

                exists = None
                if not identifier:
                    flash('An identifier is required')
                else:
                    try:
                        secret_key = pwd.genword(entropy=56,
                                                 charset='hex',
                                                 length=32)
                        cursor = mysql.connection.cursor(
                            MySQLdb.cursors.DictCursor)
                        cursor.execute(
                            'SELECT id FROM api_keys WHERE api_key = %s',
                            (identifier, ))
                        exists = cursor.fetchone()
                        if exists:
                            msg = 'A key with that name already exists'
                        else:
                            cursor.execute(
                                'INSERT INTO api_keys (name, api_key) VALUES (%s, %s)',
                                (identifier, secret_key))
                            mysql.connection.commit()
                    finally:
                        cursor.close()
            print(request.form)

        cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
        cursor.execute('SELECT identifier as id FROM devices')
        devices = cursor.fetchall()
        last_data = {}
        for device in devices:
            cursor.execute(
                'select time from data where device = %s group by time order by time desc limit 1',
                (device['id'], ))
            last_data[device['id']] = cursor.fetchone()

        cursor.execute('SELECT id, name, api_key FROM api_keys')
        api_keys = cursor.fetchall()

        return render_template('dashboard.html',
                               devices=devices,
                               api_keys=api_keys,
                               last_data=last_data)

    return redirect(url_for('ui.login', r=url_for('ui.dashboard')))
示例#24
0
def resetTokenPassword(tokenDB: TokenDB, token: Token) -> str:
    """Sets the password for this token to a new random string.

    Returns the new password. Since only a hash is stored in the
    password database, it is not possible to retrieve it later.
    """
    password = genword(length=16)
    passwordFile = tokenDB.passwordFile
    passwordFile.load_if_changed()
    passwordFile.set_password(token.getId(), password)
    writePasswordFile(passwordFile)
    return password
示例#25
0
def add_members(
        organization_id: int,
        *,
        invites: List[UserInvite] = Body(...),
        auth=Depends(authorization("organizations:add_members")),
        db: Session = Depends(get_db),
        current_user: User = Depends(get_current_user),
):
    try:
        members = crud.organization.get_members(db, id=organization_id)

        users_to_add = (invite for invite in invites
                        if invite.email not in (u.get("email")
                                                for u in members))

        for invite in users_to_add:
            user_in_db = user.get_by_email(db, email=invite.email)
            role = invite.role if invite.role else "guest"

            if not user_in_db:
                user_in_db = user.create(
                    db,
                    obj_in=UserCreate(
                        full_name=invite.full_name,
                        email=invite.email,
                        password=pwd.genword(),
                    ),
                )
            else:
                organization_in_db = crud.organization.get(db,
                                                           id=organization_id)

                if organization_in_db:
                    send_new_invitation_email_task.delay(
                        full_name=user_in_db.full_name,
                        email_to=user_in_db.email,
                        organization=organization_in_db.name,
                        role=role)

            enforcer.add_role_for_user_in_domain(
                str(user_in_db.id),
                role,
                str(organization_id),
            )
            enforcer.load_policy()

        return [
            user for user in get_members(
                organization_id, auth=auth, db=db, current_user=current_user)
            if user.get("email") in (invite.email for invite in invites)
        ]
    except Exception as e:
        logging.error(e)
示例#26
0
    def generate_serial(length: int = 5) -> str:
        """Generate a valid session serial.

        A serial is comprised of the current timestamp and N random characters.

        Args:
            length (int): Length for the random string appended to the timestamp.

        Returns:
            Serial string.
        """
        return '{}{}'.format(int(time.time()), genword(length=length))
示例#27
0
 def verify_password(self, password):
     if self.password is None:
         return False
     valid, new_hash = pwd_context.verify_and_update(
         password, self.password)
     if valid:
         if new_hash:
             self._password = new_hash
             self.session_token = genword(length=50)
             self.save()
         return True
     return False
示例#28
0
    def keyFor(self, path: SandboxedPath) -> str:
        """Return a key for accessing the given sandbox path.
        """

        # Skip key generation if artifacts are public.
        if self.project.anonguest:
            return 'anon'

        key = genword(length=self.keyLength)
        self._activeKeys[key] = path
        reactor.callLater(self.keyTimeout, self.keyExpired, key)
        return key
示例#29
0
def reset_password(userid: str) -> Response:
    user = User.query.filter_by(id=userid).first()

    if user is None:
        flash(i8n.USER_DOES_NOT_EXIST, category='error')
        return redirect(url_for('admin'))

    new_password = genword()
    user.password = encrypt_password(new_password)
    user.save()

    flash(i8n.PASSWORD_CHANGED_BY_ADMIN + new_password, category='success')
    return redirect(url_for('admin'))
示例#30
0
def user_add(args):
	if args.generate:
		password = pwd.genword(128, charset='ascii_50')
	else:
		password = getpass.getpass("Password: "******"Again: ")
		if password != password_verify:
			raise RuntimeError("Passwords don't match.")
	pass_hash = bcrypt.hash(password)
	user = User(name=args.name, pass_hash=pass_hash)
	db.session.add(user)
	db.session.commit()
	print(f"User id: {user.id}")
示例#31
0
def create_organization_root_node(
    *,
    db: Session = Depends(get_db),
    organization_in: OrganizationCreateRoot,
    current_user: User = Depends(get_current_user),
) -> Optional[Organization]:
    """
    Create a new **root node for organizations tree**;
    
    If `owner_email` is present organization tree ownership will be affected to *existing or newly created user*,
    else organizations tree ownership will be affected to *superuser*.
    """
    if not current_user.is_superuser:
        raise HTTPException(
            status_code=403,
            detail="You are not authorized to perform this action.")
    new_organization_root_node = organization.create_root(
        db, obj_in=organization_in).to_schema()
    if organization_in.owner_email:
        user_in_db = user.get_by_email(db, email=organization_in.owner_email)
        if not user_in_db:
            user_in_db = user.create(
                db,
                obj_in=UserCreate(
                    full_name=organization_in.owner_email.split("@")[0],
                    email=organization_in.owner_email,
                    password=pwd.genword(),
                ),
            )
        if new_organization_root_node:
            send_new_invitation_email_task.delay(
                full_name=user_in_db.full_name,
                email_to=user_in_db.email,
                organization=new_organization_root_node.name,
                role="owner")
            enforcer.add_role_for_user_in_domain(
                str(user_in_db.id), "owner",
                str(new_organization_root_node.id))
            enforcer.load_policy()
    else:
        enforcer.add_role_for_user_in_domain(
            str(current_user.id), "owner", str(new_organization_root_node.id))
        enforcer.load_policy()
    current_roles = enforcer.get_roles_for_user_in_domain(
        str(current_user.id), str(new_organization_root_node.id))
    if len(current_roles) > 0:
        new_organization_root_node.current_user_role = current_roles[0]
    if current_user.is_superuser:
        new_organization_root_node.current_user_role = 'admin'
    # new_organization_root_node.current_user_role = current_roles[0]
    return new_organization_root_node
示例#32
0
文件: config.py 项目: kuwv/spades
class Config:
    '''Provide Flask configuration.'''

    SQLALCHEMY_DATABASE_URI: str = os.getenv(
        'SQLALCHEMY_DATABASE_URI',
        f"{db_type}://{db_user}:{db_pass}@{db_host}:{db_port}/{db_name}")
    SQLALCHEMY_ECHO: bool = bool(os.getenv('SQLALCHEMY_ECHO', True))
    SQLALCHEMY_TRACK_MODIFICATIONS: bool = bool(
        os.getenv('SQLALCHEMY_TRACK_MODIFICATIONS', False))

    SESSION_COOKIE_SECURE: bool = True
    SESSION_COOKIE_HTTPONLY: bool = True
    SESSION_COOKIE_SAMESITE: str = 'Lax'

    SECRET_KEY: str = genword(entropy=56, length=128)
    WTF_CSRF_SECRET_KEY: str = genword(entropy=56, length=128)

    SESSION_TYPE: str = session_type
    SESSION_PERMANENT: bool = True
    SESSION_USE_SIGNER: bool = True
    SESSION_REDIS = Redis(**session)  # type: ignore
    SSE_REDIS_URL = "redis://:{p}@{h}:{s}".format(p=session['password'],
                                                  h=session['host'],
                                                  s=session['port'])
示例#33
0
 def _initArgs(self,
               element: Optional[Resource]
               ) -> Mapping[str, object]:
     if element is None:
         return dict(secret=genword(length=20))
     elif element.typeName == repoResourceTypeName:
         return dict(
             locator = element.getParameter('locator') or '',
             secret = element.getParameter('secret') or '',
             capabilities = ' '.join(element.capabilities),
             description = element['description']
             )
     else:
         raise InvalidRequest(
             f'Resource "{element.getId()}" is not a repository'
             )
示例#34
0
 def _create_default_users(self):
     print('adding default system users')
     roles = self.session.query(Role).filter(Role.name == 'system').all()
     for user_data in system_users:
         user_fields = system_users[user_data]
         print('  user: @%s' % user_fields['login'])
         if user_fields['password'] is None:
             user_fields['password'] = pwd.genword()
         password_hash = pwd_context.encrypt(user_fields['password'])
         user = User(name_first=str(user_fields['first']), name_last=str(user_fields['last']),
                     email=str(user_fields['email']), login=user_fields['login'], password_hash=password_hash,
                     roles=roles)
         try:
             self.session.add(user)
             self.session.commit()
         except IntegrityError:
             self.session.rollback()
示例#35
0
文件: tokens.py 项目: insxa/Mailu
def token_create(user_email):
    user_email = user_email or flask_login.current_user.email
    user = models.User.query.get(user_email) or flask.abort(404)
    form = forms.TokenForm()
    wtforms_components.read_only(form.displayed_password)
    if not form.raw_password.data:
        form.raw_password.data = pwd.genword(entropy=128, charset="hex")
        form.displayed_password.data = form.raw_password.data
    if form.validate_on_submit():
        token = models.Token(user=user)
        token.set_password(form.raw_password.data)
        form.populate_obj(token)
        db.session.add(token)
        db.session.commit()
        flask.flash('Authentication token created')
        return flask.redirect(
            flask.url_for('.token_list', user_email=user.email))
    return flask.render_template('token/create.html', form=form)
示例#36
0
 def reset_password(self, password: Optional[str] = None) -> str:
     new_password = password or genword()
     self.password = hash_password(new_password)
     return new_password