Python werkzeug.security.generate_password_hash() Examples

The following are 30 code examples of werkzeug.security.generate_password_hash(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module werkzeug.security , or try the search function .
Example #1
Source File: routes.py    From thewarden with MIT License 8 votes vote down vote up
def reset_token(token):
    if current_user.is_authenticated:
        return redirect(url_for("main.home"))
    user = User.verify_reset_token(token)
    if user is None:
        flash("That is an invalid or expired token", "warning")
        return redirect(url_for("users.reset_request"))
    form = ResetPasswordForm()
    if form.validate_on_submit():
        hash = generate_password_hash(form.password.data)
        user.password = hash
        db.session.commit()
        flash("Your password has been updated! You are now able to log in",
              "success")
        return redirect(url_for("users.login"))
    return render_template("reset_token.html",
                           title="Reset Password",
                           form=form) 
Example #2
Source File: views.py    From incepiton-mysql with MIT License 7 votes vote down vote up
def user_create():
    """
    Create users.
    :return:
    """
    form = UserForm()

    if form.validate_on_submit():
        user = User()
        user.name = form.name.data
        user.hash_pass = generate_password_hash(form.password.data)
        user.role = form.role.data
        user.email = form.email.data
        db.session.add(user)
        db.session.commit()

        return redirect(url_for('.user'))

    return render_template('admin/user_create.html', form=form) 
Example #3
Source File: manage.py    From flask_simplelogin with MIT License 7 votes vote down vote up
def create_user(**data):
    """Creates user with encrypted password"""
    if 'username' not in data or 'password' not in data:
        raise ValueError('username and password are required.')

    # Hash the user password
    data['password'] = generate_password_hash(
        data.pop('password'),
        method='pbkdf2:sha256'
    )

    # Here you insert the `data` in your users database
    # for this simple example we are recording in a json file
    db_users = json.load(open('users.json'))
    # add the new created user to json
    db_users[data['username']] = data
    # commit changes to database
    json.dump(db_users, open('users.json', 'w'))
    return data


# [--- Flask Factories  ---] 
Example #4
Source File: user.py    From AutoLink with Apache License 2.0 6 votes vote down vote up
def __create(self, args):
        result = {"status": "success", "msg": "创建用户成功"}
        user_path = self.app.config["AUTO_HOME"] + "/users/%s" % (args["username"])
        if not exists_path(user_path):
            mk_dirs(user_path)

            make_nod(user_path + "/config.json")

            user = {"fullname": args["fullname"],
                    "email": args["email"],
                    "passwordHash": generate_password_hash(args["password"]),
                    "data": []}
            json.dump(user, codecs.open(user_path + '/config.json', 'w', 'utf-8'))
        else:
            result["status"] = "fail"
            result["msg"] = "用户名称重复,创建失败"

        return result 
Example #5
Source File: verification_request.py    From everyclass-server with Mozilla Public License 2.0 6 votes vote down vote up
def _new_request(cls, identifier: str, verification_method: str, status: str, password: str = None) -> str:
        """
        新增一条注册请求

        :param identifier: 学号/教工号
        :param verification_method: password or email
        :param status: status of the request
        :param password: if register by password, fill everyclass password here
        :return: the `request_id`
        """
        if verification_method not in (cls.METHOD_PASSWORD, cls.METHOD_EMAIL):
            raise ValueError("verification_method must be one of email and password")

        request_id = uuid.uuid4()

        extra_doc = {}
        if password:
            extra_doc.update({"password": generate_password_hash(password)})

        request = VerificationRequest(request_id=request_id, identifier=identifier, method=verification_method,
                                      status=status, extra=extra_doc)
        db_session.add(request)
        db_session.commit()

        return str(request_id) 
Example #6
Source File: user.py    From everyclass-server with Mozilla Public License 2.0 6 votes vote down vote up
def add_user(cls, identifier: str, password: str, password_encrypted: bool = False) -> None:
        """新增用户。当用户已存在时,抛出ValueError。

        :param identifier: 学号或教工号
        :param password: 密码
        :param password_encrypted: 密码是否已经被加密过了(否则会被二次加密)
        """
        if not password_encrypted:
            password_hash = generate_password_hash(password)
        else:
            password_hash = password

        user = User(identifier=identifier, password=password_hash, create_time=datetime.datetime.now())

        db_session.add(user)
        try:
            db_session.commit()
        except IntegrityError as e:
            raise AlreadyRegisteredError from e 
Example #7
Source File: views.py    From incepiton-mysql with MIT License 6 votes vote down vote up
def register():
    form = RegisterForm()
    if form.validate_on_submit():
        user = User()
        user.name = form.username.data
        user.hash_pass = generate_password_hash(form.password.data)
        user.email = form.email.data

        # Register user's role is dev, by default.
        user.role = 'dev'

        db.session.add(user)
        db.session.commit()

        flash('You have registered successfully. Please login! ', category='success')

        return redirect(url_for('auth.login'))

    return render_template('auth/register.html', form=form) 
Example #8
Source File: auth.py    From chirp with MIT License 6 votes vote down vote up
def register():
    """Render the register page."""
    form = RegisterForm(request.form)
    if request.method == 'POST' and form.validate():
        c = mongo.db[app.config['USERS_COLLECTION']]
        user = {
            "username": form.username.data,
            "email": form.email.data,
            "first_name": form.first_name.data,
            "last_name": form.last_name.data,
            "password": generate_password_hash(form.password.data),
            "groups": [],
            "first_active": now_time(),
            "last_active": now_time()
        }
        logger.debug("User: %s" % user)
        user_count = c.count(dict())
        if user_count == 0:  # Make the first user an administrator
            user['groups'] = ['admin']
        _id = c.insert(user)
        next = request.args.get('next')
        return redirect(next or url_for('core.login'))
    errors = ','.join([value[0] for value in form.errors.values()])
    return render_template('register.html', message=errors) 
Example #9
Source File: user_management.py    From fame with GNU General Public License v3.0 6 votes vote down vote up
def create_user(name, email, groups, default_sharing, permissions, password=None):
    user = User.get(email=email.lower())

    if user:
        print "/!\ User with this email address already exists."
    else:
        user = User({
            'name': name,
            'email': email.lower(),
            'groups': groups,
            'default_sharing': default_sharing,
            'permissions': permissions,
            'enabled': True
        })
        if password:
            user['pwd_hash'] = generate_password_hash(password)
        user.save()
        print "[+] User created."

        user.generate_avatar()
        print "[+] Downloaded avatar."

    return user 
Example #10
Source File: views.py    From stack with MIT License 6 votes vote down vote up
def setup():
    """
    Called on a new install to setup an admin account
    """
    form = SetupForm(request.form)
    if form.validate_on_submit():
        # On submit, grab form information
        project_name = form.project_name.data
        password = form.password.data
        hashed_password = generate_password_hash(password)

        # Create the account
        db = DB()
        resp = db.create(project_name, password, hashed_password, admin=True)
        if resp['status']:
            flash(u'Project successfully created!')
            return redirect(url_for('index'))
        else:
            flash(resp['message'])

    return render_template('setup.html', form=form) 
Example #11
Source File: views.py    From stack with MIT License 6 votes vote down vote up
def create():
    """
    Page to create a new project account
    """
    form = CreateForm(request.form)
    if form.validate_on_submit():
        # On submit, grab form information
        project_name = form.project_name.data
        email = form.email.data
        password = form.password.data
        hashed_password = generate_password_hash(password)
        description = form.description.data

        # Create the account
        db = DB()
        resp = db.create(project_name, password, hashed_password, description=description, email=email)
        if resp['status']:
            flash(u'Project successfully created!')
            return redirect(url_for('admin_home', admin_id=g.admin['project_id']))
        else:
            flash(resp['message'])

    return render_template('create.html', form=form) 
Example #12
Source File: helpers.py    From spendb with GNU Affero General Public License v3.0 6 votes vote down vote up
def make_account(name='test', fullname='Test User',
                 email='test@example.com', twitter='testuser',
                 admin=False, password='password'):
    from spendb.model.account import Account

    # First see if the account already exists and if so, return it
    account = Account.by_name(name)
    if account:
        return account

    # Account didn't exist so we create it and return it
    account = Account()
    account.name = name
    account.fullname = fullname
    account.email = email
    account.twitter_handle = twitter
    account.admin = admin
    account.password = generate_password_hash(password)
    db.session.add(account)
    db.session.commit()
    return account 
Example #13
Source File: user.py    From walle-web with Apache License 2.0 6 votes vote down vote up
def avatar(self, user_id):
        random = generate_password_hash(str(user_id))
        fname = random[-10:] + '.jpg'
        current_app.logger.info(fname)

        f = request.files['avatar']
        # todo rename to uid relation
        # fname = secure_filename(f.filename)
        # TODO try
        ret = f.save(os.path.join(current_app.config['UPLOAD_AVATAR'], fname))
        user = UserModel.query.get(user_id)
        user.avatar = fname
        user.save()
        return self.render_json(data={
            'avatar': UserModel.avatar_url(user.avatar),
        }) 
Example #14
Source File: User.py    From AIOPS_PLATFORM with MIT License 5 votes vote down vote up
def __init__(self, user_name, password = None, email = None, group_list = None,
        role_list = None, business_system_list = None):
        self.user_name = user_name
        self.password = None if password is None else generate_password_hash(password)
        self.email = email
        self.group_list = group_list
        self.role_list = role_list
        self.business_system_list = business_system_list
        self.id = self.getId()

    ## __repr__ func 
Example #15
Source File: hashed_user.py    From web_develop with GNU General Public License v3.0 5 votes vote down vote up
def _set_password(self, plaintext):
        self._password = generate_password_hash(plaintext) 
Example #16
Source File: models.py    From graphql-pynamodb with MIT License 5 votes vote down vote up
def serialize(self, value):
        if is_password_hash(value):
            return value
        return generate_password_hash(value) 
Example #17
Source File: models.py    From BackManager with Apache License 2.0 5 votes vote down vote up
def password(self, password):
        self.password_hash = generate_password_hash(password) 
Example #18
Source File: basic.py    From burp-ui with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def change_password(self, user, passwd, old_passwd=None):
        """Change a user password"""
        self._setup_users()
        old_users = self.users
        self.load_users(True)
        current = self.users.get(
            user,
            old_users.get(user, None)
        )

        if not current:
            message = "user '{}' does not exist".format(user)
            self.logger.error(message)
            return False, message, NOTIF_ERROR

        if current['salted']:
            comp = check_password_hash
        else:
            def comp(x, y):
                return x == y

        curr = current['pwd']
        if old_passwd and not comp(curr, old_passwd):
            message = "unable to authenticate user '{}'".format(user)
            self.logger.error(message)
            return False, message, NOTIF_ERROR

        if comp(curr, passwd):
            message = 'password is the same'
            self.logger.warning(message)
            return False, message, NOTIF_WARN

        pwd = generate_password_hash(passwd)
        self.conf.options[self.section][user] = pwd
        self.conf.options.write()
        self.load_users(True)
        message = "user '{}' successfully updated".format(user)
        return True, message, NOTIF_OK 
Example #19
Source File: gen-passwords.py    From android-emulator-container-scripts with Apache License 2.0 5 votes vote down vote up
def main(argv):
    if len(argv) > 1:
        raise app.UsageError("Too many command-line arguments.")

    # Create salted passwords
    unsalted = pairwise(FLAGS.pairs)
    salted = {}
    for pair in unsalted:
        logging.info("%s : %s", pair[0], pair[1])
        salted[pair[0]] = generate_password_hash(pair[1])

    # And write them to a file
    with open(FLAGS.passwords, "w") as f:
        f.write(json.dumps(salted))

    # Create the jwks secrets and export them
    keys = jwk.JWK.generate(kty="RSA", size=2048)

    # Python 2 does signed crc32, unlike Python 3
    kid = hex(binascii.crc32(keys.export_public().encode('utf-8')) & 0xFFFFFFFF)

    public = json.loads(keys.export_public())
    private = json.loads(keys.export_private())
    public["kid"] = kid
    private["kid"] = kid
    public_jwks = {"keys": [public]}
    private_jwks = {"keys": [private]}

    with open(FLAGS.jwks + '_pub.jwks', 'w') as f:
        f.write(json.dumps(public_jwks, indent=2))

    with open(FLAGS.jwks + '_priv.jwks', 'w') as f:
        f.write(json.dumps(private_jwks, indent=2)) 
Example #20
Source File: basic.py    From burp-ui with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def add_user(self, user, passwd):
        """Add a user"""
        self._setup_users()
        if user in self.users:
            message = "user '{}' already exists".format(user)
            self.logger.warning(message)
            return False, message, NOTIF_WARN
        pwd = generate_password_hash(passwd)
        self.conf.options[self.section][user] = pwd
        self.conf.options.write()
        self.load_users(True)
        message = "user '{}' successfully added".format(user)
        return True, message, NOTIF_OK 
Example #21
Source File: cli.py    From burp-ui with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def hash_password(password, username, batch):
    """Hash a given password to fill the configuration file."""
    from werkzeug.security import generate_password_hash

    if batch and (not username or not password):
        err(
            'You need to provide both a username and a password using the '
            '-u and -p flags!',
        )
        sys.exit(1)

    askpass = False
    if not password:
        askpass = True
        import getpass
        password = getpass.getpass()

    hashed = generate_password_hash(password)
    if not batch:
        log("'{}' hashed into: {}".format(
            password if not askpass else '*' * 8,
            hashed
        ))
    if username:
        if not batch:
            info('#8<{}'.format('-' * 77))
        log('{} = {}'.format(username, hashed))
        if not batch:
            info('#8<{}'.format('-' * 77)) 
Example #22
Source File: test_00_base.py    From walle-web with Apache License 2.0 5 votes vote down vote up
def test_add_super(self):
        self.user_super_login['role'] = SUPER
        self.user_super_login['password'] = generate_password_hash(self.user_super_login['password'])
        user = UserModel(**self.user_super_login)
        user.save() 
Example #23
Source File: user.py    From walle-web with Apache License 2.0 5 votes vote down vote up
def general_password(self, password):
        """
        检查密码是否正确
        :param password:
        :return:
        """
        self.password = generate_password_hash(password)
        return generate_password_hash(password) 
Example #24
Source File: user.py    From walle-web with Apache License 2.0 5 votes vote down vote up
def get_password(self, password):
        """Set password."""
        return generate_password_hash(password) 
Example #25
Source File: user.py    From walle-web with Apache License 2.0 5 votes vote down vote up
def form2dict(self):
        return {
            'username': self.username.data,
            'password': generate_password_hash(self.password.data),
            'email': self.email.data,
            'role': self.role.data if self.role.data else '',
            'created_at': datetime.now(),
            'updated_at': datetime.now(),

        } 
Example #26
Source File: models.py    From flask-session-tutorial with MIT License 5 votes vote down vote up
def set_password(self, password):
        """Create hashed password."""
        self.password = generate_password_hash(password, method='sha256') 
Example #27
Source File: account.py    From spendb with GNU Affero General Public License v3.0 5 votes vote down vote up
def update(account):
    """ Change settings for the logged in user """
    require.account.update(current_user)
    data = AccountSettings().deserialize(request_data())

    # If the passwords don't match we notify the user
    if not data['password1'] == data['password2']:
        raise colander.Invalid(AccountSettings.password1,
                               _("Passwords don't match!"))

    current_user.fullname = data['fullname']
    current_user.email = data['email']
    current_user.public_email = data['public_email']
    if data['twitter'] is not None:
        current_user.twitter_handle = data['twitter'].lstrip('@')
        current_user.public_twitter = data['public_twitter']

    # If a new password was provided we update it as well
    if data['password1'] is not None and len(data['password1']):
        current_user.password = generate_password_hash(
            data['password1'])

    # Do the actual update in the database
    db.session.add(current_user)
    db.session.commit()
    return jsonify(current_user) 
Example #28
Source File: account.py    From spendb with GNU Affero General Public License v3.0 5 votes vote down vote up
def register():
    """ Perform registration of a new user """
    require.account.create()
    data = AccountRegister().deserialize(request_data())

    # Check if the username already exists, return an error if so
    if Account.by_name(data['name']):
        raise colander.Invalid(
            AccountRegister.name,
            _("Login name already exists, please choose a "
              "different one"))

    # Check if passwords match, return error if not
    if not data['password1'] == data['password2']:
        raise colander.Invalid(AccountRegister.password1,
                               _("Passwords don't match!"))

    # Create the account
    account = Account()
    account.name = data['name']
    account.fullname = data['fullname']
    account.email = data['email']
    account.public_email = data['public_email']
    account.password = generate_password_hash(data['password1'])

    db.session.add(account)
    db.session.commit()

    # Perform a login for the user
    login_user(account, remember=True)

    # Registration successful - Redirect to the front page
    return jsonify(account) 
Example #29
Source File: models.py    From Building-Serverless-Python-Web-Services-with-Zappa with MIT License 5 votes vote down vote up
def password(self, password):
        if not bool(password):
            raise ValueError('no password given')

        hashed_password = generate_password_hash(password)
        if not len(hashed_password) <= 128:
            raise ValueError('not a valid password, hash is too long')
        self.password_hash = hashed_password 
Example #30
Source File: channel_manager.py    From gdanmaku-server with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, name, desc="Test", ttl=-1, sub_passwd="",
                 pub_passwd=None, exam_passwd=None):
        self.name = name
        self.desc = desc
        self._ttl = ttl
        self.sub_passwd = generate_password_hash(sub_passwd)
        self.pub_passwd = generate_password_hash(pub_passwd) \
            if pub_passwd else None
        self.exam_passwd = generate_password_hash(exam_passwd) \
            if exam_passwd else None