class LongPasswordsTestCase(BasicTestCase): def setUp(self): app = flask.Flask(__name__) app.config['BCRYPT_LOG_ROUNDS'] = 6 app.config['BCRYPT_HASH_IDENT'] = '2b' app.config['BCRYPT_HANDLE_LONG_PASSWORDS'] = True self.bcrypt = Bcrypt(app) def test_long_password(self): """Test the work around bcrypt maximum password length.""" # Create a password with a 72 bytes length password = '******' * 72 pw_hash = self.bcrypt.generate_password_hash(password) # Ensure that a longer password **do not** yield the same hash self.assertFalse(self.bcrypt.check_password_hash(pw_hash, 'A' * 80))
class BasicTestCase(unittest.TestCase): def setUp(self): app = flask.Flask(__name__) app.config['BCRYPT_LOG_ROUNDS'] = 6 app.config['BCRYPT_HASH_IDENT'] = '2b' app.config['BCRYPT_HANDLE_LONG_PASSWORDS'] = False self.bcrypt = Bcrypt(app) def test_is_string(self): pw_hash = self.bcrypt.generate_password_hash('secret') if PY3: self.assertTrue(isinstance(pw_hash, bytes)) else: self.assertTrue(isinstance(pw_hash, str)) def test_custom_rounds(self): password = '******' pw_hash1 = self.bcrypt.generate_password_hash(password, 5) self.assertNotEqual(password, pw_hash1) def test_check_hash(self): pw_hash = self.bcrypt.generate_password_hash('secret') # check a correct password self.assertTrue(self.bcrypt.check_password_hash(pw_hash, 'secret')) # check an incorrect password self.assertFalse(self.bcrypt.check_password_hash(pw_hash, 'hunter2')) # check unicode pw_hash = self.bcrypt.generate_password_hash(u'\u2603') self.assertTrue(self.bcrypt.check_password_hash(pw_hash, u'\u2603')) # check helpers pw_hash = generate_password_hash('hunter2') self.assertTrue(check_password_hash(pw_hash, 'hunter2')) def test_check_hash_unicode_is_utf8(self): password = u'\u2603' pw_hash = self.bcrypt.generate_password_hash(password) # check a correct password self.assertTrue( self.bcrypt.check_password_hash(pw_hash, b'\xe2\x98\x83')) def test_rounds_set(self): self.assertEqual(self.bcrypt._log_rounds, 6) def test_unicode_hash(self): password = u'東京' h = generate_password_hash(password).decode('utf-8') self.assertTrue(check_password_hash(h, password)) def test_long_password(self): """Test bcrypt maximum password length. The bcrypt algorithm has a maximum password length of 72 bytes, and ignores any bytes beyond that.""" # Create a password with a 72 bytes length password = '******' * 72 pw_hash = self.bcrypt.generate_password_hash(password) # Ensure that a longer password yields the same hash self.assertTrue(self.bcrypt.check_password_hash(pw_hash, 'A' * 80))
class BasicTestCase(unittest.TestCase): def setUp(self): app = flask.Flask(__name__) app.config['BCRYPT_LOG_ROUNDS'] = 6 app.config['BCRYPT_HASH_IDENT'] = '2b' app.config['BCRYPT_HANDLE_LONG_PASSWORDS'] = False self.bcrypt = Bcrypt(app) def test_is_string(self): pw_hash = self.bcrypt.generate_password_hash('secret') if PY3: self.assertTrue(isinstance(pw_hash, bytes)) else: self.assertTrue(isinstance(pw_hash, str)) def test_custom_rounds(self): password = '******' pw_hash1 = self.bcrypt.generate_password_hash(password, 5) self.assertNotEqual(password, pw_hash1) def test_check_hash(self): pw_hash = self.bcrypt.generate_password_hash('secret') # check a correct password self.assertTrue(self.bcrypt.check_password_hash(pw_hash, 'secret')) # check an incorrect password self.assertFalse(self.bcrypt.check_password_hash(pw_hash, 'hunter2')) # check unicode pw_hash = self.bcrypt.generate_password_hash(u'\u2603') self.assertTrue(self.bcrypt.check_password_hash(pw_hash, u'\u2603')) # check helpers pw_hash = generate_password_hash('hunter2') self.assertTrue(check_password_hash(pw_hash, 'hunter2')) def test_check_hash_unicode_is_utf8(self): password = u'\u2603' pw_hash = self.bcrypt.generate_password_hash(password) # check a correct password self.assertTrue(self.bcrypt.check_password_hash(pw_hash, b'\xe2\x98\x83')) def test_rounds_set(self): self.assertEqual(self.bcrypt._log_rounds, 6) def test_unicode_hash(self): password = u'東京' h = generate_password_hash(password).decode('utf-8') self.assertTrue(check_password_hash(h, password)) def test_long_password(self): """Test bcrypt maximum password length. The bcrypt algorithm has a maximum password length of 72 bytes, and ignores any bytes beyond that.""" # Create a password with a 72 bytes length password = '******' * 72 pw_hash = self.bcrypt.generate_password_hash(password) # Ensure that a longer password yields the same hash self.assertTrue(self.bcrypt.check_password_hash(pw_hash, 'A' * 80))
def login(app): form = request.form bcrypt = Bcrypt(app) email = form['email'] password = form['password'] query = "SELECT user_password, user_role, user_id, user_email FROM user\ WHERE user_email = %s" try: connection = connect() cur = connection.cursor() cur.execute(query, (email, )) results = cur.fetchall() if len(results) > 0: results = results[0] if bcrypt.check_password_hash(results[0], password): session['email'] = results[3] session['role'] = results[1] session['id'] = results[2] flash("Login successful") return redirect(url_for('index')) else: flash("Incorrect password") return redirect(url_for('auth')) else: flash("No such user.. Register first!!") return redirect(url_for('auth')) except mysql.connector.Error as err: flash("Something went wrong") print("Something went wrong: {}".format(err)) return "SQL ERROR" finally: cur.close() connection.close()
def login(): bcrypt = Bcrypt(current_app) if request.method == 'GET': return render_template('login.html') # Get username from form username = request.form['username'] # Get authentication details with pg_simple.PgSimple() as db: auths = db.fetchone(userTable, fields=['password', 'api'], where=('name = %s', [username])) try: # Check password salt if bcrypt.check_password_hash(auths.password, request.form['password']): session['user'] = auths.api # API key in session session['username'] = username # username in session return redirect(url_for('stats')) except (ValueError, TypeError, AttributeError) as e: # Non-existent username pass messages("401") return redirect(url_for('authentication.login'))
class db_login: def __init__(self): db_uri = app.config['SQLALCHEMY_DATABASE_URI'] self.flsk_bcrypt = Bcrypt(app) self.engine = create_engine(db_uri) self.conn = self.engine.connect() self.Session = sessionmaker(bind=self.engine) self.session = self.Session() def _close_conn(self): self.session.expire_all() self.conn.close() def validate(self, email, password): query = "SELECT hash_and_salt FROM bball_user WHERE email_address = :email" result = self.session.execute(query, {"email": email}) user = result.fetchone() self._close_conn() if user is not None: return self.flsk_bcrypt.check_password_hash(user[0], password) return False def ins_cred(self, email, password=None): if self.user_exists(email): return False, "Email already taken" hashed_pw = self.flsk_bcrypt.generate_password_hash(password) query = 'INSERT INTO bball_user (email_address, hash_and_salt) VALUES (:email, :hashed_pw)' result = self.session.execute(query, { "email": email, "hashed_pw": hashed_pw }) self.session.commit() self._close_conn() if result: return True, "Registration Successful" else: return False, "Registration failed, try again" def get_user_id(self, email): result = self.session.execute( "SELECT id, email_address FROM bball_user WHERE email_address = :email", {"email": email}) user_id = result.fetchone() self._close_conn() if user_id: return [user_id[0], user_id[1]] return [None, None] def user_exists(self, email): user_df = pd.read_sql_query( "SELECT email_address FROM bball_user WHERE email_address = '{email}'" .format(email=email), self.conn) self._close_conn() return not user_df.empty
def post(self): parser = reqparse.RequestParser() parser.add_argument('ausername', type=str, required=True, help='username cannot be left blank') parser.add_argument('apassword', type=str, required=True, help='password cannot be left blank') data = parser.parse_args() bcrypt = Bcrypt() try: adminuser = AdminUser.getAdminUserByAusername(data['ausername']) if adminuser and bcrypt.check_password_hash( adminuser.apassword, data['apassword']): access_token = create_access_token( identity=adminuser.ausername, expires_delta=False) return { "ausername": adminuser.ausername, "aname": adminuser.aname, "adept": adminuser.adept, "access_token": access_token }, 200 return {"message": "Invalid credentials!"}, 401 except: return {"message": "Error while logging in"}, 500
def authenticate(): bcrypt = Bcrypt() req = request.args.to_dict() email = req['email'] password = req['password'] auth = client['nodemind'].auth response = auth.find_one({'email_id': email}) user_data = dict() if not response: user_data = dict() user_data['debug'] = '404' # User not found return jsonify(user_data) if bcrypt.check_password_hash(response['password'], password): logger.info('Auth success') db = client['nodemind'].core user_data = db.find({'email_id': response['email_id']})[0] del user_data['_id'] access_token = create_access_token(identity=email) user_data['access_token'] = access_token global EMAIL EMAIL = email user_data['debug'] = '200' return user_data else: user_data['debug'] = '401' return user_data
def login(): bcrypt = Bcrypt(app) result = [{'msg': 'success'}, {'stat': '200 ok'}] if request.method == 'POST': name = request.json.get('name', None) print(name) passworda = request.json.get('password', None) print('password='******'result': result} return jsonify(access_token=access_token)
def post(self): parser = reqparse.RequestParser() parser.add_argument('srollno', type=str, required=True, help='roll no cannot be left blank') parser.add_argument('spassword', type=str, required=True, help='password cannot be left blank') data = parser.parse_args() bcrypt = Bcrypt() try: studentuser = StudentUser.getStudentUserBySrollno(data['srollno']) if studentuser and bcrypt.check_password_hash( studentuser.spassword, data['spassword']): access_token = create_access_token( identity=studentuser.srollno, expires_delta=False) return { "sname": studentuser.sname, "sdept": studentuser.sdept, "syear": studentuser.syear, "access_token": access_token }, 200 return {"message": "Invalid credentials!"}, 401 except: return {"message": "Error while logging in"}, 500
def get_by_user_name_and_password(user_name, password): bcrypt = Bcrypt(None) user = user_reader.get_by_user_name(user_name) if user: if bcrypt.check_password_hash(user.password, password): return user return None
def modifyPassword(current_user, user_id): if current_user.id != int(user_id): return jsonify({ "error_code": "404", "error_msg": "user Not Found" }), 404 try: d = request.get_json() old_password = d['old_password'] new_password = d['new_password'] user = queryUserById(user_id) except Exception as e: return jsonify({ "error_code": "400", "error_msg": "f**k you asshole" }), 400 if user: bcrypt = Bcrypt(current_app) if bcrypt.check_password_hash(user.password, old_password): hashed_password = bcrypt.generate_password_hash( new_password).decode('utf-8') try: changePassword(user_id, hashed_password) except Exception as e: return jsonify({"error_code": 500, "error_msg": str(e)}), 500 else: return jsonify({"message": "Modify Successfully!"}), 200 else: return jsonify({ "error_code": "404", "error_msg": "account not found/password incorrect" }), 404
def post(self): data = ResetPassword.parser.parse_args() bcrypt = Bcrypt() if UserModel.user_exists(data['username']) == 0: logger.error("User with this username doesn't exist") return {"message": "User with this username doesn't exist!"}, 401 stored_password = UserModel.get_password_by_username( data['username'], "password") check_password = bcrypt.check_password_hash(stored_password, data['oldPassword']) if check_password: logger.info("Password matched") hashed_password = bcrypt.generate_password_hash( data['newPassword']).decode('utf-8') try: UserModel.update_password(data['username'], hashed_password) logger.info("message:" "Password updated") return {"message": "Password updated"}, 200 except Exception as e: logger.error(e) logger.error("Update password operation failed!", exc_info=True) return {"message": "Update password operation failed!"}, 500 else: return {"message": "Old password doesn't match"}, 403
def login(): from flask_bcrypt import Bcrypt bcrypt = Bcrypt() if request.method == 'POST': username = request.form['username'] password = request.form['password'] db = get_db() error = None user = db.execute('SELECT * FROM user WHERE username = ?', (username, )).fetchone() if user is None: error = 'Incorrect username.' elif not bcrypt.check_password_hash(user['password'], password + user['salt']): error = 'Incorrect password.' if error is None: session.clear() session['user_id'] = user['id'] return redirect(url_for('index')) flash(error) return render_template('auth/login.html')
def login(): form=LoginForm() users = mongo.db.users session['username']=None mssg='Invalid Username or Password' active1 = 'active' if request.method=='POST': existing_user=users.find_one({'username': form.username.data}) if existing_user is None: return render_template('login.html',form=form,mssg=mssg, active1=active1) bcrypt=Bcrypt() db_uname=existing_user['username'] db_pass=existing_user['password'] if db_uname==form.username.data and bcrypt.check_password_hash(db_pass, form.password.data): session['username'] = form.username.data return redirect(url_for('url', name=db_uname)) return render_template('login.html', mssg=mssg, form=form, active1=active1) return render_template('login.html',form=form, active1=active1)
def post(self): contract = LoginContract() playload = request.json if not (contract.validate(playload)): return ResultModel('Envie todos parametros obrigatorios.', False, contract.errors).to_dict(), 406 password = playload.get('password') bcrypt = Bcrypt(current_app) crypt_password = bcrypt.generate_password_hash(password).decode( 'utf-8') repository = UserRepository() user = repository.get_by_username(playload.get('username'), True)['data']['result'] if not user: ResultModel('Usuario não existe.', False, True) if not user or not bcrypt.check_password_hash(user['password'], password): return ResultModel('Credenciais incorretas.', False, True).to_dict(), 406 data = {'userId': user['id'], 'is_admin': user['is_admin']} expires = datetime.timedelta( days=current_app.config.get('TOKEN_DAYS_EXPIRES')) token = create_access_token(identity=user['id'], expires_delta=expires, user_claims=data) return ResultModel('Sucesso na geração do token.', token, False).to_dict(), 201
def admin_index(self): bcrypt = Bcrypt(app) """For GET requests, display the login form. For POSTS, login the current user by processing the form.""" form = LoginForm() next = request.args.get('next') if form.validate(): user = User.query.filter(User.username==form.username.data).first() if user: a = bcrypt.generate_password_hash(form.password.data) if bcrypt.check_password_hash(user.password, form.password.data): user.authenticated = True db.session.add(user) db.session.commit() login_user(user, remember=True, force=True) next = request.args.get('next') print("You have successfully logged in") return redirect(next or url_for('admin.admin_index')) else: print "bad password" else: print "user mismatch" return self.render('admin/index.html', form=form)
def login(): form = LoginForm() bcrypt = Bcrypt() connection = connect() if form.validate_on_submit(): try: email = form.email.data cursor = connection.cursor() sql = "SELECT email, password FROM users WHERE email = (%s)" cursor.execute(sql, email) data = cursor.fetchone() if data is not None and email == data[ 'email'] and bcrypt.check_password_hash( data['password'], form.password.data): flash('You have successfully logged in!', 'success') return redirect(url_for('home')) else: flash('Login unsuccessful! Please check email and password.', 'danger') finally: connection.close() return render_template('login.html', title='Login Page', form=form)
def login(): user = request.json if user != None: try: db_user = UserService.getUserByUsername(user.get("username")) if Bcrypt.check_password_hash(db_user["password"], user["password"]): out = { "username": db_user["username"], "email": db_user["email"], "group": db_user["group"] } return {"msg": "Successful login", "data": out}, 200 else: return {"msg": "Unsuccessful login"} except Exception as e: return { "msg": f"Error trying to authenticate user {user['username']}", "Error": e }, 422
def validate_password(cls, email, password): owners = cls.query.filter_by(email=email).first() passwordcheck = bcrypt.check_password_hash(owners.password, password) db.session.close() if owners and passwordcheck: return True else: return False
class BasicTestCase(unittest.TestCase): def setUp(self): app = flask.Flask(__name__) app.config['BCRYPT_LOG_ROUNDS'] = 6 app.config['BCRYPT_HASH_IDENT'] = '2b' self.bcrypt = Bcrypt(app) def test_is_string(self): pw_hash = self.bcrypt.generate_password_hash('secret') if PY3: self.assertTrue(isinstance(pw_hash, bytes)) else: self.assertTrue(isinstance(pw_hash, str)) def test_custom_rounds(self): password = '******' pw_hash1 = self.bcrypt.generate_password_hash(password, 5) self.assertNotEqual(password, pw_hash1) def test_check_hash(self): pw_hash = self.bcrypt.generate_password_hash('secret') # check a correct password self.assertTrue(self.bcrypt.check_password_hash(pw_hash, 'secret')) # check an incorrect password self.assertFalse(self.bcrypt.check_password_hash(pw_hash, 'hunter2')) # check unicode pw_hash = self.bcrypt.generate_password_hash(u'\u2603') self.assertTrue(self.bcrypt.check_password_hash(pw_hash, u'\u2603')) # check helpers pw_hash = generate_password_hash('hunter2') self.assertTrue(check_password_hash(pw_hash, 'hunter2')) def test_check_hash_unicode_is_utf8(self): password = u'\u2603' pw_hash = self.bcrypt.generate_password_hash(password) # check a correct password self.assertTrue( self.bcrypt.check_password_hash(pw_hash, b'\xe2\x98\x83')) def test_rounds_set(self): self.assertEqual(self.bcrypt._log_rounds, 6) def test_unicode_hash(self): password = u'東京' h = generate_password_hash(password).decode('utf-8') self.assertTrue(check_password_hash(h, password))
class BasicTestCase(unittest.TestCase): def setUp(self): app = flask.Flask(__name__) app.config['BCRYPT_LOG_ROUNDS'] = 6 app.config['BCRYPT_HASH_IDENT'] = '2b' self.bcrypt = Bcrypt(app) def test_is_string(self): pw_hash = self.bcrypt.generate_password_hash('secret') if PY3: self.assertTrue(isinstance(pw_hash, bytes)) else: self.assertTrue(isinstance(pw_hash, str)) def test_custom_rounds(self): password = '******' pw_hash1 = self.bcrypt.generate_password_hash(password, 5) self.assertNotEqual(password, pw_hash1) def test_check_hash(self): pw_hash = self.bcrypt.generate_password_hash('secret') # check a correct password self.assertTrue(self.bcrypt.check_password_hash(pw_hash, 'secret')) # check an incorrect password self.assertFalse(self.bcrypt.check_password_hash(pw_hash, 'hunter2')) # check unicode pw_hash = self.bcrypt.generate_password_hash(u'\u2603') self.assertTrue(self.bcrypt.check_password_hash(pw_hash, u'\u2603')) # check helpers pw_hash = generate_password_hash('hunter2') self.assertTrue(check_password_hash(pw_hash, 'hunter2')) def test_check_hash_unicode_is_utf8(self): password = u'\u2603' pw_hash = self.bcrypt.generate_password_hash(password) # check a correct password self.assertTrue(self.bcrypt.check_password_hash(pw_hash, b'\xe2\x98\x83')) def test_rounds_set(self): self.assertEqual(self.bcrypt._log_rounds, 6) def test_unicode_hash(self): password = u'東京' h = generate_password_hash(password).decode('utf-8') self.assertTrue(check_password_hash(h, password))
def validate_password(cls, email, password): customer = cls.query.filter_by(email=email).first() if customer and bcrypt.check_password_hash(customer.password, password): return True else: return False
def authenticate(cls, username, password): """Register user w/hashed password & return user.""" u = User.query.filter_by(username=username).first() bcrypttt = Bcrypt() if u and bcrypttt.check_password_hash(u.password, password): return u else: return False
class Encryption(object): def __init__(self): self.bcrypt = Bcrypt() def hash_pwd(self, pwd: str): return self.bcrypt.generate_password_hash(pwd).decode('utf-8') def check_pwd(self, saved_pwd: str, inserted_pwd: str): return self.bcrypt.check_password_hash(saved_pwd, inserted_pwd)
def post(self): try: parser = reqparse.RequestParser() parser.add_argument('ausername', type = str, required = True, help = 'username cannot be left blank') parser.add_argument('aoldpassword', type = str, required = True, help = 'old password cannot be left blank') parser.add_argument('anewpassword', type = str) parser.add_argument('aname', type = str) parser.add_argument('adept', type = str) parser.add_argument('aemail', type = str) parser.add_argument('aphone', type = str) data = parser.parse_args() except: return {"message":"error in parsing data"},400 try: bcrypt = Bcrypt() adminuser = AdminUser.getAdminUserByAusername(data['ausername']) if not(adminuser and bcrypt.check_password_hash(adminuser.apassword, data['aoldpassword'])): return {"message":"Wrong password"} except: return {"message":"Error in editing details3"},500 try: if data['anewpassword'] == None: data['anewpassword'] = adminuser.apassword else: apassword_hash = bcrypt.generate_password_hash(data['anewpassword']).decode('utf-8') if data['aname'] == None: data['aname'] = adminuser.aname if data['adept'] == None: data['adept'] = adminuser.adept if data['aemail'] == None: data['aemail'] = adminuser.aemail if data['aphone'] == None: data['aphone'] = adminuser.aphone except: return {"message":"Error in editing details2"},500 try: x=query(f"""SELECT * FROM ADMINS WHERE ausername = '******'""",return_json=False) if len(x)>0: query(f"""UPDATE ADMINS SET apassword='******', aname='{data['aname']}', adept='{data['adept']}', aemail='{data['aemail']}', aphone='{data['aphone']}' WHERE ausername = '******'ausername']}'""") return {"message" : "Details are edited successfully!"},200 return {"message" : "Srollno doesn't exist"},400 except: return{"message" : "Error in editing details1"},500
class AuthService: HS256 = "HS256" UTF8 = "utf-8" def __init__(self, auth_repository: AuthRepository) -> None: self.logger = Logger(__name__) self.auth_repository = auth_repository self.bcrypt = Bcrypt() def login(self, fields: Dict, hash_passowrd: str) -> Optional[Auth]: email = fields["email"] password = fields["password"] # Check hashed password is_valid = self.bcrypt.check_password_hash(hash_passowrd, password) if not is_valid: raise AuthNotValidException("Not valid field values") token = self._encode_token(email, password) auth = self.auth_repository.find_by_token(token) if not auth: # Create token auth_fields = {"token": token, "email": email} auth = self.auth_repository.create(auth_fields) return auth def validate(self, authorization: str) -> Optional[Auth]: token = authorization.split()[1] auth = self.auth_repository.find_by_token(token) # TODO Check created_at return auth def create(self, fields: Dict) -> Optional[Auth]: auth_fields = {'token': fields['token'], 'email': fields['email']} auth = self.auth_repository.create(auth_fields) return auth def delete(self, id_: str) -> Optional[Auth]: auth = self.auth_repository.find(id_) if auth: self.auth_repository.delete(auth) return auth def _encode_token(self, email: str, password: str) -> str: payload = {'email': email, 'password': password} token = jwt.encode(payload, Config.APP_NAME, algorithm=self.HS256).decode(self.UTF8) return token def _decode_token(self, token: str) -> Dict: payload = jwt.decode(token.encode(self.UTF8), Config.APP_NAME, algorithm=self.HS256) return payload
def authenticate(cls, email, password): """ Returns True if user exists and password matches hash, else False """ bcrypt = Bcrypt() user = User.query.filter_by(email=email).first() if user and bcrypt.check_password_hash(user.password, password): return True else: return False
def login(): email = request.form['email'] password = request.form['password'] user = Users.query.filter_by(email=email).first() bcrypt = Bcrypt() if user and bcrypt.check_password_hash(user.password, password): login_user(user) return redirect('/home') else: return redirect('/')
def login_data_check(id, epass): bcrypt = Bcrypt(app) emailList = sign_up_data.query.filter_by(emailAddress=id).first() if emailList is not None and bcrypt.check_password_hash( emailList.emailPassword, epass): login_user(emailList) return redirect(url_for('home_online_halwaai')) else: flash('Username or Password is incorrect') return redirect(url_for('login_online_halwaai'))
def auth(): content = request.json u = User.query.filter_by(username=content['username']).first_or_404() bcrypt = Bcrypt() if not bcrypt.check_password_hash(u.password, content['password']): return jsonify("invalid credentials"), 401 expires = timedelta(hours=4) access_token = create_access_token(identity=u.api_key, expires_delta=expires) return jsonify({"token": access_token})
class Authenticator: bcrypt = None def set_app(self, app): self.bcrypt = Bcrypt(app) def make_hash(self, val): return self.bcrypt.generate_password_hash(val) def check_hash(self, true, val): return self.bcrypt.check_password_hash(true, val)
def login(): form = LoginForm() if form.validate_on_submit(): sleep(3) user = form.user.data.strip() userRow = DBAccess.ExecuteSQL( "select email, password, first_name, surname, id, level,salt from " "users where trim(email) ilike %s", (user, ), ) if userRow is None: flash("Uživatel nenalezen", FlashStyle.Danger) return render_template("login.html", form=form) userRow = userRow[0] # execute sql gets list with one item, ie:[(email, password, first_name, # surname, id)], we need just (), ie tuple salt = userRow[6] def addSalt(passwordArg): return passwordArg + salt #md5Pass = hashlib.md5(addSalt(str(form.password.data)).encode()).hexdigest() bcrypt = Bcrypt() #bcryptHash = bcrypt.generate_password_hash(addSalt(str(form.password.data))) # check if second item is equal to hashed password try: if bcrypt.check_password_hash(userRow[1], form.password.data) == False: flash("Špatné heslo", FlashStyle.Danger) return render_template("login.html", form=form) except: flash("Špatné heslo", FlashStyle.Danger) return render_template("login.html", form=form) if userRow[5] == 0: flash( "Uživatel není ověřen, počkejte prosím na ověření" " administrátorem stránek.", FlashStyle.Danger) return render_template("login.html", form=form) session["user"] = user session["id_user"] = userRow[4] session["level_user"] = userRow[5] dbUser = DBAccess.GetDBUserById(userRow[4]) dbUser.SaveToSession('dbUser') # flash("Uživatel/ka {0} {1} přihlášen/a".format(userRow[2], userRow[3]), FlashStyle.Success) return redirect(url_for("overview_bp.prehled_all")) return render_template("login.html", form=form)
def test_create_User(self): '''A user is successfully created with the specified information''' from flask_bcrypt import Bcrypt bcrypt = Bcrypt() self.signup_user() self.assertEqual(self.testuser3.username, 'testuser3') self.assertEqual( bcrypt.check_password_hash(self.testuser3.password, "123456"), True) self.assertEqual(self.testuser3.email, '*****@*****.**') self.assertEqual(self.testuser3.image_url, '/test.jpg')
def login(): """For GET requests, display the login form. For POSTS, login the current user by processing the form.""" bcrypt = Bcrypt(app) form = LoginForm() if form.validate_on_submit(): user = User.query.get(form.email.data) if user: if bcrypt.check_password_hash(user.password, form.password.data) and user.is_active: flash("Successfully logged in as %s" % user.email, 'success') user.authenticated = True db.session.add(user) db.session.commit() login_user(user, remember=True) return redirect(url_for('index')) else: if user.is_active: form.password.errors.append('invalid') else: form.password.errors.append('locked') return render_template("login.html", form=form)
class AuthModule(): def __init__(self, app, usersCollection): self.usersCollection = usersCollection self.bcrypt = Bcrypt(app) app.config['SECRET_KEY'] = SECRET app.config['JWT_AUTH_USERNAME_KEY'] = 'email' app.config['JWT_EXPIRATION_DELTA'] = timedelta(seconds=7*24*60*60) # 7 days class User(object): def __init__(self, id, username, password, name): self.id = username self.username = username self.name = name self.password = password def __str__(self): return "User(id='%s')" % self.id def authenticate(self, username, password): user = list(self.usersCollection.find({"_id":username})).pop() if user and self.bcrypt.check_password_hash(user.get("password"), password): return self.User(user.get("_id"), user.get("_id"), user.get("password"), user.get("name")) return def identity(self, payload): user_id = payload['identity'] user = list(self.usersCollection.find({"_id":user_id})).pop() return self.User(user.get("_id"), user.get("_id"), user.get("password"), user.get("name")) def registerUser(self, request): jsonData = request.json user = { '_id': jsonData['email'], 'password': self.bcrypt.generate_password_hash(jsonData['password']), 'name': jsonData['displayName'] } id = self.usersCollection.insert_one(user).inserted_id return jsonify({'id':id})
email = request.form['email'] username = request.form['username'] password = request.form['password'] # run validations and if they are successful we can create the password hash with bcrypt pw_hash = bcrypt.generate_password_hash(password) # now we insert the new user into the database insert_query = "INSERT INTO users (email, username, pw_hash, created_at) VALUES (:email, :username, :pw_hash, NOW())" query_data = { 'email': email, 'username': username, 'pw_hash': pw_hash } mysql.query_db(insert_query, query_data) # redirect to success page # check password hash password = '******' pw_hash = bcrypt.generate_password_hash(password) test_password_1 = 'thisiswrong' bcrypt.check_password_hash(pw_hash, test_password_1) # this will return false test_password_2 = 'password' bcrypt.check_password_hash(pw_hash, test_password_2) # this will return true # try checking password at login @app.route('/login', methods=['POST']) def login(): email = request.form['email'] password = request.form['password'] user_query = "SELECT * FROM users WHERE email = :email LIMIT 1" query_data = { 'email': email } user = mysql.query_db(user_query, query_data) # user will be returned in a list if bcrypt.check_password_hash(user[0]['pw_hash'], password): # login user pass else:
def password_exist(self, password): bcrypt = Bcrypt(None) user = user_reader.get_by_id(self._id) return bcrypt.check_password_hash(user.password, password)