def validate_login(self, username: str, password: str) -> None: """Validate a username and password. Raises InvalidAuth if auth invalid. """ username = self.normalize_username(username) dummy = b'$2b$12$CiuFGszHx9eNHxPuQcwBWez4CwDTOcLTX5CbOpV6gef2nYuXkY7BO' found = None # Compare all users to avoid timing attacks. for user in self.users: if self.normalize_username(user['username']) == username: found = user if found is None: # check a hash to make timing the same as if user was found bcrypt.checkpw(b'foo', dummy) raise InvalidAuth user_hash = base64.b64decode(found['password']) # bcrypt.checkpw is timing-safe if not bcrypt.checkpw(password.encode(), user_hash): raise InvalidAuth
def test_checkpw_extra_data(): salt = bcrypt.gensalt(4) hashed = bcrypt.hashpw(b"abc", salt) assert bcrypt.checkpw(b"abc", hashed) assert bcrypt.checkpw(b"abc", hashed + b"extra") is False assert bcrypt.checkpw(b"abc", hashed[:-10]) is False
def test_checkpw_nul_byte(): with pytest.raises(ValueError): bcrypt.checkpw( b"abc\0def", b"$2b$04$2Siw3Nv3Q/gTOIPetAyPr.GNj3aO0lb1E5E9UumYGKjP9BYqlNWJe" ) with pytest.raises(ValueError): bcrypt.checkpw( b"abcdef", b"$2b$04$2S\0w3Nv3Q/gTOIPetAyPr.GNj3aO0lb1E5E9UumYGKjP9BYqlNWJe" )
def loga(request, login): form = LoginForm(login) global t t += 1 if t <= 3: print(t) if form.is_valid(): email = form.cleaned_data["email"] senha = form.cleaned_data["senha"] user = usuario_por_email(email) senha_user = user["senha"] if user and type(user) != int: if bcrypt.checkpw(senha.encode(), senha_user.encode()): usuario = usuario_por_id(user["id"]) request.session["user"] = usuario if user["perfil"]["id"] == 1: request.session.set_expiry(600) if user["perfil"]["id"] == 2: request.session.set_expiry(300) if user["perfil"]["id"] == 3: request.session.set_expiry(0) t = 0 else: return HttpResponse("OPS! Senha incorreta, tente novamente") elif type(user) == int: return HttpResponse("404") else: return HttpResponse("OPS! Parece que esse usuário não existe em nosso sistema. Contate o seu administrador") else: return form.errors else: return HttpResponse("Parece que você tentou muito entrar! Contate o admnistrador")
def authenticate(self, password=None, google_token=None): if google_token: # TODO best practices on secure, reversible, token storage # TODO token refresh return self.google_token == google_token else: return bcrypt.checkpw(password or '', self.password or '')
def login(self, user, password): """Login as the specified user with the specified password. Args: user (str): The user ID. password (str): The password. Returns: The newly allocated access token. Raises: StoreError if there was a problem storing the token. LoginError if there was an authentication problem. """ # TODO do this better, it can't go in __init__ else it cyclic loops if not hasattr(self, "reg_handler"): self.reg_handler = self.hs.get_handlers().registration_handler # pull out the hash for this user if they exist user_info = yield self.store.get_user_by_id(user_id=user) if not user_info: logger.warn("Attempted to login as %s but they do not exist", user) raise LoginError(403, "", errcode=Codes.FORBIDDEN) stored_hash = user_info[0]["password_hash"] if bcrypt.checkpw(password, stored_hash): # generate an access token and store it. token = self.reg_handler._generate_token(user) logger.info("Adding token %s for user %s", token, user) yield self.store.add_access_token_to_user(user, token) defer.returnValue(token) else: logger.warn("Failed password login for user %s", user) raise LoginError(403, "", errcode=Codes.FORBIDDEN)
def log(self, form_data): errors=[] if len(form_data["email"]) < 1: errors.append("Email is required") elif not EMAIL_REGEX.match(form_data["email"]): errors.append("Invalid Email") else: if len(User.objects.filter(email=form_data["email"].lower())) < 1: errors.append("Login Failed") if len(form_data["password"]) < 1: errors.append("Password is required") elif len(form_data["password"]) < 8: errors.append("Password must be 8 letters or longer") if len(errors) > 0: return (False, errors) user = User.objects.filter(email=form_data["email"].lower())[0] hashed_pw = user.password.split("'")[1] if bcrypt.checkpw(form_data["password"].encode(), hashed_pw.encode()): return (True, user) else: errors.append("Invalid Login") return (False, errors)
def delete(self, password, force=False): if not force and not bcrypt.checkpw(password.encode('utf-8'), self.edit_pass.encode('utf-8')): raise Polycule.PermissionDenied cur = self._db.cursor() cur.execute('delete from polycules where id = ?', [self.id]) self._db.commit()
def login(request): if 'is_logged_in' not in request.session: request.session['is_logged_in'] = False elif request.session["is_logged_in"] is True: messages.error(request, "You are aready logged in") return redirect("/success") elif request.method == "POST": try: user = User.objects.get(email=request.POST["email"]) except User.DoesNotExist: messages.error(request, "Email does not exist") else: passed_pswd = request.POST['password'] if bcrypt.checkpw(passed_pswd.encode(), user.password.encode()): request.session['is_logged_in'] = True request.session['user_id'] = user.id request.session["first_name"] = user.first_name request.session['last_name'] = user.last_name request.session['email'] = user.email request.session['created_at'] = user.created_at.strftime( "%I:%M %p %B $d, %Y" ) request.session['changed_at'] = user.changed_at.strftime( "%I:%M %p %B $d, %Y" ) messages.success(request, "Successful Login") return redirect("/success") else: messages.error( request, "Either Email or Password or both is not correct" ) return render( request, "log_reg_app/login_reg.html", {"old_form": request.POST} )
def authenticate(self, user, passw): for user in self.passwords: print(user) stored_user, sep, stored_password = user.partition(":") if stored_user.lower() == stored_user.lower(): return bcrypt.checkpw(stored_password, passw) return False
def OnOk(self, _): if config.current_section is None: self.sizer.Hide(self.creche_sizer) self.sizer.Hide(self.btnsizer) self.sizer.Show(self.gauge) self.sizer.Layout() self.sizer.Fit(self) section = self.creche_ctrl.GetStringSelection() self.info.AppendText("Structure %s sélectionnée.\n" % section) config.set_current_section(section) wx.CallAfter(self.Load, section) return login = self.login_ctrl.GetValue() password = self.passwd_ctrl.GetValue().encode("utf-8") for user in database.creche.users: hashed = user.password.encode("utf-8") if login == user.login and bcrypt.checkpw(password, hashed): config.profil = user.profile if user.profile & PROFIL_LECTURE_SEULE: if config.server: config.server.close() config.readonly = True self.StartFrame() return else: self.login_ctrl.Clear() self.passwd_ctrl.Clear() self.login_ctrl.SetFocus()
def check_auth(user, password): """ :type: User, string :rtype: boolean """ #print password.encode('utf-8'), user.password.encode('utf-8'), bcrypt.checkpw(password.encode('utf-8'), user.password.encode('utf-8')) return bcrypt.checkpw(password.encode('utf-8'), user.password.encode('utf-8'))
async def login(req): stmt = await shared.postgres.prepare("SELECT userid, password, is_verified, is_admin FROM get_user_by_login($1);") user = await stmt.fetchrow(req.json["login"]) if all(map(lambda v: v is None, user.values())): logger.warning(f'User \'{req.json["login"]}\' not found') raise Forbidden("User not found") if not user["is_verified"]: logger.warning(f'User \'{req.json["login"]}\' is not verified yet') raise Forbidden("You must verify your email first") if not bcrypt.checkpw(req.json["password"].encode(), user["password"]): logger.log(45, f'Password for User \'{req.json["login"]}\' does not match (IP: {req.ip})') raise Forbidden("Incorrect password") jwt = jwtlib.encode({ "iss": ClientType.WEBAPI.value, "sub": "webgames", "iat": datetime.utcnow(), "exp": datetime.utcnow() + JWT_EXPIRATION_TIME, "tid": str(uuid4()), "type": ClientType.ADMIN.value if user["is_admin"] else ClientType.USER.value, "id": str(user["userid"]) }, JWT_SECRET) logger.info(f"Generated token: {jwt}") return json({"id": str(user["userid"]), "token": jwt})
def verifySession(self, user, password): self.connectBD() #Password Encriptada hashed = bcrypt.hashpw(password, bcrypt.gensalt()) #print "My password: "******" user: "******" pass: "******"username":user, "estado":"Activo"},{"tipo":1,"codtarjeta":1,"_id":1, "nombre":1, "apellido1":1, "password":1})) #Verifica el username if len(listTem) <= 0: return "faildUser" else: resultBD = listTem[0] #Verifica el password if bcrypt.checkpw(password, str(resultBD["password"])): # La contrasena es corrrecta por lo que # verifica si tiene rol de administrador admin = False for tem in list(resultBD["tipo"]): if tem == "Administrador": admin = True if admin == False: return "faildPermission" else: return "success" else: return "faildPassword"
def account_check(username, password, request): settings = request.registry.settings hmac_secret = settings['userid_hmac_secret'] cache_key = utils.hmac_digest(hmac_secret, ACCOUNT_CACHE_KEY.format(username)) cache_ttl = int(settings.get('account_cache_ttl_seconds', 30)) hashed_password = utils.hmac_digest(cache_key, password) # Check cache to see whether somebody has recently logged in with the same # username and password. cache = request.registry.cache cache_result = cache.get(cache_key) # Username and password have been verified previously. No need to compare hashes if cache_result == hashed_password: # Refresh the cache TTL. cache.expire(cache_key, cache_ttl) return True # Back to standard procedure parent_id = username try: existing = request.registry.storage.get(parent_id=parent_id, collection_id='account', object_id=username) except storage_exceptions.RecordNotFoundError: return None hashed = existing['password'].encode(encoding='utf-8') pwd_str = password.encode(encoding='utf-8') # Check if password is valid (it is a very expensive computation) if bcrypt.checkpw(pwd_str, hashed): cache.set(cache_key, hashed_password, ttl=cache_ttl) return True
def system_api_auth(): hostname = request.form['hostname'] api_key = request.form['api_key'] app.logger.debug("system_api_auth: request to auth " + hostname) # Locate the hostname in the database curd = g.db.cursor(mysql.cursors.DictCursor) curd.execute("SELECT * FROM `systems` WHERE `name` = %s",(request.form['hostname'].lower(),)) system = curd.fetchone() ## that hostname is not valid, no such system! if system == None: abort(404) if isinstance(api_key, unicode): api_key = api_key.encode('utf8') if isinstance(system['api_key'], unicode): system['api_key'] = system['api_key'].encode('utf8') ## check the API key - its bcrypt encrypted in the DB if bcrypt.checkpw(api_key, system['api_key']): return system else: abort(403)
def __eq__(self, value): if not self.hash or not value: # For security reasons we never consider an empty password/hash valid return False if isinstance(value, unicode): value = value.encode('utf-8') return bcrypt.checkpw(value, self.hash)
def login(): if request.method == 'GET': if current_user: return redirect("/") reset = request.args.get('reset') == '1' return render_template("login.html", **{ 'return_to': request.args.get('return_to'), 'reset': reset, "site_name": _cfg('site-name'), "support_mail": _cfg('support-mail') }) else: username = request.form['username'] password = request.form['password'] remember = request.form.get('remember-me') if remember == "on": remember = True else: remember = False user = User.query.filter(User.username.ilike(username)).first() if not user: return render_template("login.html", **{ "username": username, "errors": 'Your username or password is incorrect.', "site_name": _cfg('site-name'), "support_mail": _cfg('support-mail') }) if user.confirmation != '' and user.confirmation != None: return redirect("/account-pending") if not bcrypt.checkpw(password, user.password): return render_template("login.html", **{ "username": username, "errors": 'Your username or password is incorrect.', "site_name": _cfg('site-name'), "support_mail": _cfg('support-mail') }) login_user(user, remember=remember) if 'return_to' in request.form and request.form['return_to']: return redirect(urllib.parse.unquote(request.form.get('return_to'))) return redirect("/")
def test_store_recovery_codes(): user_id = db_utils.create_user() valid_code_string = "01234567890123456789,02234567890123456789,03234567890123456789,04234567890123456789,05234567890123456789,06234567890123456789,07234567890123456789,08234567890123456789,09234567890123456789,10234567890123456789" _insert_recovery_code(user_id) # store_recovery_codes() will not accept a string of codes where the total code count is not 10 invalid_codes = valid_code_string.split(',').pop() assert not tfa.store_recovery_codes(user_id, ','.join(invalid_codes)) # store_recovery_codes() will not accept a string of codes when the code length is not tfa.LENGTH_RECOVERY_CODE invalid_codes = "01,02,03,04,05,06,07,08,09,10" assert not tfa.store_recovery_codes(user_id, invalid_codes) # When a correct code list is provided, the codes will be stored successfully in the database assert tfa.store_recovery_codes(user_id, valid_code_string) # Extract the current hashed recovery codes query = d.engine.execute(""" SELECT recovery_code_hash FROM twofa_recovery_codes WHERE userid = %(userid)s """, userid=user_id).fetchall() # Ensure that the recovery codes can be hashed to the corresponding bcrypt hash valid_code_list = valid_code_string.split(',') for row in query: code_status = False for code in valid_code_list: if bcrypt.checkpw(code.encode('utf-8'), row['recovery_code_hash'].encode('utf-8')): # If the code matches the hash, then the recovery code stored successfully code_status = True break # The code must be valid assert code_status
def auth(): unauthorized = make_response('', 401) data = request.get_json() username = '' if 'username' in data: username = data['username'] password = '' if 'password' in data: password = data['password'] user = db.session.query(Users).filter(Users.username == username).first() if user and bcrypt.checkpw(password, user.password): hash = hashlib.sha1() hash.update(os.urandom(128)) token = hash.hexdigest() db.session.add(Tokens(token = hash.hexdigest(), admin = user.admin, expires = int(time.time()) + 3600)) db.session.commit() return jsonify({ "token" : token, "admin" : user.admin }) else: return unauthorized
def validate_userPassword(username,password): if PredictiveUsers.objects.filter(username=username).exists(): user = PredictiveUsers.objects.filter(username=username).first() if not (bcrypt.checkpw(password.encode('utf-8'), user.password.encode('utf-8'))): raise forms.ValidationError(u'Invalid password.') return password
def login(): error = None if 'name' in session: #check if usr is already logged in return redirect('/') if request.method == 'POST': u = User() u.name = request.form['username'].lower() u = get_user(u) if u is None: error = 'User does not exist!' return render_template('login.html', error=error, user=get_user_by_name(session.get('name'))) #if u.password != request.form['password']: # bcrypt.checkpy(plaintxt, hash) if not bcrypt.checkpw(request.form['password'], u.password): error = 'Wrong password!' return render_template('login.html', error=error, user=get_user_by_name(session.get('name'))) session['name'] = u.name return redirect('/') return render_template('login.html', error=error, user=get_user_by_name(session.get('name')))
def selfmanagement(): if request.method == 'POST': u = get_user_by_name(session.get('name')) if not bcrypt.checkpw(request.form['password_old'], u.password): success = "Passwort falsch!" else: if ('password1' in request.form) & ('password2' in request.form): if request.form['password1'] == request.form['password2']: u.password = bcrypt.hashpw(request.form['password1'], bcrypt.gensalt()) u.rfid_id = request.form['rfid_id'] if 'onlyrfid' in request.form: u.onlyrfid = True else: u.onlyrfid = False update_user(u) success = u'Einstellungen wurden übernommen!' else: success = u'Neue Passwörter stimmen nicht überein!' else: u.rfid_id = request.form['rfid_id'] if 'onlyrfid' in request.form: u.onlyrfid = True else: u.onlyrfid = False update_user(u) success = u'Einstellungen wurden übernommen!' return render_template('selfmanagement.html', success=success, user=get_user_by_name(session.get('name'))) if request.method == 'GET': return render_template('selfmanagement.html', user=get_user_by_name(session.get('name')))
def passwordValid(appuser, password): '''Check if master pass is valid.''' pwHash, salt = getMasterPass(appuser) if bcrypt.checkpw(password, pwHash): return True else: return False
def post(self, **kwargs): args = login_parser.parse_args() username, password = args["username"], args["password"] user_obj = User() try: user = user_obj.get_by_username(username) # compare input password with password in db if bcrypt.checkpw(password.encode('utf8'), bytes(user.password.encode())): login_user(user) # if login success save login history login_history = LoginHistory(user=user.dbUser) login_history.save() user_id = str(user.id) data = { "success": True, "id": user_id, "next": url_for('bp_index.show') } return data, 200 else: data = { "success": False, "error": "Wrong username or password" } return data, 401 except Exception as exc: logger.info("error {}".format(exc)) data = { "success": False, "error": "login failed" } return data, 401
def password_matches(user, password): hashed = user.password if type(hashed) is str: hashed = hashed.encode() if type(password) is str: password = password.encode() return bcrypt.checkpw(password, hashed)
async def verify_hash(self, pw_hash, password): assert isinstance(pw_hash, str) assert isinstance(password, str) loop = asyncio.get_event_loop() check = lambda: bcrypt.checkpw(password.encode(), pw_hash.encode()) matches = await loop.run_in_executor(None, check) return matches
def bcrypt_check_pw(self, password_string, hashed_pw_str): """ Bcrypt-based password checker. Takes a raw string password and compares it to the hash of a previously hashed password, returning True if the passwords match, or False if not. Bcrypt functions are to be used where ever you are storing a user's password, but do not ever want to be able to "know" their password directly. We only need to know if the password they supplied is correct or not. If bcrypt is not installed on the system, the comparison is just a comparison of the two supplied strings. :Args: :passphrase: 32 URL-safe Base64 encoded bytes :data: string data or password to encrypt :encoding: encoding (string). :returns: a string repr of the encrypted data """ if not bcrypt: print( "\x1b\x5b\x33\x33\x6dWARNING! Package `bcrypt` is not installed" ". Therefore, `crypt` is only doing a string comparison of the " "'hash' and the 'password'! \x1b\x5b\x30\x6d" ) if password_string == hashed_pw_str: return True else: return False password_bytes = py_bytes(password_string, self.encoding) hashed_pw = py_bytes(hashed_pw_str, self.encoding) return bcrypt.checkpw(password_bytes, hashed_pw)
def _check_password(password1, password2): password1 = bytes(password1, 'utf-8') password2 = bytes(password2, 'utf-8') try: return bcrypt.checkpw(password1, password2) except ValueError: return False
def _do_validate_hash(): # Normalise the Unicode in the password pw = unicodedata.normalize("NFKC", password) return bcrypt.checkpw( pw.encode('utf8') + self.hs.config.password_pepper.encode("utf8"), stored_hash )
def test_checkpw_bad_salt(): with pytest.raises(ValueError): bcrypt.checkpw( b"badpass", b"$2b$04$?Siw3Nv3Q/gTOIPetAyPr.GNj3aO0lb1E5E9UumYGKjP9BYqlNWJe")
def test_checkpw_str_salt(): with pytest.raises(TypeError): bcrypt.checkpw( b"password", six.text_type("$2b$04$cVWp4XaNU8a4v1uMRum2SO"), )
def validate_password_hash(self, password): if self.password_hash: return bcrypt.checkpw(password.encode("utf8"), self.password_hash) return False
def check_bcrypt(hashed, password): return bcrypt.checkpw(preprocess_password(password), base64.b64decode(hashed.encode('ascii')))
def verify_password(self, password): return bcrypt.checkpw(password.encode("utf8"), self.password_digest)
def check_password(plain_text_password, hashed_text_password): hashed_bytes_password = hashed_text_password.encode("utf-8") # Check hased password. Useing bcrypt, the salt is saved into the hash itself return bcrypt.checkpw(plain_text_password.encode('utf-8'), hashed_bytes_password)
def pass_checker(old, password): return bcrypt.checkpw(old.encode(), password)
def check_password(self, pw): if self.password_hash is not None: expected_hash = self.password_hash.encode('utf8') return bcrypt.checkpw(pw.encode('utf8'), expected_hash) return False
def check_password(password, hashed): return bcrypt.checkpw(password, hashed)
def verify_password(self, password): return bcrypt.checkpw(password.encode('utf-8'), self.password.encode('utf-8'))
def autenticate(username, password): user = User.query.filter(User.username == username).first() if user and bcrypt.checkpw(password.encode('utf-8'), user.password.encode('utf-8')): return user
def compare_password(password, hashed_password): return bcrypt.checkpw(password.encode(), hashed_password.encode())
def validate_password(given_password, saved_password): hash = bcrypt.checkpw(given_password.encode(), saved_password.encode()) return hash
def test_checkpw_wrong_password(): assert bcrypt.checkpw( b"badpass", b"$2b$04$2Siw3Nv3Q/gTOIPetAyPr.GNj3aO0lb1E5E9UumYGKjP9BYqlNWJe" ) is False
def password_is_correct(self, password): return bcrypt.checkpw(password.encode('utf-8'), self.password.encode('utf-8'))
def check_password(self, pw): if self.password_hash is None: return False expected_hash = self.password_hash.encode("utf8") return bcrypt.checkpw(pw.encode("utf8"), expected_hash)
def login(): # Output message if something goes wrong... msg = '' # Creating all the db and tables needed can add your if necessary cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor) cursor.execute('''CREATE TABLE IF NOT EXISTS accounts( id INT(11) NOT NULL PRIMARY KEY AUTO_INCREMENT, username VARCHAR(250) NOT NULL UNIQUE, firstname VARCHAR(250) NOT NULL, lastname VARCHAR(250) NOT NULL, password VARCHAR(250) NOT NULL, email VARCHAR(250) NOT NULL UNIQUE, vkey VARCHAR(250) NOT NULL, picture VARCHAR(500) NOT NULL DEFAULT 'profile.jpg', user_valid TINYINT(1) NOT NULL DEFAULT '0' )''') print("Table created: accounts") cursor.execute(''' CREATE TABLE IF NOT EXISTS profiles( id INT(11) NOT NULL PRIMARY KEY AUTO_INCREMENT, user_id INT(11) NOT NULL UNIQUE, gender VARCHAR(250) NOT NULL, sexual_orientation VARCHAR(250) NOT NULL, bio VARCHAR(250) NOT NULL, nature TINYINT(1) DEFAULT '0', art TINYINT(1) DEFAULT '0', music TINYINT(1) DEFAULT '0', sports TINYINT(1) DEFAULT '0', memes TINYINT(1) DEFAULT '0', age1 TINYINT(1) DEFAULT '0', age2 TINYINT(1) DEFAULT '0', age3 TINYINT(1) DEFAULT '0', FOREIGN KEY(user_id) REFERENCES accounts(id) )''') print("Table created: profiles") cursor.execute(''' CREATE TABLE IF NOT EXISTS images( id INT(11) NOT NULL PRIMARY KEY AUTO_INCREMENT, user_id INT(11) NOT NULL, image_path VARCHAR(500) NOT NULL, FOREIGN KEY(user_id) REFERENCES accounts(id) )''') print("Table created: images") cursor.execute(''' CREATE TABLE IF NOT EXISTS popularity( id INT(11) NOT NULL PRIMARY KEY AUTO_INCREMENT, profile_id INT(11) NOT NULL, upvote INT NOT NULL DEFAULT '1', FOREIGN KEY(profile_id) REFERENCES accounts(id) )''') print("Table created: popularity") cursor.execute(''' CREATE TABLE IF NOT EXISTS likes( id INT(11) NOT NULL PRIMARY KEY AUTO_INCREMENT, user_id INT(11) NOT NULL, profile_id INT(100) NOT NULL, action TINYINT(1) DEFAULT '0', created_at DATETIME DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY(user_id) REFERENCES accounts(id), FOREIGN KEY(profile_id) REFERENCES accounts(id) )''') print("Table created: likes") cursor.execute('''CREATE TABLE IF NOT EXISTS notification( id INT(11) NOT NULL PRIMARY KEY AUTO_INCREMENT, name VARCHAR(128), user_id INT(100) NOT NULL, created_at DATETIME DEFAULT CURRENT_TIMESTAMP, payload_json TEXT, FOREIGN KEY(user_id) REFERENCES accounts(id) )''') print("Table created: notifications") cursor.execute('''CREATE TABLE IF NOT EXISTS location( id INT(11) NOT NULL PRIMARY KEY AUTO_INCREMENT, user_id INT(100) NOT NULL, location VARCHAR(250) NULL DEFAULT 'pretoria', FOREIGN KEY(user_id) REFERENCES accounts(id) )''') print("Table created: location") # Check if "username" and "password" POST requests exist (user submitted form) if request.method == 'POST' and 'username' in request.form and 'password' in request.form: # Create variables for easy access username = request.form['username'] password = request.form['password'] # Check if account exists using MySQL cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor) cursor.execute('SELECT * FROM accounts WHERE username = %s', (username, )) # Fetch one record and return result account = cursor.fetchone() # If account exists in accounts table in out database if account: if bcrypt.checkpw(password.encode('utf-8'), account['password'].encode('utf-8')): # Create session data, we can access this data in other routes session['loggedin'] = True session['id'] = account['id'] session['username'] = account['username'] # Redirect to home page return redirect(url_for('home')) else: # Account doesnt exist or username/password incorrect msg = 'Incorrect username/password!... Please check you login details' # Show the login form with message (if any) return render_template('index.html', msg=msg)
a = '''1.LOGIN\n2.SIGNUP\nchoose 1 for LOGIN OR 2 for SIGNUP\n''' option = input(a) if option == '1': name = input('USERNAME:'******'PASSWORD:'******'{}' AND passcode='{}'".format(name, hashed_passcode)) c.execute("SELECT passcode FROM students WHERE username = '******'".format( name, )) conn.commit() data = c.fetchall() found = False for key in data: for keys in key: ignore = 0 if bcrypt.checkpw(passcode, keys): print('Logged in as ', name) found = True break if found == False: print('Wrong Username or Password') else: break if option == '2': name = input('ENTER YOUR DESIRED USERNAME: '******'{}' ".format(name)) conn.commit() data = c.fetchall() if len(data) > 0:
def is_valid(hashed_password: bytes, password: str) -> bool: """ is valid? """ return bcrypt.checkpw(password.encode('utf-8'), hashed_password)
def check_password(self, password: str) -> bool: param_bytes = str.encode(password) pw_bytes = str.encode(self.password) return bcrypt.checkpw(param_bytes, pw_bytes)
def login_is_valid(user, password): if user not in arlo_logins.keys(): return False return checkpw(password.encode(), arlo_logins[user].encode())
def check_password(plaintext_pwd, hashed_pwd): return checkpw(plaintext_pwd, hashed_pwd)
def decryptStringBcrypt(EncValidate, EncCompare): return bcrypt.checkpw(bytes(str(EncValidate), encoding='utf-8'), EncCompare)
def validate(self, data, action): # obtain form values email = data['email'] password = data['password'] if action == 'register': first_name = data['first_name'] last_name = data['last_name'] confirm_password = data['confirm_password'] # define regular expressions and error flag name_regex = re.compile(r'^[a-zA-Z]+$') email_regex = re.compile( r'^[a-zA-Z0-9.!#$%&\u2019*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)+$' ) valid = True password_regex = re.compile(r'^(?=.*[A-Z])(?=.*\d).{8,}$') messages = [] # make sure there are no blank fields for i in data: if len(data[i]) == 0: messages.append('Error: All fields are required.') valid = False break # first and last name may only contain letters if action == 'register': if len(first_name) < 2 or len(last_name) < 2: messages.append( 'Error: First and last name must contain at least two characters.' ) valid = False elif not name_regex.match(first_name) or not name_regex.match( last_name): messages.append( 'Error: First and last name may not contain numbers or special characters.' ) valid = False # email format should be valid if len(email) > 0 and not email_regex.match(email): messages.append('Error: Invalid email format.') valid = False # password must be of at least medium strength if action == 'register': if not password_regex.match(password): message = 'Error: Password must be at least 8 characters in length ' message += 'containing at least 1 uppercase letter, at least 1 number, and no spaces.' messages.append(message) valid = False # passwords should match if action == 'register': if password != confirm_password: messages.append('Error: Passwords do not match.') valid = False # check if email is registered count = User.objects.filter(email=email).count() if action == 'register' and count > 0: messages.append( 'Error: A user has already registered with that email.') valid = False # check if password matches if action == 'login': users = User.objects.filter(email=email) if len(users) == 0: messages.append( 'Error: No user has registered with that email.') valid = False elif not bcrypt.checkpw(password.encode(), str(users[0].password)): messages.append('Error: Password does not match.') valid = False # take action if valid, return error messages otherwise if valid: if action == 'register': hashed_pw = bcrypt.hashpw(password.encode(), bcrypt.gensalt()).encode() user = User.objects.create(first_name=first_name, last_name=last_name, email=email, password=hashed_pw) elif action == 'login': user = User.objects.get(email=email) return (True, user) else: return (False, messages)
def verify_password(plain_text_password, hashed_password): hashed_bytes_password = hashed_password.encode('utf-8') return bcrypt.checkpw(plain_text_password.encode('utf-8'), hashed_bytes_password)
def check_password(self, password): return bcrypt.checkpw(password.encode(), self.password_hash)
def test_checkpw_str_password(): with pytest.raises(TypeError): bcrypt.checkpw( six.text_type("password"), b"$2b$04$cVWp4XaNU8a4v1uMRum2SO", )
def check_hash(password, _hash): return bcrypt.checkpw(bytes(password, 'utf-8'), bytes(_hash, 'utf-8'))
#!/usr/bin/env python # -*- coding: utf-8 -*- from getpass import getpass from bcrypt import gensalt, hashpw, checkpw SALT = gensalt() PASSWORD = hashpw(b'abc$123', SALT) password = getpass('What is the password: '******'utf-8') if checkpw(password, PASSWORD): print('Welcome!') else: print('That password is incorrect.')
import bcrypt passwd = b'rajath' salt = bcrypt.gensalt() hashed = bcrypt.hashpw(passwd, salt) passwd = b'rajath' if bcrypt.checkpw(passwd, hashed): print("Match") else: print("Doesn't Match") print(passwd) print(salt) print(hashed)