def checkpassword(id,oldpassword,newpassword): temp = db.reader.find({id,oldpassword}) if temp == None: return False else: generate_password_hash(newpassword,str='pbkdf2:sha1',int=8) return True
def bootstrap_auth(app): '''Bootstrap all the necessary authentication support if it is enabled.''' # Check that the admin credentials are valid. if not app.config.get('ADMINISTRATOR'): sys.exit('You did not provide an administrator username.') if not app.config.get('ADMIN_PASSWORD'): sys.exit('You did not provide an administrator password.') # Store the credentials of the admin account. admin = app.user_storage.find_by_name(app.config['ADMINISTRATOR']) if admin is None: pwhash = security.generate_password_hash(app.config['ADMIN_PASSWORD']) # No admin for this account name so create one. admin = User(app.config['ADMINISTRATOR'], '', # The admin does not use email. 'password', pwhash) app.user_storage.create(admin) else: # The configuration file may have changed the password so always update # the administrator's password. pwhash = security.generate_password_hash(app.config['ADMIN_PASSWORD']) admin.password_digest = pwhash app.user_storage.update(admin)
def setup_server(manager, session=None): """ Sets up and starts/restarts the web service. """ if not manager.is_daemon: return web_server_config = manager.config.get('web_server') if not web_server_config: return web_server = WebServer( bind=web_server_config['bind'], port=web_server_config['port'], ) _default_app.secret_key = get_secret() # Create default flexget user if session.query(User).count() == 0: session.add(User(name="flexget", password=generate_password_hash("flexget"))) session.commit() # Migrate existing user password to be hashed elif session.query(User).count() >= 1: users = session.query(User).filter(User.name == "flexget").all() for user in users: if not user.password.startswith('pbkdf2:sha1'): user.password = unicode(generate_password_hash(user.password)) session.commit() if web_server.is_alive(): web_server.stop() if _app_register: web_server.start()
def on_model_change(self, form, model, is_created): username = model.get('username') password = model.get('password') if is_created: # if password is blank raise error if not password: raise ValidationError('Password is required for new users') # new user so hash the new password model['_id'] = username model['password'] = generate_password_hash( password, method='pbkdf2:sha256' ) else: # existing user, so compare if password is provided and changed current = current_app.db.users.find_one({'username': username}) if password and current.get('password') != password: # if a different password provided, hash it model['password'] = generate_password_hash( password, method='pbkdf2:sha256' ) else: # if password is blank in form, keep the current model['password'] = current['password'] model.pop('csrf_token', None) return model
def test_password_hashing(self): hash0 = generate_password_hash("default") assert check_password_hash(hash0, "default") assert hash0.startswith("pbkdf2:sha1:1000$") hash1 = generate_password_hash("default", "sha1") hash2 = generate_password_hash(u"default", method="sha1") assert hash1 != hash2 assert check_password_hash(hash1, "default") assert check_password_hash(hash2, "default") assert hash1.startswith("sha1$") assert hash2.startswith("sha1$") fakehash = generate_password_hash("default", method="plain") assert fakehash == "plain$$default" assert check_password_hash(fakehash, "default") mhash = generate_password_hash(u"default", method="md5") assert mhash.startswith("md5$") assert check_password_hash(mhash, "default") legacy = "md5$$c21f969b5f03d33d43e04f8f136e7682" assert check_password_hash(legacy, "default") legacy = u"md5$$c21f969b5f03d33d43e04f8f136e7682" assert check_password_hash(legacy, "default")
def setUp(self): """ Test Setup """ self.browser = Browser("phantomjs") self.browser.driver.set_window_size(1440, 900) # set browser size. # set up the tables in the database Base.metadata.create_all(engine) # create 2 example users self.user = models.User(name="Alice", email="*****@*****.**", password=generate_password_hash("test")) session.add(self.user) session.commit() self.user2 = models.User(name="Ryan", email="*****@*****.**", password=generate_password_hash("test")) session.add(self.user2) session.commit() # Create some sample posts content = "Acceptance testing content" for i in range (5): post = models.Post(title="Acceptance test post #{}".format(i+1), content=content, author=self.user) session.add(post) session.commit() """ gives the ability to start and run other code simultaneously with your own scripts """ self.process = multiprocessing.Process(target=app.run) self.process.start() # pause for 1 second time.sleep(1)
def setUp(self): ''' Test setup ''' self.browser = Browser('phantomjs') # if we don't set the window size, we won't be able to interact with UI that might # be hidden because of our media queries with a smaller emulated window self.browser.driver.set_window_size(1120, 550) # set up the tables in the database Base.metadata.create_all(engine) # create an example user self.user = User(name = 'capnmorgan', email = '*****@*****.**', password = generate_password_hash('test')) session.add(self.user) session.commit() # create a second example user self.user = User(name = 'Bob', email = '*****@*****.**', password = generate_password_hash('test')) session.add(self.user) session.commit() self.process = multiprocessing.Process(target = app.run, kwargs = { 'port': 7000 }) self.process.start() time.sleep(1)
def setUpClass(cls): conn = MongoClient() cls.database = conn['dev_scdb'] # Add superuser cls.s = cls.database.user.insert({'email':'*****@*****.**', 'password': generate_password_hash('123'), 'roles': ["superusers"], 'token': generate_token('*****@*****.**')}) # Add ordinary user cls.u = cls.database.user.insert({'email':'*****@*****.**', 'password': generate_password_hash('123'), 'roles': ["users"], 'token': generate_token('*****@*****.**')}) # simple join string to url host = 'http://localhost:9014/api/v2/' cls.concat = lambda cls, rp: "{}{}".format(host, rp) # rp = relative path cls.LOGIN_URL = "http://localhost:9010/login_api/" cls.get_token = lambda cls, token: base64.b64encode("{}:".format(token)) # get token by POST in webapp (another host) def get_token_via_api(cls, identifier, password="******"): r = requests.post(cls.LOGIN_URL, json={"identifier": identifier, "password": password}) token_64 = cls.get_token(json.loads(r.text)['message']['token']) return token_64 cls.get_token_api = get_token_via_api
def create(): """ Creates and initializes the SQLite database from the schema file. """ with current_app.app_context(): connect() with current_app.open_resource(schema_name, mode="r") as f: g.sqlite_connection.cursor().executescript(f.read()) add_user({ "username": "******", "password_hash": generate_password_hash("password"), "email": "*****@*****.**", "permissions": "administrator" }) add_user({ "username": "******", "password_hash": generate_password_hash("password"), "email": "*****@*****.**", "permissions": "author" }) add_category({"name": "Uncategorized"}) add_post({ "author": "author", "creation_date": str(datetime.now()).split(".")[0], "category": category_id("Uncategorized"), "title": "Test Post", "body": "<p>Your bones don't break, mine do. That's clear. Your cells react to bacteria and viruses differently than mine. You don't get sick, I do. That's also clear. But for some reason, you and I react the exact same way to water. We swallow it too fast, we choke. We get some in our lungs, we drown. However unreal it may seem, we are connected, you and I. We're on the same curve, just on opposite ends.</p><p>The path of the righteous man is beset on all sides by the iniquities of the selfish and the tyranny of evil men. Blessed is he who, in the name of charity and good will, shepherds the weak through the valley of darkness, for he is truly his brother's keeper and the finder of lost children. And I will strike down upon thee with great vengeance and furious anger those who would attempt to poison and destroy My brothers. And you will know My name is the Lord when I lay My vengeance upon thee.</p><p>The path of the righteous man is beset on all sides by the iniquities of the selfish and the tyranny of evil men. Blessed is he who, in the name of charity and good will, shepherds the weak through the valley of darkness, for he is truly his brother's keeper and the finder of lost children. And I will strike down upon thee with great vengeance and furious anger those who would attempt to poison and destroy My brothers. And you will know My name is the Lord when I lay My vengeance upon thee.</p>" }) create_about("New Site", "This is a blank description.") create_site_avatar("/static/face.png") g.sqlite_connection.commit()
def register(): if request.method == 'POST' and 'User-Agent' not in request.headers: email = request.form['email'] password = generate_password_hash(request.form['password']) name = request.form['name'] if name and email and password: if Users.query.filter_by(email = email).first() is None: new_user = Users(name, email, password) db.session.add(new_user) db.session.commit() user = Users.query.filter_by(email = email).first() token = user.generate_auth_token(600) #---visit tutorial on generating this return jsonify({'error':'null', 'data':{'token': token.decode('ascii'), 'expires': 600, 'user':{'id': user.id, 'email': user.email, 'name': user.name}, 'message':'success'}}) if Users.query.filter_by(email = email).first() is not None: user = Users.query.filter_by(email = email).first() return jsonify({'error': '1', 'data': {'email': user.email}, 'message':'user already exists'}) form = SignUpForm() if request.method == 'POST' and 'User-Agent' in request.headers: if form.validate_on_submit(): email = request.form['email'] password = generate_password_hash(request.form['password']) name = request.form['name'] new_user = Users(name, email, password) db.session.add(new_user) db.session.commit() # user = Users.query.filter_by(email = email).first() # token = user.generate_auth_token(600) #---visit tutorial on generating this return redirect(url_for('login')) return render_template( 'signup.html', title='User Signup', year=datetime.now().year, form=form, user=g.user )
def test_password_hashing(self): hash0 = generate_password_hash('default') assert check_password_hash(hash0, 'default') assert hash0.startswith('pbkdf2:sha1:1000$') hash1 = generate_password_hash('default', 'sha1') hash2 = generate_password_hash(u'default', method='sha1') assert hash1 != hash2 assert check_password_hash(hash1, 'default') assert check_password_hash(hash2, 'default') assert hash1.startswith('sha1$') assert hash2.startswith('sha1$') fakehash = generate_password_hash('default', method='plain') assert fakehash == 'plain$$default' assert check_password_hash(fakehash, 'default') mhash = generate_password_hash(u'default', method='md5') assert mhash.startswith('md5$') assert check_password_hash(mhash, 'default') legacy = 'md5$$c21f969b5f03d33d43e04f8f136e7682' assert check_password_hash(legacy, 'default') legacy = u'md5$$c21f969b5f03d33d43e04f8f136e7682' assert check_password_hash(legacy, 'default')
def setUp(self): """ Test setup """ self.browser = Browser("phantomjs") # Set up the tables in the database Base.metadata.create_all(engine) # Create an example user self.user = models.User(name="Alice", email="*****@*****.**", password=generate_password_hash("test")) session.add(self.user) session.commit() # Create a second example user self.user2 = models.User(name="Carlos", email="*****@*****.**", password=generate_password_hash("test")) session.add(self.user2) session.commit() # Create some sample posts content = "A post for acceptance testing" for i in range (5): post = models.Post(title="Acceptance test post #{}".format(i+1), content=content, author=self.user) session.add(post) session.commit() self.process = multiprocessing.Process(target=app.run, kwargs={"host": "0.0.0.0", "port": 8080}) self.process.start() time.sleep(1)
def test_identify(self): password = self.generate_password() # Identify hashes generated by werkzeug passlib_hash = generate_password_hash(password, method=self.werkzeug_method) self.assertEqual(self.passlib.identify(passlib_hash), self.passlib_method) # Identify hashes generated by other werkzeug methods diff_werkzeug_method = random.choice([method for method in WERKZEUG_METHODS if method not in [self.werkzeug_method]]) passlib_hash = generate_password_hash(password, method=diff_werkzeug_method) self.assertNotEqual(self.passlib.identify(passlib_hash), self.passlib_method) # Identify hashes generated by werkzeug with varying salt length passlib_hash = generate_password_hash(password, method=self.werkzeug_method, salt_length=self.salt_length + 1) self.assertEqual(self.passlib.identify(passlib_hash), self.passlib_method) # Identify hashes generated by itself passlib_hash = self.passlib.encrypt(password, method=self.passlib_method) self.assertEqual(self.passlib.identify(passlib_hash), self.passlib_method) # Identify hashes generated by other methods diff_passlib_method = random.choice([method for method in PASSLIB_METHODS if method not in [self.passlib_method]]) passlib_hash = self.passlib.encrypt(password, method=diff_passlib_method) self.assertNotEqual(self.passlib.identify(passlib_hash), self.passlib_method) # Identify hashes generated by itself with varying salt length passlib_hash = self.passlib.encrypt(password, method=self.passlib_method, salt_length=self.salt_length + 1) self.assertEqual(self.passlib.identify(passlib_hash), self.passlib_method)
def general_password(self, password): """ 检查密码是否正确 :param password: :return: """ self.password = generate_password_hash(password) return generate_password_hash(password)
def fix_pws(): for client in Client.query.all(): client.password_ = generate_password_hash('test') db.session.commit() for trainer in Trainer.query.all(): trainer.password_ = generate_password_hash('test') db.session.commit() return 'changed!'
def setUp(self): self.fixtures = { 'alice': User(name='Alice', email='*****@*****.**', password=generate_password_hash('alice')), 'bob': User(name='Bob', email='*****@*****.**', password=generate_password_hash('bob'))} self.fixtures.update({ 'entry': Entry(title='Test Entry', content='Test Content', author=self.fixtures['alice'])}) super(TestEditEntry, self).setUp()
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
def create_users(): try: user1 = Users(username='******', email='*****@*****.**', password=generate_password_hash('user1234')) user2 = Users(username='******', email='*****@*****.**', password=generate_password_hash('user221234')) db.session.add(user1) db.session.add(user2) db.session.commit() except Exception as err: print("-- user creation failed..") print(err)
def registro(): datos=request.form nombre=datos["nombre"] apellidos=datos["apellidos"] telefono=datos["telefono"] pueblo=datos["pueblo"] correo=datos["correo"] passwd= generate_password_hash(datos["password"])# check_password_hash(pw_hash, password) #verificar datos aqui: #el pueblo existe errores=list() if(len(datos["password"])<6): errores.append("Contraseña demasiado corta") if(getIdPueblo(pueblo)=="ERROR"): errores.append("error: pueblo no existente: "+pueblo) #el correo es valido if not validate_email(correo):#paranoya: verify=True revisar que el correo existe errores.append("error: correo no valido: "+correo) #el telefono es valido regexpTelefono = re.compile("^[9|6|7][0-9]{8}$") if not regexpTelefono.match(telefono): errores.append("error: telefono no valido: "+telefono) #verificar que el usuario no está registrado: consultaCorreoUnico='SELECT correo FROM `usuarios` WHERE `correo` LIKE \''+correo+'\'' conexionRegistro=conexion.conectar() cursorRegistro=conexionRegistro.cursor() cursorRegistro.execute(consultaCorreoUnico) for mail in cursorRegistro: errores.append("Ya existe un usuario con este correo") #En caso de error devolver una lista con los errores if(len(errores)>0): return errores #No hace falta else: hacemos un return #Generar token para el usuario en caso de exito token=generate_password_hash("TOKEN++"+passwd+datos["password"]+correo) #insertar datos en la base de datos insertarUsuario="INSERT INTO `usuarios` (`id_usuario`, `nombre`, `apellidos`, `telefono`, `pueblo_origen`, `pass`, `correo`, `token`) VALUES (NULL, \'" +\ nombre+"\',\'"+apellidos+"\',\'"+telefono+"\',"+getIdPueblo(pueblo)+",\'"+passwd+"\',\'"+correo+"\',\'"+token+"\');" #print(insertarUsuario) cursorRegistro.execute(insertarUsuario) conexionRegistro.commit() conexionRegistro.close() #devolver {"token":token} return {"exito":True,"token":token}
def setUp(self): """Test setup""" self.client = app.test_client() #Set up the tables in the database Base.metadata.create_all(engine) #Create an example user self.user_a = models.User(name="Alice", email ="*****@*****.**", password=generate_password_hash("test")) self.user_b = models.User(name="Eddie", email="*****@*****.**", password=generate_password_hash("1234")) session.add_all([self.user_a, self.user_b]) session.commit()
def __init__(self, name, desc="Test", timeout=5, ttl=-1, sub_passwd="", pub_passwd=None): self.name = name self.desc = desc self.timeout = timeout self.gc_time = datetime.now() + timedelta(hours=ttl) \ if ttl > 0 else None self.sub_passwd = generate_password_hash(sub_passwd) self.pub_passwd = generate_password_hash(pub_passwd) \ if pub_passwd else None self.subscribers = {"ALL": Subscriber("ALL")} self.lock = gevent.lock.RLock()
def sign_up(): if request.method == 'GET': return render_template('sign_up.html', signup_form=RegistrationForm(), hide=True) else: rf = RegistrationForm(request.form) if rf.validate_on_submit(): users = db.userprofiles users.insert({'username': rf.username.data, 'password':generate_password_hash(rf.password.data), 'email':rf.email.data, 'first_name':rf.first_name.data, 'last_name':rf.last_name.data, 'competencies':[], 'compfwks':[], 'lrsprofiles':[]}) user = User(rf.username.data, generate_password_hash(rf.password.data)) login_user(user) return redirect(url_for('index')) return render_template('sign_up.html', signup_form=rf, hide=True)
def setUp(self): Base.metadata.create_all(engine) alice = User(name="Alice", email="*****@*****.**", password=generate_password_hash("atest")) bob = User(name="Bob", email="*****@*****.**", password=generate_password_hash("btest")) session.add_all([alice, bob]) session.commit() post1 = Post(title="Alice's Title", content="Alice's Content", author_id=alice.id) post2 = Post(title="Bob's Title", content="Bob's Content", author_id=bob.id) session.add_all([post1, post2]) session.commit()
def register(): # Grab the information from the request body name = request.form['name'] email = request.form['email'] password = request.form['password'] user_type = request.form['type'].lower() tid = int(request.form['team']) cursor = g.db.cursor() # first check if user with email address already exists cursor.execute('SELECT * FROM User WHERE email = %s', (email,)) # if any user was found, then cannot register with that email if int(cursor.rowcount) != 0: flash('That email address is already taken.', 'error') return redirect(url_for('index')) uid = 0 # if the user is an athlete, then we insert them into the Athletes table # and put them on a team, as well as insert them into the User table if user_type == 'athlete': weight = float(request.form['weight']) height = float(request.form['height']) cursor.execute('INSERT INTO User(name, email, password) VALUES(%s, %s, %s)', (name, email, generate_password_hash(password))) uid = cursor.lastrowid cursor.execute('INSERT INTO Athlete VALUES(%s, %s, %s)', (uid, height, weight)) cursor.execute('INSERT INTO member_of VALUES(%s, %s, "Bench", NextTeamNumber(%s))', (uid, tid, tid)) # if the user is a coach, then we insert them into the Coach table # and have them coach a team, as well as insert them into the User table elif user_type == 'coach': salary = float(request.form['salary']) cursor.execute('INSERT INTO User(name, email, password) VALUES(%s, %s, %s)', (name, email, generate_password_hash(password))) uid = cursor.lastrowid cursor.execute('INSERT INTO Coach VALUES(%s, %s)', (uid, salary)) cursor.execute('INSERT INTO coaches VALUES(%s, %s, %s)', (uid, tid, datetime.now())) # commit the transaction g.db.commit() # set the cookies session['user_id'] = uid session['user_name'] = name session['user_type'] = user_type flash('You were successfully registered and logged in.', 'success') return redirect(url_for('index'))
def upload_photo(): try: file = request.files["file"] if file and allowed_file(file.filename): ext = file.filename.rsplit(".", 1)[1] filename = secure_filename(generate_password_hash(str(random.random())) + "." + ext) filepath = os.path.join(app.config["UPLOAD_FOLDER"], filename) while os.path.isfile(filepath): filename = secure_filename(generate_password_hash(filename) + "." + ext) filepath = os.path.join(app.config["UPLOAD_FOLDER"], filename) file.save(filepath) return json.dumps(dict(state=True, filename=filename, url=url_for("uploaded_file", filename=filename))) except Exception as e: raise e return json.dumps(dict(state=False))
def set_password(self): if not self.password: raise ValueError('No password set') password_hash = generate_password_hash(self.password) _, salt, __ = password_hash.split('$') self.token = salt self.password = password_hash
def new_smiley(): """ Input info for new user """ in_use = [] people = PeopleModel.all() for person in people: in_use.append(person.name) reservered = [u'new', u'debug', u'debug-people', u'home', u'about'] form = PeopleForm() if form.validate_on_submit(): person = PeopleModel( key_name = form.name.data.lower(), name = form.name.data.lower(), startdate = form.startdate.data, enddate = form.enddate.data, password = generate_password_hash(form.password.data) ) person.name = slugify(person.name) if form.password.data == "": person.password = "" if unicode(person.name) not in in_use and (unicode(person.name) not in reservered): try: person.put() flash(unicode(person.name), 'success') mail.send_mail(sender="Neuer Nutzer! <*****@*****.**>",\ to = "<*****@*****.**>", subject="Neuer Benutzer!", body=person.name) return redirect(url_for('home') + person.name.encode("utf-8")) except CapabilityDisabledError: flash(u'App Engine Datastore is currently in read-only mode.', 'failure') return redirect(url_for('list_examples')) else: flash(u'Der Name ist leider schon reserviert, probiere doch einfach einen anderen') return redirect(url_for('new_smiley')) return render_template('setup.html', form=form)
def patch(self, id): user = Users.query.get_or_404(id) raw_dict = request.get_json(force=True) try: schema.validate(raw_dict) request_dict = raw_dict['data']['attributes'] payload = parse_token(request) logged_user = Users.query.get(payload['sub']) request_dict['updatedby'] = logged_user.name for key, value in request_dict.items(): if key == "password": value = generate_password_hash(value) setattr(user, key, value) user.update() return self.get(id) except ValidationError as err: resp = jsonify({"error": err.messages}) resp.status_code = 401 return resp except SQLAlchemyError as e: db.session.rollback() resp = jsonify({"error": str(e.orig.args)}) resp.status_code = 401 return resp
def build_sample_db(): import string import random db.drop_all() db.create_all() # passwords are hashed, to use plaintext passwords instead: test_user_1 = User(login="******", password=generate_password_hash("p@ssw0rd*"),last_name='lastTest') db.session.add(test_user_1) test_user_2 = User(login="******", password=generate_password_hash("@ndr0P@tch@pp"),last_name='lastTest') db.session.add(test_user_2) test_user_3 = User(login="******", password=generate_password_hash("op3rand0!op3rand0!"),last_name='lastTest') db.session.add(test_user_3) db.session.commit() return
def add_register_user(self, username, first_name, last_name, email, password='', hashed_password=''): """ Add a registration request for the user. :rtype : RegisterUser """ register_user = self.registeruser_model() register_user.username = username register_user.email = email register_user.first_name = first_name register_user.last_name = last_name if hashed_password: register_user.password = hashed_password else: register_user.password = generate_password_hash(password) register_user.registration_hash = str(uuid.uuid1()) try: self.get_session.add(register_user) self.get_session.commit() return register_user except Exception as e: log.error(c.LOGMSG_ERR_SEC_ADD_REGISTER_USER.format(str(e))) self.appbuilder.get_session.rollback() return None
def signup(): accounts = app.data.driver.db['people'] user_email = accounts.find_one({'email': request.json['email']}) if not user_email: dt = datetime.now() user = { 'email': request.json['email'], 'username': request.json['username'], 'name': { 'first': request.json['firstname'], 'last': request.json['lastname'] }, 'password': { 'password': generate_password_hash(request.json['password']), 'password_test': request.json['password'], 'password_updated': str(datetime.now()) }, 'email_confirmed': False, 'picture': { 'large': "static/app/images/w-logo.jpg", 'medium': "static/app/images/w-logo.jpg", 'thumbnail': "static/app/images/w-logo.jpg" }, 'phone': "", 'interests': [], 'study': { 'intermediate': "", 'graduate': "" }, 'random_string': id_generator(), 'accept_notifications': [], 'born': "", 'gender': request.json['gender'], 'lastmessageseen': dt.strftime('%Y-%m-%dT%H:%M:%SZ'), 'location': { 'city': "", 'state': "", 'street': "" }, 'friends': [], 'matchnotifications': [], 'notifications': [], 'interests': request.json['interests'], 'interestsimilarwords': request.json['interestsimilarwords'], 'conversations': [] } data = accounts.insert(user) user_id = str(user['_id']) user_random_string = str(user['random_string']) msg = Message('Confirm your Weber account', sender='*****@*****.**', recipients=[request.json['email']]) msg.html = '<div style="min-height:100px;border:1px solid #dcdcdc;">' \ '<h5>Thanks for registering with us, To complete your Weber registration, Follow this link:</h5>' \ '<div style="padding:20px 5px">' \ '<a href="http://www.weber.ooo/#/confirm_account/users/'\ +user_id+'/confirm/'+user_random_string+'">Click Here</a>' \ '</div>' \ '</div>' mail.send(msg) return user_id else: response = jsonify( error= 'This email is registered with us. Please try forgot password.') response.status_code = 401 return response
import pytest from seleniumbase import BaseCase from qa327.models import db, User from qa327_test.conftest import base_url from unittest.mock import patch from werkzeug.security import generate_password_hash, check_password_hash test_user = User(email='*****@*****.**', name='testuser', password=generate_password_hash('test_frontendA1$')) class R7TestPost(BaseCase): # Logout will invalidate the current session and redirect to # the login page. After logout the user should not be able to # access restricted pages @patch('qa327.backend.get_user', return_value=test_user) def test_r1_post_1(self, *_): # logout self.open(base_url + '/logout') # check if we are on the login page now self.assert_text("Please Login") # try to go to / self.open(base_url) # validate that we are still on the login page self.assert_text("Please Login")
def password(self, value): self.password_hash = generate_password_hash(value)
def set_password(self, password): self.password = generate_password_hash(password)
def set_password(self, password): self.senha = generate_password_hash(password)
def add_admin(): res = {} file = request.files['image'] if 'firstname' in request.form and 'lastname' in request.form and 'email' in request.form and 'password' in request.form: firstname = request.form['firstname'] lastname = request.form['lastname'] email = request.form['email'] password = request.form['password'] position = request.form['position'] phone = request.form['phone'] role = request.form['role'] user_type = request.form['user_type'] print(request.files['image']) get_filename = secure_filename(file.filename) filename, file_extension = os.path.splitext(get_filename) today = datetime.date.today() today = str(today) #encodedBytes = base64.b64encode(today.encode("utf-8")) #encodedStr = str(encodedBytes, "utf-8") filename = today + '-' + firstname + file_extension filename = filename.replace(' ', '-').lower() print(filename) else: if not 'image' in request.files: res["error"] = "No Image" if not allowed_file(file.filename): res["error"] = "File type not supported" return jsonify({"data": res}) filename = os.path.join(app.config['UPLOAD_FOLDER'], filename) #Cropp image #img = Image.open(filename) #area =(200, 100, 700,400) #new_sizeed_file = img.crop(area) #new_sizeed_file.show(new_sizeed_file) print(filename) if not os.path.exists(UPLOAD_FOLDER): os.makedirs(UPLOAD_FOLDER) temp_file = os.path.join(app.config['UPLOAD_FOLDER'], "temp.jpg") file.save(temp_file) storage.child(filename).put(temp_file) # Get image url from firebase img_url = storage.child(filename).get_url(None) #res["msg"] = "Valid_Image" shutil.copy(temp_file, filename) file = request.files['image'] res["media"] = filename print(request.files) req_data = request.get_json() print(req_data) hashed_password = generate_password_hash(request['password'], method='sha256') data = { 'firstname': firstname, 'lastname': lastname, 'avatar_thumbnail': img_url, 'email': email, 'password': hashed_password, 'position': position, 'phone': phone, 'role': role, } data['_id'] = str(ObjectId()) x = database["admins"].insert_one(data) #memberID = request.form['memberID'] #database['users'].update({'_id': memberID}, {"$set": {'profile_bg':profile_bg}}) os.remove(temp_file) return jsonify({"data": res})
def password(self, orig_password): self._password = generate_password_hash(orig_password)
def __init__(self, name,email,password): # მხოლოდ გვჭირდება ამ ბაზის მოდელისთვის უნიკალური წევრის ატრიბუტის აღწერა self.name = name self.email=email self.password=generate_password_hash(password)
specfic values. For example: @patch('qa327.backend.get_user', return_value=test_user) Will patch the backend get_user function (within the scope of the current test case) so that it return 'test_user' instance below rather than reading the user from the database. Annotate @patch before unit tests can mock backend methods (for that testing function) """ # Mock a sample user test_user = User(email='*****@*****.**', name='test_frontend', password=generate_password_hash('Testfrontend123!'), balance=5000) # Mock some sample tickets test_tickets = [{ 'name': 'ticket1', 'price': 100, 'email': '*****@*****.**', 'date': '20210901' }] class FrontEndSellTesting(BaseCase): @patch('qa327.backend.get_user', return_value=test_user) @patch('qa327.backend.get_all_tickets', return_value=test_tickets)
def makePassword(self, password): return generate_password_hash(password)
def password(self, raw): self._password = generate_password_hash(raw)
def password(self, password): self.password_hash = generate_password_hash(password)
def __init__(self,first_name,last_name,username,password): self.first_name=first_name self.last_name=last_name self.username=username self.password=generate_password_hash(password,method='pbkdf2:sha256')
def pre_add(self, item): item.password = generate_password_hash(item.password)
def changepassword(): accounts = app.data.driver.db['people'] user = accounts.find_one({'username': request.json['user_name']}) if user: password = generate_password_hash(request.json['password']) return password
def set_password(password): return generate_password_hash(password)
def password(self, password): """ Merubah password ke dalam bentuk hash """ self.password_hash = generate_password_hash(password)
def hash_password(self, password): """Uses werkzeug to hash the plaintext password Sets the password_hash as a property of the User """ logger.debug("hashing password...") self.password_hash = generate_password_hash(password, method="sha256")
def set_password(self, password): """Create hashed password.""" self.password = generate_password_hash(password, method='pbkdf2:sha256:100000', salt_length=16)
def __init__(self, **kwargs): super().__init__(**kwargs) self.nmUsuario = kwargs.pop('nmUsuario') self.senha = generate_password_hash(kwargs.pop('senha'))
def solution_put_new_user(new_user_id, user_data): user = User(new_user_id) user.email = user_data['email'] user.password = generate_password_hash(user_data['password']) user.username = user_data['username'] user.save()
def register(): """Registers users""" usern = request.form.get("usern") email = request.form.get("email") passw = request.form.get("passw") confirm = request.form.get("confirm") hsh = generate_password_hash(passw) validation = {"errors": {}} if not usern: validation["errors"]["usern"] = "This field is required." if not email: validation["errors"]["email"] = "This field is required." if not passw: validation["errors"]["passw"] = "This field is required." if not confirm: validation["errors"]["confirm"] = "This field is required." # If at least one field is empty if not (usern and email and passw and confirm): return validation # The password must be secure if not re.match( r"(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%^&*?~\\/|<>,.0-9]).{8,26}", passw): validation["errors"][ "passw"] = "Use at least: 8 characters; 1 uppercase and 1 lowercase letter; 1 digit or 1 symbol" return validation # The passwords must match if passw != confirm: validation["errors"]["confirm"] = "The passwords don't match." return validation # Returns "True" if username/email exists, "False" otherwise usern_exists = db.execute( "SELECT EXISTS(SELECT * FROM users WHERE username=:usern)", { "usern": usern }).fetchone()[0] email_exists = db.execute( "SELECT EXISTS(SELECT * FROM users WHERE email=:email)", { "email": email }).fetchone()[0] # Returns to the user if the username/email subbmited already exists if usern_exists: validation["errors"]["usern"] = "Username is already taken." return validation elif email_exists: validation["errors"]["email"] = "Email is already taken." return validation # Insert the new user into the "users" table db.execute( "INSERT INTO users (username, email, hash) VALUES (:usern, :email, :hash)", { "usern": usern, "email": email, "hash": hsh }) db.commit() # Log the new user in session["uid"] = db.execute("SELECT id FROM users WHERE username=:usern", { "usern": usern }).fetchone()[0] session["usern"] = db.execute("SELECT username FROM users WHERE id=:uid", { "uid": session["uid"] }).fetchone()[0] # No errors were found return validation
def hash_password(self): self.password = generate_password_hash(self.password)
def set_password(self, password): self.password = generate_password_hash(password, method='sha256')
def password(self, p): self._password = generate_password_hash(p)
from flask import Flask import sqlite3 from werkzeug.security import generate_password_hash, check_password_hash connection = sqlite3.connect('database1.db') cursor = connection.cursor() password = generate_password_hash('asecurepasswordladz1') cursor.execute( 'CREATE TABLE User (FirstName varchar(255) NOT NULL,Surname varchar(255) NOT NULL,UserName varchar(255) UNIQUE NOT NULL,Password varchar(255) NOT NULL,Email varchar(255) UNIQUE NOT NULL,UID bigint(255),isAdmin BIT NOT NULL,isBanned BIT NOT NULL)' ) cursor.execute('INSERT INTO User VALUES (?,?,?,?,?,?,?,?)', ('Andrew', 'Nicolaou', 'ANiclaou', password, '2greeks1italian{0x40}gmail{0x2e}com', '1', 1, 0)) connection.commit() cursor.execute( 'CREATE TABLE Posting(PostID bigint UNIQUE NOT NULL, Content varchar(1700) NOT NULL,DateStamp varchar(255) NOT NULL, Username varchar(255) NOT NULL)' ) connection.commit()
from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_httpauth import HTTPBasicAuth from werkzeug.security import generate_password_hash, check_password_hash # General flask and DB setup app = Flask(__name__) app.config["SECRET_KEY"] = "hfds98fuzausaujfs7f/HD(dVbQ3pVr7H" app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///data/rnsm.db" db = SQLAlchemy(app) # HTTP Authentication setup auth = HTTPBasicAuth() users = { "rnsm-admin": generate_password_hash("rnsm"), } @auth.verify_password def verify_password(username, password): if username in users and check_password_hash(users.get(username), password): return username from app import routes
def set_password(self, password): if not password: self.password = None else: self.password = generate_password_hash(password)
def password(self, password): self.pass_secure = generate_password_hash(password)
def enregistrer_mot_de_passe(self, mot_de_passe): self.mot_de_passe_hash = generate_password_hash(mot_de_passe)