def __init__(self, email, firstname, lastname, password): super().__init__() self.email = email self.password = bcrypt.generate_password_hash(password) self.firstname = firstname self.lastname = lastname
def _generate_password(cls, password, salt): """ Hash password using bcrypt. A standard defined. """ password_salt = password + salt return bcrypt.generate_password_hash( password_salt, rounds=current_app.config.get('BCRYPT_ROUNDS'))
def set_password(self, password): """ Set's a user's password to a hashed version of their desired password :param password: User's password :type password: str """ self.password = bcrypt.generate_password_hash(password)
def _register_user(): json_data = request.get_json() if not json_data: return jsonify({'message': 'No input data provided'}), 400 try: user_schema.load(json_data) except ValidationError as err: return jsonify(err.messages), 422 duplicateuser = User.query.filter_by( email=json_data['email'].lower()).first() if duplicateuser: return jsonify({'message': 'Duplicate user'}), 400 user = User(username=json_data['username'].lower(), email=json_data['email'].lower(), firstname=json_data['firstname'].lower(), lastname=json_data['lastname'].lower(), password=bcrypt.generate_password_hash(json_data['password']), school=json_data['school'].lower()) user.is_teacher = json_data['is_teacher'] db.session.add(user) db.session.commit() return jsonify(message="Successful user creation", username=user.username)
def set_password(password): """ 生成hash序列 :param password: :return: """ return bcrypt.generate_password_hash(password).decode('utf-8')
def __init__(self, email, firstname, lastname, password): super().__init__() self.created_at = datetime.utcnow() self.email = email self.password = bcrypt.generate_password_hash(password) self.firstname = firstname self.lastname = lastname
def UserSeeder(): user = User(uuid=uuid.uuid4(), name="Test", email="*****@*****.**", password=bcrypt.generate_password_hash('test').decode('utf-8')) db.session.add(user) for _ in range(9): user = User( uuid=uuid.uuid4(), name=fake.name(), email=fake.email(), password=bcrypt.generate_password_hash('test').decode('utf-8')) db.session.add(user) db.session.commit()
def __init__(self, password, user_uuid=None, created_at=datetime.datetime.utcnow()): """Initialize MetaGenScope User model.""" if user_uuid: self.user_uuid = user_uuid self.password = bcrypt.generate_password_hash( password, current_app.config.get('BCRYPT_LOG_ROUNDS')).decode() self.created_at = created_at
def password(self, value): """ Hash password when setter is triggered and generate new secret key. :param value: Raw password """ # Generate password hash self._password = bcrypt.generate_password_hash(value) # Generate secret key on password change self.secret_key = generate_secret_key()
def __init__(self, username, email, password, created_at=datetime.datetime.utcnow()): """Initialize MetaGenScope User model.""" self.username = username self.email = email self.password = bcrypt.generate_password_hash( password, current_app.config.get('BCRYPT_LOG_ROUNDS')).decode() self.created_at = created_at
def register(): form = RegisterForm() if (form.validate_on_submit()): new_account = User() new_account.fullname = form.name.data new_account.username = form.username.data new_account.password = bcrypt.generate_password_hash( form.password.data).decode('utf-8') db.session.add(new_account) db.session.commit() return 'account made' return render_template('register.html', form=form)
def register(): if current_user.is_authenticated: return redirect(url_for('main.home')) form = RegisterForm() if request.method == "POST": if form.validate_on_submit(): hashed_password = bcrypt.generate_password_hash( form.password.data).decode('utf-8') user = User(email=form.email.data, password_hash=hashed_password) user.add_user_to_db() flash(f'User {form.email.data} has been registered!', category='info') return redirect(url_for('auth.login')) return render_template('register.html', form=form)
def user_submit(form, user_id=None): if user_id: user = u.User() else: user = u.CreateUserRequest() user.name = form.name.data user.email = form.email.data user.password = bcrypt.generate_password_hash(form.password.data).decode('utf-8') if user_id: new_user = users.UpdateUser(u.UpdateUserRequest(_id=user_id, user=user)) else: new_user = users.CreateUser(user) return redirect('/user/{}'.format(new_user._id))
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(): hashed_password = bcrypt.generate_password_hash(form.password.data).decode('utf-8') user.password = hashed_password 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)
def register(): if current_user.is_authenticated: return redirect(url_for('main.home')) form = RegistrationForm() if form.validate_on_submit(): hashed_password = bcrypt.generate_password_hash( form.password.data).decode('utf-8') user = User(username=form.username.data, email=form.email.data, password=hashed_password) db.session.add(user) db.session.commit() flash('Your account has been created! You are now able to log in', 'success') return redirect(url_for('users.login')) return render_template('register.html', title='Register', form=form)
def _change_password(): json_data = request.get_json() if not json_data: return jsonify({'message': 'No input data provided'}), 400 current_user = get_jwt_identity() if current_user: user = User.query.filter_by(username=current_user).first() password = bcrypt.generate_password_hash(json_data['password']) user.password = password db.session.commit() return jsonify(message="Change password successful"), 200 return jsonify({'message': "Invalid Token"}), 401
def reset_password(token=None): token = request.args.get('token') or None if token is not None: user = User.query.filter_by(reset_password_token=token).first() if user is not None: form = ResetPasswordForm() if form.validate_on_submit(): user.password = bcrypt.generate_password_hash( form.password.data).decode('utf-8') user.reset_password_token = None db.session.commit() flash("Password Changed") return redirect(url_for('public.index')) return render_template('reset-password.html', form=form, username=user.username) flash('Token not found, please request new token') return redirect(url_for('public.index')) return 'no token'
def _post_index(self, username: str, password: str): user = user_data_store.find_user(username=username) if user is not None: raise Conflict(description='用户名冲突') else: try: user = user_data_store.create_user( username=username, pw_hash=bcrypt.generate_password_hash(password).decode('utf-8'), roles=[RoleContainer.get_member()] ) user_data_store.commit() return { 'id': user.id, 'user': user.username } except Exception as ex: db.session.rollback() logger.error(ex) abort(500)
def register(): # If user already is logged in return to home page if current_user.is_authenticated: return redirect(url_for('main.home')) form = RegistrationForm() # Initialize Registration FOrm and pass it to html template # Ths will check if it is a POST request and if it is valid. if form.validate_on_submit(): # Create User Object (account) and save to Database # Before saving user details, password should be hashed hashed_password = bcrypt.generate_password_hash(form.password.data).decode('utf-8') # UTF-8 makes the hash string instead of bytes newUser = User(username=form.username.data, email=form.email.data, password=hashed_password) db.session.add(newUser) db.session.commit() flash(f'Account created, you can now log in!', 'success') return redirect(url_for('users.login')) return render_template('register.html', title='Register', form=form)
def set_password(self, password: str) -> None: """Set password.""" self.password = bcrypt.generate_password_hash(password)
def update_user(): """Updates the data of a user only if the user making the request is an admin .. :quickref: User; Update a user. **Example request**: .. sourcecode:: http PUT /api/user HTTP/1.1 Host: localhost Accept: application/json Content-Type: application/json { "admin_username": 1, "username": "******", "f_name": "John", "l_name": "Doe", "email": "*****@*****.**", "password": "******", "confirm_password": "******", "role": 2, } **Example response**: .. sourcecode:: http HTTP/1.1 200 OK Content-Type: application/json { "message": "Success" } .. sourcecode:: http HTTP/1.1 401 UNAUTHORIZED Content-Type: application/json { "message": { "user": ["User is not an admin."] } } :<json string admin_username: the username of the person updating the user :<json string username: the updated username of the user :<json string f_name: the updated first name of the user :<json string l_name: the updated last name of the user :<json string email: the updated email of the user :<json string password: the updated password of the user, optional :<json string confirm_password: field that must match the original password, optional :<json int role: the cost_per_hour of the car being updated :>json message: repsonse information such as error information :resheader Content-Type: application/json :status 200: updating user was successful :status 400: missing or invalid fields :status 401: user is not an admin """ response = { 'message': '', } status = 200 form_schema = UpdateUserFormSchema() form_errors = form_schema.validate(request.json) if form_errors: response['message'] = form_errors status = 400 else: # Checking if user making the request is an admin admin_user = User.query.get(request.json["admin_username"]) if admin_user.role is not Role.admin: response['message'] = { 'user': ['User is not an admin.'] } status = 401 else: user = User.query.get(request.json["username"]) user.username = request.json["username"] user.f_name = request.json["f_name"] user.l_name = request.json["l_name"] user.email = request.json["email"] user.role = Role(int(request.json["role"])) if "password" in request.json: password = request.json["password"] hashed_password = bcrypt.generate_password_hash(password) user.password = hashed_password db.session.commit() response['message'] = "Success" return response, status
def register_user(): """Creates a user account that does not already exist .. :quickref: User; Create new user. **Example request**: .. sourcecode:: http POST /api/user HTTP/1.1 Host: localhost Accept: application/json Content-Type: application/json { "username": "******", "f_name": "John", "l_name": "Doe", "email": "*****@*****.**", "password": "******", "confirm_password": "******" } **Example response**: .. sourcecode:: http HTTP/1.1 200 OK Content-Type: application/json { "message": "Registered user successfully", "user": { "username": "******" } } .. sourcecode:: http HTTP/1.1 400 BAD REQUEST Content-Type: application/json { "message": "Passwords do not match", "user": null } :<json string username: username that does not already exist within the database :<json string f_name: first name of the user :<json string l_name: last name of the user :<json string email: email of the user (in the correct format) :<json string password: password for new accoutn :<json string confirm_password: retyped password which should match the previous password value :>json message: repsonse information such as error information :>json app.models.user.User user: the user object that has been created :resheader Content-Type: application/json :status 200: successful registration :status 400: malformed request """ response = { 'message': '', 'user': None } status = 200 # Checking that form data is correct form_schema = RegisterFormSchema() form_errors = form_schema.validate(request.json) if form_errors: response['message'] = form_errors status = 400 else: username = request.json["username"] f_name = request.json["f_name"] l_name = request.json["l_name"] email = request.json["email"] password = request.json["password"] # Checking that user is not already in the system if User.query.get(username) is not None: response['message'] = { 'user': ['User already exists.'] } status = 400 else: # Hashing password using brcypt's one-way encryption hashed_password = bcrypt.generate_password_hash(password) # Creating user and adding to the database new_user = User(username, hashed_password, f_name, l_name, email) db.session.add(new_user) db.session.commit() response['message'] = "Success" response['user'] = user_schema.dump(new_user) return response, status
def check_password(self, value): return bcrypt.generate_password_hash(self.password, len(value))
def set_password(self, password): self.pw_hash = bcrypt.generate_password_hash(password, 10)
def set_password(self, password): hash_ = bcrypt.generate_password_hash(password, 10).decode('utf-8') self.pw_hash = hash_
def password(self, password): self._password = bcrypt.generate_password_hash(password, rounds=8)
def _set_password(self, plaintext): self._password = bcrypt.generate_password_hash(plaintext)
def set_password(self, password): self.passwd = bcrypt.generate_password_hash(password)
def on_before_insert_usuario(mapper, connection, target): target.senha = bcrypt.generate_password_hash(target.senha).decode('utf-8')
def __init__(self, name, email, password: str): self.name = name.strip().title() self.email = email.lower() self.password = bcrypt.generate_password_hash(password).decode("utf-8")
def set_password(self, password): self.password = bcrypt.generate_password_hash(password).decode("utf-8")
def set_password(self, password): """Set password.""" self.password = bcrypt.generate_password_hash(password)
def set_password(self, password): """Convert the password to cryptograph via flask-bcrypt""" return bcrypt.generate_password_hash(password)