def register_user_svc(new_user, **kwargs): """ Register new user service :param new_user: User query object with new variables to save as a new user. :param kwargs: :return: user query object """ user = get_user_by_email(new_user.email) if user: return None user = new_user user.password = bcrypt.generate_password_hash( new_user.password).decode("utf-8") # user = User() # user.email = kwargs["email"] # user.username = kwargs["username"] # user.first_name = kwargs["f_name"] # user.last_name = kwargs["l_name"] # user.bio = kwargs["bio"] # user.password = bcrypt.generate_password_hash(kwargs["password"]).decode("utf-8") db.session.add(user) db.session.commit() return user
def register(body): if request.is_json: username = body.get('username') email = body.get('email') password = bcrypt.generate_password_hash(body.get('password')) image_url = body.get('image_url') new_user = User(username=username, email=email, password=password.decode('utf-8'), image_url=image_url) existing_user = User.query\ .filter(User.username == username)\ .filter(User.email == email)\ .one_or_none() if existing_user is None: try: db.session.add(new_user) db.session.commit() return make_response('New user was successfully created', 201) except IntegrityError: return make_response( 'A user with the same credentials already exists', 409) else: return make_response(f'User, {username}, already exists', 409)
def __init__(self, email, password, admin=False): self.email = email self.password = bcrypt.generate_password_hash( password, app.config.get('BCRYPT_LOG_ROUNDS') ).decode() self.registered_on = datetime.datetime.now() self.admin = admin
def seed_db(): from src.models.User import User from src import bcrypt from faker import Faker import random faker = Faker() users = [] TEST_PASSWORD = current_app.config["TEST_PASSWORD"] if not TEST_PASSWORD: raise ValueError('TEST_PASSWORD not provided.') for i in range(5): # Add users user = User() user.email = f"test{i}@test.com" user.bio = faker.paragraph(nb_sentences=3) user.username = f"test{i}" user.first_name = faker.first_name() user.last_name = faker.last_name() user.password = bcrypt.generate_password_hash( f"{TEST_PASSWORD}").decode("utf-8") db.session.add(user) db.session.commit() print("Users Added") print("Tables seeded")
def post(self): args = parser.parse_args() print(args) username = args.get('username') # find if username exists results = session.query(User).filter(User.username == username) if results.count() > 0: print('user already found') raise BadRequest() return {'response': 'failure', 'reason': 'User already exists'} else: print('user not found, creating new account') password = args.get('password') pwd_hash = bcrypt.generate_password_hash(password) user = User(fname=args.get('fname'), lname=args.get( 'lname'), username=username, password=pwd_hash, email=args.get('email')) session.add(user) session.commit() return {'response': 'success'}
def __init__(self, username, password, account_type): self.username = username self.password = bcrypt.generate_password_hash( password, app.config.get("BCRYPT_LOG_ROUNDS")).decode() self.registered_on = datetime.datetime.now() self.account_type = (account_type if account_type == 1 or account_type == 2 else None)
def __init__(self, first_name, last_name, email, password): self.first_name = first_name self.last_name = last_name self.email = email self.hashed_pw = bcrypt.generate_password_hash( password, current_app.config.get("BCRYPT_LOG_ROUNDS") ).decode() self.registered_on = datetime.datetime.now()
def encrypted_password(self): """ Property Method to encrypt self.password. :return: encrypted string of self.password by 12 cycles/rounds. """ password = bcrypt.generate_password_hash(self.password, 12) return password
def __init__(self, username="", email="", password=""): self.username = username self.email = email self.password = password if password != "": self.password = bcrypt.generate_password_hash( password, current_app.config.get("BCRYPT_LOG_ROUNDS")).decode()
def encrypted_pin(self): """ Property Method to encrypt self.pin. the pin will be converted to string first. this is because integer values are not iterable :return: encrypted string of self.password by 12 cycles/rounds. 12 rounds is the default value which can be omitted on the parameters """ pin = bcrypt.generate_password_hash(str(self.pin)) return pin
def register(): form = RegisterForm() 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,contact=form.contact.data, address=form.address.data) db.session.add(user) db.session.commit() flash('Your account has been created!', 'success') return redirect(url_for('login')) return render_template('register.html', title='Sign Up', form=form)
def encode_email_token(self) -> str: """Encode the email token""" email_token = encode_jwt(sub=self.email) conf = app.config["BCRYPT_LOG_ROUNDS"] email_token_hash = bcrypt.generate_password_hash(email_token, conf) self.modify(set__email_token_hash=email_token_hash) self.save() return email_token
def register(): if current_user.is_authenticated: return redirect(url_for('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('login')) return render_template('register.html', title='Register', form=form)
def register(): 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('Account Created Successfully', 'success') return redirect(url_for('users.login')) return render_template('register.html', form=form, title='Register')
def post(self): try: json_data = UserSchema().load(request.json) except ValidationError as err: return err.messages, 422 hashed_password = bcrypt.generate_password_hash( json_data['password']).decode('utf-8') user = User(username=json_data['username'], email=json_data['email'], password=hashed_password) AuthService.register(user) return {"msg": f"You have been registered. {user.username}"}, 201
def register(): form = RegistrationForm() try: if form.validate_on_submit(): hash_password = bcrypt.generate_password_hash(form.password.data) user = User(name=form.name.data, username=form.username.data, email=form.email.data, password=hash_password, access=form.access.data) db.session.add(user) db.session.commit() flash(f'Welcome {form.name.data} Thank you for registering','success') return redirect(url_for('dashboard')) else: print(form.errors) except Exception as e: print(e) return render_template('admin/register.html', form=form, title="Registeration page")
def register(): if current_user.is_authenticated: return redirect(url_for('main.hello')) 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(f'Регистрация аккаунта {form.username.data} завершена!' 'Теперь вы можете войти в систему', 'success') return redirect(url_for('users.login')) context = {'title': 'Регистрация нового пользователя'} return render_template('register.html', context=context, form=form)
def sign_up(): form = SignUpForm() if form.validate_on_submit(): hashed_password = bcrypt.generate_password_hash( form.password.data).decode("utf-8") user = User(firstName=form.firstName.data.lower(), lastName=form.lastName.data.lower(), email=form.email.data.lower(), password=hashed_password) db.session.add(user) db.session.commit() return redirect(url_for("home")) return render_template("sign_up.html", title="Sign Up", header="Sign Up", form=form)
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 changd! Login Now', 'success') return redirect(url_for('users.login')) return render_template('reset_token.html', form=form)
def update_admin_profile(): if is_admin() is False: return register_error_handler(404, page_not_found) user = User.query.filter_by(id=current_user.id).first() print('user', user) if request.method == "POST": update_name = request.form.get('update_name') if update_name is not None: user.name = update_name flash(f"Your Name have been updated", "success") db.session.commit() return redirect(url_for('update_admin_profile')) update_email = request.form.get('update_email') if update_email is not None: user.email = update_email flash(f"Your Email have been updated", "success") db.session.commit() return redirect(url_for('update_admin_profile')) update_confirm_password = request.form.get('update_confirm_password') if update_confirm_password is not None: user.password = bcrypt.generate_password_hash( update_confirm_password) flash(f"Your Password have been updated", "success") db.session.commit() return redirect(url_for('update_admin_profile')) update_photo = request.files.get('update_photo') if update_photo: print(update_photo) try: os.unlink(os.path.join(current_app.root_path, "static/images/" + user.profile)) user.profile = photos.save( update_photo, name=secrets.token_hex(10) + ".") except: user.profile = photos.save( update_photo, name=secrets.token_hex(10) + ".") flash(f"Your Profile image been updated", "success") db.session.commit() return redirect(url_for('update_admin_profile')) return render_template('admin/update_profile.html', title="Admin Page")
def reset_token(token): if current_user.is_authenticated: return redirect(url_for('main.index')) user = User.verify_reset_token(token) if user is None: flash('Your token is either invalid or has been expired.') return redirect(url_for('users.request_reset')) form = ResetPasswordForm() if form.validate_on_submit(): hashed_password = bcrypt.generate_password_hash(form.password.data) user.password = hashed_password db.session.commit() flash('Your password has been updated', 'success') return redirect(url_for('users.login')) return render_template('reset_token.html', title='Reset Password', form=form)
def register(): if 'user' in session: return redirect(url_for('index')) register = Registration_Form() if register.validate_on_submit(): hashed_pass = bcrypt.generate_password_hash( register.password.data).decode('utf-8') usuario = {'usuario': register.username.data, 'password': hashed_pass, 'email': register.email.data, 'image': 'default.jpg', 'colaboradores': ['nada']} tabla_usuarios.insert_one(usuario) session['user'] = register.username.data session['email'] = register.email.data session['image'] = 'default.jpg' flash( f'Tu cuenta fue creada satisfactoriamente tu usuario es:{register.username.data}', 'success') return redirect(url_for('login')) return render_template('registro.html', title='Registro', form=register)
def auth_register(): user_fields = user_schema.load(request.json) user = User.query.filter_by(email=user_fields["email"]).first() if user: return abort(400, description="User already") user = User() user.email = user_fields["email"] user.password = bcrypt.generate_password_hash( user_fields["password"]).decode("utf-8") db.session.add(user) db.session.commit() return jsonify(user_schema.dump(user))
def sign_up(): if current_user.is_authenticated: return redirect(url_for('main.home')) form = SignUpForm() if form.validate_on_submit(): hashed_pw = bcrypt.generate_password_hash( form.password.data).decode('utf-8') new_user = User(username=form.username.data, email=form.email.data, password=hashed_pw) db.session.add(new_user) db.session.commit() flash( 'Your account was successfully created. You are now able to log in.', 'success') return redirect(url_for('users.login')) return render_template('users/signup.html', title='Sign Up', form=form)
def reset_token(token): if current_user.is_authenticated: return redirect(url_for('main.hello')) user = User.verify_reset_token(token) if user is None: flash('Срок действия ссылки истек') 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(f'Пароль успешно изменен! Можете войти в систему', 'success') return redirect(url_for('users.login')) context = { 'title': 'Новый пароль', 'form': form } return render_template('reset_token.html', context=context, form=form)
def get(self): args = login_parser.parse_args() print(args) username = args.get('username') password = args.get('password') pwd_hash = bcrypt.generate_password_hash(password) users = session.query(User).filter(User.username == username).all() if len(users) > 0: user = users[0] correct = bcrypt.check_password_hash(user.password, password) if correct: return {'response': 'success'} else: return {'response': 'bad password'} return {'response': 'no user found'}
def change_password(): form = ChangePasswordForm() if form.validate_on_submit(): email = form.email.data password = secrets.token_hex(6) print('email: ', email) print('password: '******'change_password.html', form=form, categories=categories())
def register_user_svc(**kwargs): """ Register new user service :param kwargs: :return: user query object """ user = get_user_by_email(kwargs["email"]) if user: return None user = User() user.email = kwargs["email"] user.username = kwargs["username"] user.f_name = kwargs["f_name"] user.l_name = kwargs["l_name"] user.bio = kwargs["bio"] user.password = bcrypt.generate_password_hash(kwargs["password"]).decode("utf-8") db.session.add(user) db.session.commit() return user
def customer_register(): form = CustomerRegisterForm() if form.validate_on_submit(): hash_password = bcrypt.generate_password_hash(form.password.data) register = Register(name=form.name.data, username=form.username.data, email=form.email.data, password=hash_password, country=form.country.data, city=form.city.data, contact=form.contact.data, address=form.address.data, zipcode=form.zipcode.data) db.session.add(register) flash(f'Thank you for signing up with us!', 'success') db.session.commit() session['email'] = False return redirect(url_for('login')) return render_template('customer/register.html', form=form, categories=categories())
def signup(): if current_user.is_authenticated: return redirect(url_for('main.home')) form = SignupForm() if form.validate_on_submit(): try: hashed_password = bcrypt.generate_password_hash( form.password.data).decode('utf-8') time = datetime.utcnow() user = User(username=form.username.data, showname=form.showname.data, email=form.email.data, password=hashed_password, created_utc=time) db.session.add(user) db.session.commit() flash('Your account has been created. Login Now', 'success') return redirect(url_for('main.home')) except Exception as e: flash(e, 'error') return render_template('users/signup.html', title='Sign Up', form=form)