我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用werkzeug.security.generate_password_hash()。
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
def add(username, password, **kwargs): """ :param username: :type username: :param password: :type password: :param kwargs: :type kwargs: :return: :rtype: """ hashed_password = generate_password_hash(password) user = User.create( username=username, password=hashed_password, **kwargs) return user
def register_view(self): form = RegistrationForm(request.form) if helpers.validate_form_on_submit(form): user = User() form.populate_obj(user) user.password = generate_password_hash(form.password.data) db.session.add(user) db.session.commit() login.login_user(user) return redirect(url_for('.index')) link = '<p>Already have an account? <a href="' \ + url_for('.login_view') + '">Click here to log in</a></p>' self._template_args['form'] = form self._template_args['link'] = link return super(AuthenticationView, self).index()
def registry(): if request.method == 'POST': user_id = Standardlib.create_uuid() username = request.form.get('username',None) password = request.form.get('password', None) email = request.form.get('email', None) try: newuser = models.User(uuid = user_id, username = username, password = generate_password_hash(password), email = email, timestamp = datetime.utcnow()) db.session.add(newuser) db.session.commit() return jsonify(result="sucessfull") except: return jsonify(result = "failed") finally: db.session.close() return redirect('login')
def change_passwd(): if session.get('login_in',None): if session.get('username',None): oldpassword = request.values['oldpassword'] newpassword = request.values['newpassword'] try: user = models.User.query.filter_by(username = session['username']).first() if check_password_hash(user.password, oldpassword): user.password = generate_password_hash(newpassword) db.session.add(user) db.session.commit() return jsonify(result="change sucessfull") else: return jsonify(result="change failed") except: db.session.rollback() return jsonify(result="change failed") finally: db.session.close() else: return redirect('/login') else: return redirect('/login')
def register(): #?????? registerform=RegisterForm() if registerform.validate_on_submit(): if User.query.filter_by(name=registerform.name.data).first(): flash("The username %s is already exist !"%registerform.name.data) return redirect(url_for('register')) elif User.query.filter_by(student_number=registerform.student_number.data).first(): flash("The student_number is already exist !") return redirect(url_for('register')) else: inset=User(classes=registerform.year.data+registerform.major.data+registerform.grade.data+"?",student_number=registerform.student_number.data,name=registerform.name.data,password=generate_password_hash(registerform.password.data),admin=0,onlineTime=0,numofSubmit=0,recentsubmitTime='Never Submittied',averageSpeed=0) db.session.add(inset) #?????generate_password_hash?????hash??????? db.session.commit() flash('????????') return redirect('/auth/login') return render_template('register.html',register=registerform)
def modifypwd(username): #???????? if username!=session.get('name'): #????????????????????? return redirect('/auth') else: form=ChangePersonalPwd() user=User.query.filter_by(name=username).first() if form.validate_on_submit(): if user is not None and check_password_hash(user.password,form.oldpassword.data): if form.newpassword.data!=form.confirmpassword.data: flash('??????????') else: user.password=generate_password_hash(form.newpassword.data) db.session.commit() flash('?????') return redirect('/auth') else: flash('??????????????') return render_template('modifypwd.html',form=form,writer=session.get('name'))
def create(): """ ???? :return: """ username = request.values.get("username") password = request.values.get("password") email = request.values.get("email") gender = int(request.values.get("gender")) password_hash = generate_password_hash(password, method='pbkdf2:sha1', salt_length=8) user = User(username=username, password_hash=password_hash, email=email, gender=gender) user.save() return success()
def register_post(): try: if request.form["password"] != request.form["password2"]: flash("Your password and password verification didn't match.", "danger") return redirect(url_for("register_get")) if len(request.form["password"]) < 8: flash("Your password needs to be at least 8 characters", "danger") return redirect(url_for("register_get")) user = User(name=request.form["username"], password=generate_password_hash(request.form["password"]), email=request.form["email"]) session.add(user) allusers = session.query(User).all() for users in allusers: session.add(user.follow(users)) session.add(users.follow(user)) session.commit() flash("User successfully registered", "success") login_user(user) return redirect(request.args.get("next") or url_for("entries")) except IntegrityError: flash("The username or email was already taken." + " Maybe you need to reset your password (below)?", "danger") session.rollback() return redirect(url_for("register_get"))
def pwreset_post(id): if request.form["password"] != request.form["password2"]: flash("Your password and password verification didn't match.", "danger") return redirect(url_for("pwreset_get", id = id)) if len(request.form["password"]) < 8: flash("Your password needs to be at least 8 characters", "danger") return redirect(url_for("pwreset_get", id = id)) user_reset = session.query(PWReset).filter_by(reset_key=id).one() #session.query(User).filter_by(id=user_reset.user.id).one() #gi(user_reset.user_id, "PRINTING ID") try: session.query(User).filter_by(id = user_reset.user_id).update({'password': generate_password_hash(request.form["password"])}) session.commit() except IntegrityError: flash("Something went wrong", "danger") session.rollback() return redirect(url_for("entries")) user_reset.has_activated = True session.commit() flash("Your new password is saved.", "success") #login_user(user) return redirect(url_for("entries"))
def password(self, password): self.password_hash = generate_password_hash(password)
def set_password(self, password): self.pw_hash = generate_password_hash(password)
def hashing_werkzeug(password): hashpw = generate_password_hash(password) return hashpw
def password(self,rawpwd): self._password = generate_password_hash(rawpwd)
def encrypt_password(): """ Verify if the route is for password reset or user create, then encrypts the password. """ if request.json is None or not 'password' in request.json: return if str(request.url_rule) == '/auth/user/' and request.method == 'POST' \ or str(request.url_rule) == '/auth/user/resetpassword/' and request.method == 'PUT': request.json['password'] = generate_password_hash(request.json['password'])
def create_user(**data): if 'username' not in data or 'password' not in data: raise ValueError('username and password are required.') data['_id'] = data['username'] data['password'] = generate_password_hash( data.pop('password'), method='pbkdf2:sha256' ) # current_app.db.users.insert_one(data) current_app.db.insert('users', data) return data
def upsert_user(username: str, password: str=None, scope: dict=None): filter = {'username': username} set = {} if password is not None: set['password_hash'] = generate_password_hash(password) if scope is not None: set['scope'] = UserJWT.validate_scope(scope) return UsersCollection().find_one_and_update(filter, {'$set': set}, {'_id': False, 'password_hash': False}, return_document=ReturnDocument.AFTER, upsert=True)
def initialize(): from werkzeug.security import generate_password_hash import mongo def create_rabbit_init_user(username, password): number_of_tries = 100 while number_of_tries: try: number_of_tries -= 1 user.update_rabbitmq_user(username, password) break except urllib.error.URLError: sleep(5) else: raise Exception() mongo.ZimfarmDatabase().initialize() users = mongo.UsersCollection() if users.find_one() is None: username = getenv('INIT_USERNAME', 'admin') password = getenv('INIT_PASSWORD', 'admin_pass') users.insert_one({ 'username': username, 'password_hash': generate_password_hash(password), 'scope': {'admin': True} }) create_rabbit_init_user(username, password)
def password(self,password): self.password_hash=generate_password_hash(password)
def password(self, password): self._password = generate_password_hash( password, method='pbkdf2:sha512:100001', salt_length=32 )
def password(self, password): """Set password. """ self.password_hash = generate_password_hash(password)
def __setattr__(self, key, value): if key == "password": if not value or len(value) == 0: return value = str(generate_password_hash(value)) super(User, self).__setattr__(key, value)
def set_password(self, password): self.password = generate_password_hash(password)
def _set_password(self, password): """Generates a password hash for the provided password.""" if not password: return self._password = generate_password_hash(password) # Hide password encryption by exposing password field only.
def serialize(self, value): if is_password_hash(value): return value return generate_password_hash(value)
def create_user(name,password,email): if name is None: name = raw_input('?????(??admin):') or 'admin' if password is None: password = generate_password_hash(getpass('??:')) if email is None: email=raw_input('Email??:') user = User(name=name,password=password,email=email) db.session.add(user) db.session.commit() print u"???????!"
def changepassword(newpassword): name = raw_input(u'?????:') thisuser = User.query.filter_by(name=name).first() if not thisuser: print u"?????,????????!" name = raw_input(u'?????:') thisuser = User.query.filter_by(name=name).first() if newpassword is None: newpassword = generate_password_hash(getpass(u'???:')) thisuser.password=newpassword db.session.add(thisuser) db.session.commit() print u"?????,??????!"
def register(): if 'username' in session: if session['username'] != "admin": return jsonify(status_error_permission_denied) else: if request.method == 'POST': if Users.query.filter_by(USERNAME=request.form['username']).first() is not None: return jsonify(status_error_already_existed_username) else: user = Users(request.form['username'], generate_password_hash(request.form['password']), request.form['phone_number'], request.form['address']) try: db.session.add(user) db.session.commit() except: return jsonify(status_error_unknown_error) else: return redirect(url_for('index')) else: return jsonify(status_error_permission_denied) return render_template("user/register.html")
def admin(): user = Users.query.filter_by(USERNAME='admin').first() user.USERNAME = "admin" user.PASSWORD = generate_password_hash("james1") db.session.add(user) db.session.commit() return "????"
def user_edit(): if 'username' in session: if session['username'] != "admin": return jsonify(status_error_permission_denied) else: if request.method == "POST": if Users.query.filter_by(ID_USER=request.form['id_user']).first() is None: return jsonify(status_error_does_not_exist_username) else: user = Users.query.filter_by(ID_USER=request.form['id_user']).first() user.USERNAME = request.form['username'] user.PASSWORD = generate_password_hash(request.form['password']) user.MOBILE_NUMBER = request.form['phone_number'] user.ADDRESS = request.form['address'] try: db.session.add(user) db.session.commit() except: return jsonify(status_error_unknown_error) else: return jsonify(status_ok_edit_successfully) else: return jsonify(status_error_permission_denied) return render_template('user/user_edit.html')
def user_password_change(): if 'username' in session: if session['username'] != "admin": if request.method == "POST": if Users.query.filter_by(USERNAME=session['username']).first() is None: return jsonify(status_error_does_not_exist_username) else: user = Users.query.filter_by(USERNAME=session['username']).first() if check_password_hash(user.PASSWORD, request.form['password']) is False: return jsonify(status_error_wrong_username_or_password) else: user.PASSWORD = generate_password_hash(request.form['password_new']) try: db.session.add(user) db.session.commit() except: return jsonify(status_error_unknown_error) else: return jsonify(status_ok_edit_successfully) else: return render_template('user/user_change_password.html') else: if request.method == "POST": if Users.query.filter_by(ID_USER=request.form['id_user']).first() is None: return jsonify(status_error_does_not_exist_username) else: user = Users.query.filter_by(ID_USER=request.form['id_user']).first() user.PASSWORD = generate_password_hash(request.form['password_new']) try: db.session.add(user) db.session.commit() except: return jsonify(status_error_unknown_error) else: return jsonify(status_ok_edit_successfully) else: return render_template('user/user_change_password_admin.html') else: return jsonify(status_error_permission_denied)
def raw_password(self, password): """ ?? setter,????????????? :param password: ??????? :return: """ self.password = generate_password_hash(password) # mongo.db.users.update_one({ # 'user_id': self.user_id # }, { # '$set': { # 'password': self.password # } # })
def add_user(**kwargs): """ ??????? :param kwargs: ??????? :return: ?????? True,???? False """ if 'name' not in kwargs or 'email' not in kwargs or 'password' not in kwargs: return False # ?????? user = mongo.db.users.find_one({'$or': [{'name': kwargs['name']}, {'email': kwargs['email']}]}) if user: return False # ????????? kwargs['user_id'] = get_next_sequence('user_id') if 'nickname' not in kwargs: kwargs['nickname'] = kwargs['name'] # ??????????? kwargs['password'] = generate_password_hash(str(kwargs['password'])) if not mongo.db.users.find_one(): kwargs['role_id'] = 1 # ?????????? else: kwargs['role_id'] = 3 # ???????????,??????,?????????????????????? kwargs['avatar_hash'] = hashlib.md5(kwargs['email'].encode('utf-8')).hexdigest() kwargs['status'] = 'active' kwargs['confirmed'] = 0 kwargs['create_at'] = int(time.time()) kwargs['update_at'] = int(time.time()) try: result = mongo.db.users.insert_one(kwargs) return User(_id=result.inserted_id) except: return False
def set_password(self, password): self.password_hash = generate_password_hash(password)
def password(self,password) : self.password_hash = generate_password_hash(password)
def change_password(user, password): user.update_value('pwd_hash', generate_password_hash(password)) user.update_value('auth_token', auth_token(user))
def _set_password(self, plaintext): self._password = generate_password_hash(plaintext)
def password(self,password): self.password_hash = generate_password_hash(password)