def test_true_send_password(self): data = { Keys.PASSWORD: "******", Keys.PHONE_NUMBER: '09125200100', Keys.TYPE_USER: Keys.BUSINESS_OWNER } json_obj = json.dumps(data) with self.app as client: with client.session_transaction() as sess: sess[Keys.FORGET_PASS] = {} sess[Keys.FORGET_PASS][Keys.STATE_ID] = States.PASSWORD sess[Keys.FORGET_PASS][Keys.CODE] = data[Keys.PASSWORD] sess[Keys.FORGET_PASS][Keys.PHONE_NUMBER] = data[Keys.PHONE_NUMBER] sess[Keys.FORGET_PASS][Keys.USER_ID] = data[Keys.PHONE_NUMBER] sess[Keys.FORGET_PASS][Keys.TYPE_USER] = Keys.BUSINESS_OWNER # sess.update({Keys.FORGET_PASS: {Keys.STATE_ID: States.PASSWORD}}) response = self.make_post_request(json_obj) dct = json.loads(response.data) self.assertEqual(dct[Keys.STATUS], 200) self.assertEqual(dct[Keys.MESSAGE], Result.language.PASSWORD_CHANGE_SUCCESSFULLY) self.assertEqual(dct[Keys.PARAMS], None) # self.assertEqual(session[Keys.FORGET_PASS][Keys.STATE_ID], "") _, iws = User.find(phone_number=data[Keys.PHONE_NUMBER]) # dct = json.loads(response.data) result = pbkdf2_sha256.verify(data[Keys.PASSWORD], iws[0].password) self.assertTrue(result)
async def post(self, request): res, errs = UserSchema(exclude=['id']).load(request.json) if errs: return json({"valid": False, "data": errs}, status=400) async with request.app.db.acquire() as conn: _user = await conn.fetchrow( ''' SELECT * FROM users WHERE email=$1 ''', res['email']) if not (_user and pbkdf2_sha256.verify(res['password'], _user['password'])): return json({ "valid": False, "data": 'Wrong email or password' }, status=401) data = UserSchema(exclude=['password']).dump(_user).data token = uuid.uuid4().hex await request.app.redis.set(token, ujson.dumps(data)) return json({"valid": True, "data": {"access_token": token}})
def test_false_regex_password_3(self): data = { Keys.PASSWORD: "******", Keys.TYPE_USER: Keys.BUSINESS_OWNER, Keys.PHONE_NUMBER: '09125200100' } json_obj = json.dumps(data) with self.app as client: with client.session_transaction() as sess: sess[Keys.FORGET_PASS] = {} sess[Keys.FORGET_PASS][Keys.STATE_ID] = States.PASSWORD # sess[Keys.FORGET_PASS][Keys.CODE] = data[Keys.PASSWORD] sess[Keys.FORGET_PASS][Keys.PHONE_NUMBER] = data[Keys.PHONE_NUMBER] sess[Keys.FORGET_PASS][Keys.TYPE_USER] = "BusinessOwner" # sess.update({Keys.FORGET_PASS: {Keys.STATE_ID: States.PASSWORD}}) response = self.make_post_request(json_obj) dct = json.loads(response.data) self.assertEqual(dct[Keys.STATUS], 400) self.assertEqual(dct[Keys.MESSAGE], Result.language.BAD_SCHEMA) # self.assertEqual(dct[Keys.PARAMS], None) self.assertEqual(session[Keys.FORGET_PASS][Keys.STATE_ID], States.PASSWORD) _, iws = User.find(phone_number=data[Keys.PHONE_NUMBER]) print iws # dct = json.loads(response.data) result = pbkdf2_sha256.verify(data[Keys.PASSWORD], iws[0].password) self.assertFalse(result)
def change_password(self, current_password, new_password): if not pbkdf2_sha256.verify(current_password, self.password): raise ServiceException(403, _('Current password is not correct')) else: self.password = new_password self.save() return _('Password changed')
def login_user(self, username: str, password: str, captcha: str, captcha_id: str, ip: str, browser: str) -> dict: # verify captcha in the first place. redis = Redis().r correct_captcha = redis.get(captcha_id) if correct_captcha is None: return { "status_code": HTTPStatus.BAD_REQUEST, "message": "验证码已过期", "status": False } elif correct_captcha.lower() == captcha.lower(): redis.expire(captcha_id, 0) else: return { "status_code": HTTPStatus.FORBIDDEN, "message": "验证码错误", "status": False } # check user account is locked. data = self.db["users"].find_one({"username": username}) or {} if data.get("status", {}).get("disable"): return { "status_code": HTTPStatus.FORBIDDEN, "status": False, "message": data.get("status", {}).get("reason") } returned_value = {"status_code": 0, "message": ""} if data: # try to login stored_password = data["password"] if pbkdf2_sha256.verify(password, stored_password): returned_value["status_code"] = HTTPStatus.OK else: returned_value["status_code"] = HTTPStatus.FORBIDDEN returned_value["message"] = "用户名或密码错误" else: # register hash_value = pbkdf2_sha256.hash(password) try: self.db["users"].insert_one( dict(username=username, password=hash_value, date=ts_date(), ip=ip, browser=browser)) returned_value["status_code"] = HTTPStatus.CREATED except Exception as e: returned_value[ "status_code"] = HTTPStatus.INTERNAL_SERVER_ERROR returned_value["message"] = str(e) returned_value["username"] = data.get("username") returned_value["group"] = data.get("group", ["user"]) return returned_value
def check_user(username, password): if User.objects.filter(username__iexact=username).exists(): user = User.objects.get(username__iexact=username) hashed_password = user.password return pbkdf2_sha256.verify(password, hashed_password) else: return False
def login_user(self, username: str, password: str, ip: str, browser: str) -> dict: data = self.db["users"].find_one({"username": username}) returned_value = {"status_code": 0, "message": ""} if data: # try to login stored_password = data["password"] if pbkdf2_sha256.verify(password, stored_password): returned_value["status_code"] = HTTPStatus.OK else: returned_value["status_code"] = HTTPStatus.FORBIDDEN returned_value["message"] = "用户名或密码错误" else: hash_value = pbkdf2_sha256.hash(password) try: self.db["users"].insert_one( dict(username=username, password=hash_value, date=ts_date(), ip=ip, browser=browser)) returned_value["status_code"] = HTTPStatus.CREATED except Exception as e: returned_value[ "status_code"] = HTTPStatus.INTERNAL_SERVER_ERROR returned_value["message"] = str(e) return returned_value
def _changepass(self): h1 = pw.hash(getpass("Enter new passphrase: ")) if not pw.verify(getpass("Confirm passphrase: "), h1): print("Passphrases do not match.") return False self.model["hash"] = h1 print("Passphrase set. Change must be manually uploaded via 'commit'.") return True
def verify_password(password, hashed_password): try: if not sha256.verify(password, hashed_password): return False, 'The password is wrong.' else: return True, None # when password is not a valid sha256 hashed value except ValueError: return False, 'The password in database is not in the right format.'
def InvalidCredentials(form, field): """Username and Password Checker""" username_entered = form.username.data password_entered = field.data # Check credentials are valid user_object = User.query.filter_by(username=form.username.data).first() if user_object is None: raise ValidationError("Username or Password is incorrect.") elif not pbkdf2_sha256.verify(password_entered, user_object.password): raise ValidationError("Username or Password is incorrect.")
def authenticate(self): if not self.model.get("hash"): print("No passphrase is set.") return self._changepass() elif pw.verify( getpass("Passphrase for starship '{}': ".format(self.name)), self.model["hash"], ): return True else: print("Authentication failure.")
def isValidAccount(self, name, password): accExists = self.jsonAccInfo.has_key(name) if accExists: acc = self.jsonAccInfo.get(name) hash = acc.get('password') if pbkdf2_sha256.verify(password, hash): return True else: return False else: return False
def check_auth(self, username, password, allowed_roles, resource, method): # check for user exists. Only for new item from potential user. if method == 'POST' and resource == 'items': users = current_app.data.driver.db['users'] user = users.find_one({ 'username': username, }) if user: return pbkdf2_sha256.verify(password, user['password']) return False # another collections. return True
def login_user(): users_corresponding = DB.get_instance().query(User).filter_by( username=request.form.get('username')) if users_corresponding.count() == 0: return 'WRONG USERNAME' user = users_corresponding.first() if not pbkdf2_sha256.verify(request.form.get('password'), user.password): return 'WRONG PASSWORD' session['username'] = user.username session.modified = True return redirect(url_for('index'))
def mutate(root, info, username, password): user = UserModel.objects(username=username).first() if user is None: return Login.Fail( [Error("The username or password was incorrect.", [])]) if not pbkdf2_sha256.verify(password, user.password): return Login.Fail( [Error("The username or password was incorrect.", [])]) return Login.Success( refresh_token=create_refresh_token(user), access_token=create_access_token(user), user=user, )
def _authentication(self): find_result = User.find(phone_number=self.phone_number, validate=True) if not find_result[0]: return find_result if not len(find_result[1]): # in eygam ro chek kon not_registered_before = RegisteredBefore(status=404, message=MessagesKeys.NOT_REGISTERED_BEFORE, params=None) return False, not_registered_before verified_pass = pbkdf2_sha256.verify(self.old_password, find_result[1][0].password) if not verified_pass: params = {Keys.PHONE_NUMBER: self.phone_number} fail = WrongPassOrPhoneNumber(status=404, message=MessagesKeys.OLD_PASSWORD_IS_NOT_VALID, params=params) return False, fail return find_result
def test_false_regex_new_password_and_old_password_2(self): data = { Keys.OLD_PASSWORD: "", # 'phone_number': '09125200780', Keys.TYPE_USER: Keys.BUSINESS_OWNER } data1 = json.dumps(data) with self.app as client: with client.session_transaction() as sess: sess['user_id'] = 1 sess[Keys.PHONE_NUMBER] = '09125200100' response = self.make_post_request(data1) dct = json.loads(response.data) self.assertEqual(dct[Keys.STATUS], 400) self.assertEqual(dct[Keys.MESSAGE], Result.language.BAD_SCHEMA) self.assertEqual(dct[Keys.PARAMS], [Result.language.MISSING_PASSWORD_IN_JSON]) self.assertEqual(session['user_id'], 1) _, iws = User.find(phone_number=session[Keys.PHONE_NUMBER]) # dct = json.loads(response.data) result = pbkdf2_sha256.verify(data[Keys.OLD_PASSWORD], iws[0].password) self.assertFalse(result)
def login_user(data): user = UserModel.find_by_email(data['email']) if not user: return { "message": "Your email is not yet registered, Please register first to Login!" }, 401 elif user and pbkdf2_sha256.verify(data['password'], user['password']): access_token = create_access_token(identity=user['email']) refresh_token = create_refresh_token(user['email']) response_object = { 'status': 'success', 'message': 'Successfully logged in.', 'access': access_token, 'refresh': refresh_token } return response_object, 200 return { "message": "Invalid Credentials!, Either email or passwords is incorrect" }, 401
def test_true_regex_info_exist_in_db(self): data = { Keys.OLD_PASSWORD: "******", Keys.NEW_PASSWORD: "******", # "phone_number": '09125200780', Keys.TYPE_USER: Keys.BUSINESS_OWNER } data1 = json.dumps(data) with self.app as client: with client.session_transaction() as sess: sess['user_id'] = 1 sess[Keys.PHONE_NUMBER] = '09125200100' response = self.make_post_request(data1) dct = json.loads(response.data) self.assertEqual(dct[Keys.STATUS], 200) self.assertEqual(dct[Keys.MESSAGE], Result.language.PASSWORD_CHANGE_SUCCESSFULLY) self.assertEqual(dct[Keys.PARAMS], None) self.assertEqual(session['user_id'], 1) _, iws = User.find(phone_number=session[Keys.PHONE_NUMBER]) # dct = json.loads(response.data) result = pbkdf2_sha256.verify(data[Keys.NEW_PASSWORD], iws[0].password) self.assertTrue(result)
def test_old_password_is_not_verified_false_regex_new_password_1(self): data = { Keys.OLD_PASSWORD: "******", Keys.NEW_PASSWORD: "******", # 'phone_number': '09125200780', Keys.TYPE_USER: Keys.BUSINESS_OWNER } data1 = json.dumps(data) with self.app as client: with client.session_transaction() as sess: sess['user_id'] = True sess[Keys.PHONE_NUMBER] = '09125200100' response = self.make_post_request(data1) dct = json.loads(response.data) self.assertEqual(dct[Keys.STATUS], 400) self.assertEqual(dct[Keys.MESSAGE], Result.language.BAD_SCHEMA) self.assertEqual(dct[Keys.PARAMS], {'invalid_params': ['password_is_not_strength']}) self.assertEqual(session['user_id'], 1) _, iws = User.find(phone_number=session[Keys.PHONE_NUMBER]) # dct = json.loads(response.data) result = pbkdf2_sha256.verify(data[Keys.NEW_PASSWORD], iws[0].password) self.assertFalse(result)
def process_keypad(code): """ Function verifies the inputted key code to the stored key code """ time.sleep(0.5) # Display final key press on screen for short time correct = pbkdf2_sha256.verify( ''.join(str(k) for k in code), states['passcode_hash']) # Check if code is correct if correct: # if correct new_state = not states['arm_state'] states.update({'arm_state': new_state}) # Disable Alarm if on if states['alarm_state']: states.update({'alarm_state': False}) display.set_screen( MessageScreen( 'ARMING' if new_state else 'DISARMING')) # Display new state else: # if wrong display.set_screen(MessageScreen('WRONG PASS CODE')) time.sleep(2) display.set_screen(information) # show info screen
def test_old_password_is_not_verified_1(self): data = { Keys.OLD_PASSWORD: "******", Keys.NEW_PASSWORD: "******", # 'phone_number': '09125200780', Keys.TYPE_USER: Keys.BUSINESS_OWNER } data1 = json.dumps(data) with self.app as client: with client.session_transaction() as sess: sess['user_id'] = True sess[Keys.PHONE_NUMBER] = '09125200100' response = self.make_post_request(data1) dct = json.loads(response.data) print dct self.assertEqual(dct[Keys.STATUS], 404) self.assertEqual(dct[Keys.MESSAGE], MessagesKeys.OLD_PASSWORD_IS_NOT_VALID) self.assertEqual(dct[Keys.PARAMS], {"phone_number": session[Keys.PHONE_NUMBER]}) self.assertEqual(session['user_id'], 1) _, iws = User.find(phone_number=session[Keys.PHONE_NUMBER]) # dct = json.loads(response.data) result = pbkdf2_sha256.verify(data[Keys.NEW_PASSWORD], iws[0].password) self.assertFalse(result)
def userlogin(): if request.method == "POST": try: connection = psycopg2.connect( user="******", password="******", host="localhost", port="5432", database="postgres", ) cursor = connection.cursor() email_entered = request.form["email"] password_entered = request.form["password"] print(email_entered, password_entered) record_to_search = (email_entered, ) sql_login_query = """SELECT * FROM users WHERE users.email = %s""" cursor.execute(sql_login_query, record_to_search) # hash the password entered by the user hash = pbkdf2_sha256.hash(password_entered) # check the hashed password pbkdf2_sha256.verify(password_entered, hash) print("Password successful") # check the role of the user sql_role_query = """SELECT users.designation, users.motp, users.eotp, users.phone, users.email, users.designation FROM users WHERE users.email = %s""" cursor.execute(sql_role_query, record_to_search) query = cursor.fetchone() designation = query[0] motp = query[1] eotp = query[2] phone = query[3] email = query[4] role = query[5] print(designation, motp, eotp, phone, email) if (motp == False) and (eotp == False): # Need of OTP client = Client(account_sid, auth_token) # send OTP on email email_input = email # the account which sends OTP , edit values in other.py usr_mail = user_email_id # "" password, edit values in other.py usr_pwd = user_pwd # generating email OTP # selects a random number from a list(nums) in other.py file # this method will be used only for testing purposes email_otp = random.choice(nums) content = ( "Hello Use This OTP to sign in to your SS RPA account! Do not Share this code: " + str(email_otp)) msg = EmailMessage() msg["Subject"] = "OTP Verification For SS RPA Login." msg["From"] = usr_mail msg["To"] = email_input msg.set_content(content) with smtplib.SMTP( "smtp.gmail.com", 587 ) as smtp: # make sure to enable "less secure apps" on google before sending (not recievig) mail , link:https://myaccount.google.com/lesssecureapps smtp.ehlo() smtp.starttls() smtp.ehlo() smtp.login(usr_mail, usr_pwd) smtp.send_message(msg) print("Printing email OTP") print(email_otp) # send OTP on mobile phone_num = phone # right now, for indian numbers only phone_number = "+91" + str(phone_num) # generating email OTP # selects a random number from a list(nums) in other.py file # this method will be used only for testing purposes mobile_otp = random.choice(nums) msg = ("Your One Time Password(OTP) for SS RPA is:" + str(mobile_otp) + " Do Not Share This Code!") message = client.messages.create( body=msg, from_=str(from_phone), status_callback= "http://postb.in/1234abcd", # you can use this too maybe(?) to=str(phone_number), ) print("Mobile OTP") print(mobile_otp) # update database with motp and eotp sql_update_m_query = ( """Update users set m_otp_received = %s where email = %s""" ) cursor.execute(sql_update_m_query, (mobile_otp, email)) sql_update_e_query = ( """Update users set e_otp_received = %s where email = %s""" ) cursor.execute(sql_update_e_query, (email_otp, email)) connection.commit() return redirect(url_for("otp", email=email)) # connection.commit() else: if role == "Admin": return redirect(url_for("dashboard")) else: return redirect(url_for("masterpageuser")) connection.commit() print("Logged in sucessfully") except (Exception, psycopg2.Error) as error: print("Error in select operation", error) finally: # closing database connection. if connection: cursor.close() connection.close() print("PostgreSQL connection is closed") return render_template("login_user.html")
def verify_password(self, raw_password): return pbkdf2_sha256.verify(raw_password, self.password)
def check_pass(raw, enc_string) -> bool: "Checks the raw password against encrypted string." return pbkdf2_sha256.verify(raw, enc_string)
def verify_hash(password, hash): '''method to verify password with the hash''' return pbkdf2_sha256.verify(password, hash)
def password_verify(self, password): return pbkdf2_sha256.verify(password, self.__password_hash)
def check(self, password: Password) -> bool: return pbkdf2_sha256.verify(password.password, self._admin_password.password)
def verify_password(password, password_hash): return pbkdf2_sha256.verify(password, password_hash)
def auth(self, password): if self.password_hash is None: return True return password is not None and pbkdf2_sha256.verify(password, self.password_hash)