def init_test_db(cursor, username, email): secondary_email = '*****@*****.**' init_sql = f''' DROP DATABASE IF EXISTS {TestConfig.MYSQL_DATABASE_DB}; CREATE DATABASE {TestConfig.MYSQL_DATABASE_DB}; USE {TestConfig.MYSQL_DATABASE_DB}; ''' commands = read_sql('../scripts/db_setup.sql', init_sql) for command in commands: cursor.execute(command) pw = bcrypt.generate_password_hash('test') sql = "INSERT INTO user (username, password) " \ "VALUES (%s, %s)" cursor.execute(sql, (username, pw)) new_user_id = cursor.lastrowid sql = "INSERT INTO email (address, user_id) " \ f"VALUES (%s, %s)" cursor.executemany(sql, [(email, new_user_id), (secondary_email, new_user_id)]) new_email_id = cursor.lastrowid sql = 'INSERT INTO user_primary_email (user_id, email_id) ' \ 'VALUES (%s, %s)' cursor.execute(sql, (new_user_id, new_email_id)) return new_user_id
def get_hashed_passes_csv(input_path, output_path): """ Generate the hashed passwords from a csv file and save it to an output file. :param input_path: path to a csv that contains two columns. first being the email and second being the plaintext password. :param output_path: path to a csv that will contain two columns. first being the email and second being the hashed password. :return: """ with open(input_path) as input_file: csv_reader = csv.reader(input_file) num_rows = len(list(csv_reader)) input_file.seek(0) with open(output_path, 'w', newline='') as output_file: csv_writer = csv.writer(output_file, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL) for row in tqdm(csv_reader, total=num_rows): email, password = row password = bcrypt.generate_password_hash(password).decode() csv_writer.writerow([email, password])
def post(self): args = register_parser.parse_args() failed_msg = validate_registration(args) if failed_msg: return {'message': failed_msg}, 422 new_username = args['username'].lower() new_email = args['email'].lower() try: cursor = mysql.get_db().cursor() username = username_exists(cursor, new_username) email = email_exists(cursor, new_email) except OperationalError as e: return error_resp(e) if username or email: return { 'message': f'{"username " if username else "email "}' 'already exist' }, 409 pwd_hash = bcrypt.generate_password_hash( args['password'].encode('utf-8')) try: sql = ''' INSERT INTO user (username, password) VALUES (%s, %s) ''' cursor.execute(sql, (new_username, pwd_hash)) new_user_id = cursor.lastrowid sql = ''' INSERT INTO email (address, user_id) VALUES (%s, %s) ''' cursor.execute(sql, (new_email, new_user_id)) new_email_id = cursor.lastrowid sql = ''' INSERT INTO user_primary_email (user_id, email_id) VALUES (%s, %s) ''' cursor.execute(sql, (new_user_id, new_email_id)) mysql.get_db().commit() except OperationalError as e: return error_resp(e) mail_disabled = True # disable mail sending if not mail_disabled: email = '*****@*****.**' # temporary recipient token = generate_email_token(email) url = request.url_root + f'confirm-email/{token}' send_confirmation_email(url, email) return { 'message': f'user {new_username} registered', 'username': new_username, 'email': new_email }
def forgot_password(): form = ForgotPasswordForm() if form.validate_on_submit(): email = form.email.data value = user_account.query.by(email_address=email).first() if value: token = ''.join(random.choice(string.ascii_uppercase + string.digits)for _ in range(6)) value.password = bcrypt.generate_password_hash(token).decode('utf-8') db.session.commit() html = 'asdf' subject = 'RESET PASSWORD: '******'Password has been reset. Please check your email.', 'success') return redirect(url_for('unregistered.forgot_password')) else: flash('Email not existing.', 'error') return render_template('/unregistered/login/forgot_password.html', form=form)
def profile_settings_password(user): user_account_update = user_account.profile_acc_update(current_user.info_id) form = PasswordUpdateForm() if form.validate_on_submit(): user = user_account.login( [current_user.username, form.oldpassword.data]) if user: user_account_update.password = bcrypt.generate_password_hash( form.password.data).decode('utf-8') db.session.commit() flash('Password was successfully updated!', 'success') return redirect( url_for('linkages.profile_settings_password', user=current_user.username)) else: flash('Wrong password.', 'error') return render_template('/linkages/profile/settings/password.html', title="Linkages", form=form)
def staff_add(): if request.method == 'POST': from ..main.models import sendmail data = request.json first_name = data['first_name'] last_name = data['last_name'] address = data['address'] phone = data['phone'] email = data['email'] salary = data['salary'] staff_id = data['staff_id'] rights = data['rights'] warehouse = data['warehouse'] notes = data['notes'] pw_raw = token_hex(4) pw_hashed = bcrypt.generate_password_hash(pw_raw) user_1 = User(company_id=current_user.company_id, email=email, first_name=first_name, last_name=last_name, password=pw_hashed, rights=rights) db.session.add(user_1) db.session.flush() staff_1 = Staff(company_id=current_user.company_id, user_id=user_1.id, salary=salary, staff_id=staff_id, address=address, phone=phone, warehouse_id=warehouse, notes=notes) db.session.add(staff_1) db.session.commit() mail_subject = f'{current_user.company.name} Staff Registration.' mail_msg =\ f'''Hi {first_name} {last_name},\n { current_user.company.name} has added you as employee.\n You password is {pw_raw}\n Please keep your password confidential. To login go to https://necommerce.online/login/''' sendmail(email, mail_subject, mail_msg) return jsonify({ 'status': True, 'message': f'Staff {first_name} added successfully. Password is send to the staff email address.' }) last_staff = Staff.query.with_entities(Staff.staff_id, Staff.salary).\ filter_by(company_id=current_user.company_id).order_by(Staff.staff_id.desc()).first() warehouses = current_user.company.warehouse.all() return render_template('people/add_staff.html', last_staff=last_staff, warehouses=warehouses)
def staff_edit(staff_id): staff_1 = User.query.get_or_404(staff_id) if request.method == 'POST': return render_template('people/edit_staff.html', data=staff_1) if request.method == 'PUT': if not staff_1.company_id == current_user.company_id and not current_user.rights >= 4: abort(403) action = 'edited' data = request.json first_name = data['first_name'] last_name = data['last_name'] address = data['address'] phone = data['phone'] email = data['email'] salary = data['salary'] staff_id = data['staff_id'] rights = data['rights'] warehouse = data['warehouse'] notes = data['notes'] pw_raw = token_hex(4) pw_hashed = bcrypt.generate_password_hash(pw_raw) first_name = first_name last_name = last_name address = address phone = phone email = email salary = salary staff_id = staff_id rights = rights warehouse = warehouse notes = notes pw_raw = token_hex(4) pw_hashed = bcrypt.generate_password_hash(pw_raw) if request.method == 'DELETE': action = 'deleted' db.session.delete(staff_1) db.session.commit() return jsonify({ 'status': True, 'message': f'{staff_1.name} {action} successfully.' })
def add_item(cls, item): try: with cls.get_db().atomic(): return User.create(name=item.get("Name"), login=item.get("Login"), password=bcrypt.generate_password_hash( item.get("Password")), role=item.get("Role")).id except IntegrityError: return 0 except ValueError: return -1
def signup_user(): """ Checks if Email already exists in database otherwise, creates an account for the User :param email: :param name: :param password: :param phone_no: :return: """ req = request.get_json() req['password'] = bcrypt.generate_password_hash(req['password']) user_exists = db.session \ .query(User.query.filter(User.email == req['email']).exists()) \ .scalar() if user_exists: return Error("User exists", 400)() del req['captcha_token'] user = User(**req) db.session.add(user) serializer = URLSafeSerializer(app.config['SECRET_KEY']) activation_token = serializer.dumps(user.email) activation_url = url_for('User.activate_user', activation_token=activation_token, _external=True) db.session.commit() # if mautic works , then we will deleted this code block # Mail(req['email'], # subject_data={'name': req['full_name']}, # html_data={'token': activation_url}, # text_data={'name': req['full_name']}, # template_root=SIGNUP_ACTIVATION # ).send() add_user_to_mautic.delay(req['full_name'], req['email'], req['phone_no'], user.created_date, user.referral_code_used, user.graduation_date, user.branch, user.degree, activation_url=activation_url) return ""
def add(value): record = user_account(id=value[0], info_id=value[1], username=value[2], password=bcrypt.generate_password_hash( value[3]).decode('utf-8'), email_address=value[4], type=value[5], last_active=value[6], status=value[7]) db.session.add(record) db.session.commit()
def mutate(root, info, first_name, last_name, email, password): new_user = UserModel( first_name=first_name, last_name=last_name, email=email, password=str( bcrypt.generate_password_hash(password), 'utf-8' ) ) session.add(new_user) session.commit() ok = True return createUser(ok=ok, user=new_user)
def register(self, db, login, password): cursor = db.cursor() sql = ''' INSERT INTO dev.admin (admin_login, password) SELECT * FROM (SELECT %s, %s) as tmp WHERE NOT EXISTS(SELECT * FROM dev.admin WHERE admin_login = %s); ''' hash_pw = bcrypt.generate_password_hash(password.encode('utf-8')) try: rows = cursor.execute(sql, (login, hash_pw, login)) if not rows: return {'message': 'admin already exist'}, 400 db.commit() except OperationalError as e: print(e) return abort(500) return {'message': 'admin registered', 'login_id': login}
def signup_post(): email = request.form.get('email') name = request.form.get('name') password = request.form.get('password') user = User.query.filter_by(email=email).first() if user: # if a user is found, ask user try to sign up again flash('Email address already exists') return redirect(url_for('auth.signup')) # create new user with the form data. Hash the password so plaintext version isn't saved. pwhash = bcrypt.generate_password_hash(password) new_user = User(email=email, name=name, password=pwhash.decode('utf8')) # add the new user to the database db.session.add(new_user) db.session.commit() return redirect(url_for('auth.login'))
def signup(): if current_user.is_authenticated: flash('You\'re already signed up', 'info') return redirect(url_for('base.index')) form = SignupForm() if form.validate_on_submit(): user = User() form.password.data = bcrypt.generate_password_hash( form.password.data).decode('utf-8') form.populate_obj(user) db.session.add(user) db.session.commit() flash('You have successfully sign up. Please sign in now', 'success') return redirect(url_for('user.login')) render_vars = {'page_name': 'Signup', 'form': form} return render_template('user/signup.html', **render_vars)
def change_password(): """ Allows User to change Password after validating the Old Password. User must be logged in to be able to do this. :return: 403 if old password doesn't match, 400 if any error, else 200 """ req = request.get_json() try: user = User.query \ .filter(User.id == current_user.id) \ .filter(User.is_active) \ .one() if bcrypt.check_password_hash(user.password, req['old_password']): user.password = bcrypt.generate_password_hash(req['new_password']) db.session.commit() return "" return Error('Invalid Old Password', 403) except NoResultFound: return Error('Invalid User', 400)()
def post(self): args = parser.parse_args() print("args", args) first_name = args['first_name'] last_name = args['last_name'] email = args['email'] password = bcrypt.generate_password_hash( args['password']).decode('utf-8') created = datetime.utcnow() user = User(first_name=first_name, last_name=last_name, email=email, password=password) db.session.add(user) try: db.session.commit() result = { 'first_name': first_name, 'last_name': last_name, 'email': email, 'password': password, 'created': created } return jsonify({ 'action': 'registering user', 'status': 'success', 'result': result }) except IntegrityError: return jsonify({ 'action': 'registering user', 'status': 'failed', 'result': 'user already exists' })
def reset_password(reset_token): """ Validates Reset Token and Updates the Password in the Database :param reset_token: :return: 403 if any errors, else return 200 """ req = request.get_json() serializer = URLSafeSerializer(app.config['SECRET_KEY']) try: email = serializer.loads(reset_token) user = User.query \ .filter(User.email == email) \ .filter(User.is_active) \ .one() user.password = bcrypt.generate_password_hash(req['new_password']) db.session.commit() return "" except NoResultFound: return Error('Invalid Reset Token', 403)()
def change_password(db, user_id, new_pwd): """ Change user's current password :param db: :param user_id: :param new_pwd: :return: Response Object """ cursor = db.cursor() sql = ''' UPDATE user SET password = %s WHERE id = %s ''' pwd_hash = bcrypt.generate_password_hash(new_pwd.encode('utf-8')) try: cursor.execute(sql, (pwd_hash, user_id)) db.commit() except OperationalError as e: print(e) return abort(500) return make_response({'message': 'password updated'})
def registration(): if request.method == "POST": username = request.form.get("username") email = request.form.get("email") password = request.form.get("password") repeat = request.form.get("repeat") # check email valid is_valid = check_email(email) if not is_valid: flash("Email is not a valid email", "warning") return redirect(url_for("user.registration")) if password != repeat: flash("Password and repeat did not match!", "warning") return redirect(url_for("user.registration")) # check if email is already taken: user = User.query.filter_by(email=email).first() if user: flash("Email is already taken", "warning") return redirect(url_for("user.registration")) # check if username is already taken in Database! user = User.query.filter_by(username=username).first() if user: flash("Username is already taken", "warning") return redirect(url_for('user.registration')) password_hash = bcrypt.generate_password_hash(password).decode('utf-8') session_cookie = str(uuid.uuid4()) session_expiry_datetime = datetime.datetime.now() + datetime.timedelta( seconds=COOKIE_DURATION) user = User(username=username, email=email, password_hash=password_hash, session_cookie=session_cookie, session_expiry_datetime=session_expiry_datetime) db.session.add(user) db.session.commit() flash("Registration Successful!", "success") # send registration confirmation email msg = Message(subject="WebDev Blog - Registration Successful", sender=SENDER, recipients=[email], bcc=[SENDER]) msg.body = f"Hi {username}!\n" \ f"Welcome to our WebDev Flask site!\n" \ f"Visit us: {HOST_ADDR}\n" \ f"Enjoy!" mail.send(msg) # set cookie for the browser response = make_response(redirect(url_for('main.index'))) response.set_cookie(WEBSITE_LOGIN_COOKIE_NAME, session_cookie, httponly=True, samesite='Strict') return response elif request.method == "GET": return render_template("registration.html", user=request.user, active0="active")
def set_password(self, password): """Set password.""" self.password = bcrypt.generate_password_hash(password)
def password(self, password): self._password = bcrypt.generate_password_hash(password)
def user_seeder(): mongo.db.sequences.delete_one({'_id': 'users'}) mongo.db.sequences.delete_one({'_id': 'user_articles'}) mongo.db.users.delete_many({}) seeds = [] try: for number in range(seed_length): if number == 0: seeds.append({ 'first_name': 'Jonathan', 'last_name': 'Sugianto', 'gender': 'M', 'date_of_birth': datetime(1999, 11, 1), 'email': '*****@*****.**', 'username': '******', 'password': bcrypt.generate_password_hash('kusogaki'), 'img_url': default_img, 'joined_at': datetime.now(), 'is_admin': False, 'is_active': True }) else: seeds.append({ 'first_name': fake.first_name(), 'last_name': fake.last_name(), 'gender': random.choice(['M', 'F']), 'date_of_birth': fake.date_time_between_dates( datetime(1980, 1, 1, 0, 0, 0, 0), datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)), 'email': fake.email(), 'username': fake.profile()['username'], 'password': bcrypt.generate_password_hash('seeding-password'), 'img_url': default_img, 'joined_at': fake.date_time_between_dates(datetime(2017, 1, 1), datetime.now()), 'is_admin': False, 'is_active': fake.boolean() }) result = mongo.db.users.insert_many(seeds) if len(result.inserted_ids) == 0: print('Seeding users collection failed...') return sequence_seed = mongo.db.sequences.insert_one({ '_id': 'users', 'value': seed_length }) if sequence_seed.inserted_id is None: print('Seeding users sequences collection failed...') return print('Seeding users collection succeed...') except Exception as ex: print('Seeding users collection failed...') print('error: ', ex)
def set_pasword(self, password): encryptPassword = bcrypt.generate_password_hash(password) self.password = encryptPassword print(encryptPassword) return encryptPassword
def set_password(self, password): return bcrypt.generate_password_hash(password)
def set_password(self, password): self.password = bcrypt.generate_password_hash(password).decode('utf-8')
def password(self, plaintext): self._password = bcrypt.generate_password_hash(plaintext)
def mutate(self, info, _id, fields, img_upload): if ObjectId.is_valid(_id) is False: return UpdateUser( updated_user= None, response= ResponseMessage(text= 'Format Id tidak sesuai, pengguna gagal diperbarui', status= False) ) if validate_datetime(fields['date_of_birth'], 'date') is False: return UpdateUser( updated_user= None, response= ResponseMessage(text= 'Format tanggal tidak sesuai, pengguna gagal diperbarui', status= False) ) if 'date_of_birth' in fields: fields['date_of_birth']= datetime.datetime.strptime(fields['date_of_birth'], datetime_format('date')) if 'password' in fields: fields['password']= bcrypt.generate_password_hash(fields['password']) if img_upload.filename != 'default': file_name= formatted_file_name(img_upload.filename) fields['img_url']= f"{request.host_url}uploads/images/{file_name}" img_upload.save(os.path.join(f"{upload_path}/images", file_name)) if calculate_age(datetime.datetime.strptime(fields['date_of_birth'], datetime_format('date')).date()) < 12: return UpdateUser( updated_user= None, response= ResponseMessage(text= 'Umur pengguna belum mencukupi untuk menggunakan aplikasi ini, pengguna gagal diperbarui', status= False) ) result= mongo.db.users.find_one_and_update( { '_id': ObjectId(_id) }, { '$set': dict(fields) } ) if result is None: return UpdateUser( updated_user= None, response= ResponseMessage(text= 'Terjadi kesalahan pada server, pengguna gagal diperbarui', status= False) ) updated_user= mongo.db.users.find_one({ '_id': ObjectId(_id) }) updated_user['date_of_birth']= updated_user['date_of_birth'].date() updated_user['joined_at']= updated_user['joined_at'].date() if updated_user['img_url'] != default_img and is_uploaded_file_exist(updated_user['img_url'].split('/')[-1]) is False: result= mongo.db.users.update_one( { '_id': ObjectId(_id) }, { '$set': { 'img_url': default_img } } ) if result.modified_count == 0: return UpdateUser( updated_user= None, response= ResponseMessage(text= 'Terjadi kesalahan pada gambar profil pengguna, pengguna gagal diperbarui', status= False) ) updated_user['img_url']= default_img return UpdateUser( updated_user= updated_user, response= ResponseMessage(text= 'Berhasil membarui informasi pengguna', status= True) )
def set_password(self, password): """Convert the password to cryptograph via flask-bcrypt""" return bcrypt.generate_password_hash(password)
def _set_password(self, plaintext): self._password = bcrypt.generate_password_hash(plaintext)
def registration(): default = "Admin" if request.method == "POST": username = request.form.get("username") email = request.form.get("email") password = request.form.get("password") repeat = request.form.get("repeat") role = default # check email valid is_valid = check_email(email) if not is_valid: flash("Email is not a valid email", "warning") return redirect(url_for("user.registration")) if password != repeat: flash("Password and repeat did not match!", "warning") return redirect(url_for("user.registration")) if check_email_exists(email): flash("This E-Mail already exist, please go to Login", "warning") return redirect(url_for("user.registration")) password_hash = bcrypt.generate_password_hash(password).decode('utf-8') session_cookie = str(uuid.uuid4()) expiry_time = datetime.datetime.now() + datetime.timedelta( seconds=COOKIE_DURATION) user = User(username=username, email=email, password_hash=password_hash, session_cookie=session_cookie, session_expiry_datetime=expiry_time, role=default) db.session.add(user) db.session.commit() flash("Registration successful!", "success") msg = Message(subject="HelloWorld Blog - Registration successful", sender=SENDER, recipients=[email], bcc=[SENDER]) msg.body = f"Hi {username}!\n" \ f"Welcome to our WebDev Flask site!\n" \ f"Visit us: {HOST_ADDR}\n" \ f"Enjoy!" mail.send(msg) redirect_url = "/" response = make_response(redirect(redirect_url)) response.set_cookie(WEBSITE_LOGIN_COOKIE_NAME, session_cookie, httponly=True, samesite='Strict') return response elif request.method == "GET": return render_template("register.html")
def encrypt_password(self, pass_raw): self.password = bcrypt.generate_password_hash(pass_raw).decode('utf-8')