def loginuser(self): loginbool = True self.chosen = "none" while loginbool == True: print "User accounts: ", users.keys() self.chosen = raw_input("Please choose an account.\n> ") if self.chosen not in users.keys(): print "That account does not exist." print "User accounts: ", users.keys() self.chosen = raw_input("Please choose an account.\n**Capitalization matters.**\n> ") if self.chosen in users.keys(): chosenpw = usersen[self.chosen] x = raw_input("Logging in as " + self.chosen + ".\nPlease enter your password.\n> ") pwcheck = sha256_crypt.verify(x, chosenpw) while pwcheck == False: print "That is incorrect." x = raw_input("Please enter your password.\n**Capitalization matters.**\n> ") pwcheck = sha256_crypt.verify(x, chosenpw) if pwcheck == True: print "Logging in as " + self.chosen + "." pwcheck = True load() print "You are now logged in as " + self.chosen + "!" break else: print "That account does not exist." print "User accounts: ", users.keys() self.chosen = raw_input("Please choose an account.\n**Capitalization matters.**\n> ")
def zmianaHaslaPrzyLogowaniuAND(request): if post(request): dane = request.POST.copy() try: uzytkownik = models.Uzytkownik.objects.get(nick = dane['login']) print('znalazlo uzytkownika') except: return HttpResponse('-2') #bledny login lub haslo starePasuje = sha256_crypt.verify(dane['oldPass'], uzytkownik.haslo) if starePasuje: print('stare haslo pasuje') hasloOk = pasuje('^(?!.*(.)\1{3})((?=.*[\d])(?=.*[A-Za-z])|(?=.*[^\w\d\s])(?=.*[A-Za-z])).{8,20}$', dane['newPass']) hasloOk = hasloOk and (dane['newPass'] == dane['newPass2']) if hasloOk: print('nowe haslo spelnia wymagania') if not sha256_crypt.verify(dane['newPass'], uzytkownik.haslo): uzytkownik.haslo = sha256_crypt.encrypt(dane['newPass']) uzytkownik.dataOstZmianyHasla = datetime.date.today() uzytkownik.save() print('zapisano nowe haslo') return HttpResponse('0') else: return HttpResponse('-6') #nowe haslo nie rozni sie od starego else: return HttpResponse('-7') # haslo nie spelnia wymagan else: return HttpResponse('-2') #bledny login lub haslo else: return HttpResponse('-1') #blad wyslania
def test_02_handler_wrapper(self): """test Hasher-compatible handler wrappers""" from passlib.ext.django.utils import get_passlib_hasher from django.contrib.auth import hashers # should return native django hasher if available hasher = get_passlib_hasher("hex_md5") self.assertIsInstance(hasher, hashers.UnsaltedMD5PasswordHasher) hasher = get_passlib_hasher("django_bcrypt") self.assertIsInstance(hasher, hashers.BCryptPasswordHasher) # otherwise should return wrapper from passlib.hash import sha256_crypt hasher = get_passlib_hasher("sha256_crypt") self.assertEqual(hasher.algorithm, "passlib_sha256_crypt") # and wrapper should return correct hash encoded = hasher.encode("stub") self.assertTrue(sha256_crypt.verify("stub", encoded)) self.assertTrue(hasher.verify("stub", encoded)) self.assertFalse(hasher.verify("xxxx", encoded)) # test wrapper accepts options encoded = hasher.encode("stub", "abcd"*4, iterations=1234) self.assertEqual(encoded, "$5$rounds=1234$abcdabcdabcdabcd$" "v2RWkZQzctPdejyRqmmTDQpZN6wTh7.RUy9zF2LftT6") self.assertEqual(hasher.safe_summary(encoded), {'algorithm': 'sha256_crypt', 'salt': u('abcdab**********'), 'iterations': 1234, 'hash': u('v2RWkZ*************************************'), })
def login_page(): error = '' gc.collect() try: dbconfig = read_db_config() conn = MySQLConnection(**dbconfig) cur = conn.cursor() if request.method == "POST": query = ("""SELECT * FROM users WHERE username = %s""") cur.execute(query, (request.form['username'],)) userpw = cur.fetchone()[2] if sha256_crypt.verify(request.form['password'], userpw): session['logged_in'] = True session['username'] = request.form['username'] session['user-ip'] = request.remote_addr if session['username'] == 'admin': flash(Markup('The Dark Knight <span class="glyphicon glyphicon-knight"></span>')) else: flash('Logged In') return redirect(url_for('blog')) else: error = "Invalid Credentials. Please try again." gc.collect() return render_template('login.html', error = error) except Exception as e: error = 'Invalid Credentials. Please try again.' return render_template('login.html', error = error)
def login(): try: errorLog = '' errorReg = '' formLog = LoginForm(request.form) formReg = RegistrationForm(request.form) if request.method == "POST": #print "Hello" username = formLog.username.data password = formLog.password.data #print username, password c, conn = connection() data = c.execute("SELECT * FROM users WHERE username = (%s)",(thwart(username))) data = c.fetchone()[2] uid = c.execute("SELECT * FROM users WHERE username = (%s)",(thwart(username))) uid = c.fetchone()[0] #print "hello",data, uid #print "Hello" if sha256_crypt.verify(password, data): session['uid'] = uid session['logged_in'] = True session['username'] = username gc.collect() return redirect(url_for("news")) #return render_template("test.html", username = session["username"], loggedIn = session["logged_in"]) else: errorLog = "Invalid Credentials" return render_template('home.html', formLog = formLog, formReg = formReg, errorLog = errorLog, errorReg = errorReg) except Exception as e: errorLog = "Invalid credentials" return render_template ("home.html", formLog = formLog, formReg = formReg, errorLog = errorLog, errorReg = errorReg)
def authenticate_user(username, password): """ Authenticate a user """ try: user = User.query.filter_by(username=username).first() except OperationalError: db.create_all() user = User.query.filter_by(username=username).first() authenticated = False if user: authenticated = sha256_crypt.verify(password, user.password) else: time.sleep(1) logger.info("Authentication Error: User not found in DB: %s", username) return False if authenticated: logger.debug("Successfully Authenticated user: %s", username) else: logger.info("Authentication Failed: %s", username) return authenticated
def post(self): try: args = self.reqparse.parse_args() email = args['id'] query = db_session.query(models.User).filter(models.User.email == email) user = query.one_or_none() if user is None: # return {'status': 'error', 'code': error_code.Login.NOT_FOUND_ID, 'message': error_code.Login.NOT_FOUND_ID.message()} return Response.error(error_code.Login.NOT_FOUND_ID) if not sha256_crypt.verify(str(args['password']), user.password_hash): # return {'status': 'error', 'code': error_code.Login.WRONG_PASSWORD, 'message': error_code.Login.WRONG_PASSWORD.message()} return Response.error(error_code.Login.WRONG_PASSWORD) if user.confirmed is False: return Response.error(error_code.Login.NOT_CONFORMED) user.last_seen = datetime.now() db_session.commit() session.clear() session[Session.LOGIN_SESSION] = sha256_crypt.encrypt(str(user.code + user.password_hash)) session[Session.USER_SESSION] = user.code session[Session.ADMIN_SESSION] = decorators.is_admin(user.code) current_app.logger.info("Login - " + email) return Response.ok() except Exception as e: current_app.logger.error(str(e)) return Response.error(error_code.Global.UNKOWN)
def confirm_user_login(): """Confirm user account information is correct.""" user_email = request.form.get("email") user_password = request.form.get("password") try: # checks if user exists user = User.get_user_by_email(user_email) # get pw from db and compare it to user input hash = user.password password_check = sha256_crypt.verify(user_password, hash) # if everything works, log user in and create a cart if password_check: userid = user.user_id session['User'] = userid if 'Cart' not in session: new_cart = Cart.create_new_cart(userid) session['Cart'] = new_cart.cart_id return jsonify({"confirmed_user": True, "user_id": userid}) else: raise Exception except Exception: return jsonify({"confirmed_user": False})
def user_data(): if request.method == 'GET': return render_template('user_service/user-data.html') else: if not sha256_crypt.verify(request.form.get('lg-current-password'), current_user.password): flash(u"Wrong password!", 'danger') return render_template('user_service/user-data.html') fname = request.form.get('lg-fname') lname = request.form.get('lg-lname') email = request.form.get('lg-email') password = request.form.get('lg-new-password') if password == '': password = current_user.password else: password = sha256_crypt.encrypt(password) try: user_obj = User(current_user.username, password, fname, lname, email, current_user.status, current_user.is_active) user_data_access.alter_user(user_obj) flash(u"User data has been updated!", 'success') except: flash(u"User data couldn't be updated!", 'danger') return render_template('user_service/user-data.html')
def login_page(): error = '' try: c, conn = connection() if request.method == "POST": data = c.execute("SELECT * FROM users WHERE username = (%s)", thwart(request.form['username'])) data = c.fetchone()[2] if sha256_crypt.verify(request.form['password'], data): session['logged_in'] = True session['username'] = request.form['username'] flash("You are now logged in") return redirect(url_for("dashboard")) else: error = "Invalid credentials, try again." gc.collect() return render_template("login.html", error=error) except Exception as e: error = flash(e) #error = "Invalid credentials, try again." return render_template("login.html", error = error)
def login(request): login_url = request.route_url('login') referrer = request.url if referrer == login_url: referrer = '/' came_from = request.params.get('came_from', referrer) message = '' login_name = '' password = '' context = dict( message=message, url=request.application_url + '/login', came_from=came_from, login=login_name, password=password, logged_in=authenticated_userid(request), ) if 'form.submitted' in request.params: login_name = request.params['login'] password = request.params['password'] user = DBSession.query(User).filter_by(username=login_name).first() try: if sha256_crypt.verify(password, user.password): headers = remember(request, login_name) return HTTPFound(location=came_from, headers=headers) except AttributeError: context['message'] = 'No such user!' return context context['message'] = 'Wrong password!' return context
def login(): if request.method == 'GET': return render_template('user_service/login-form.html') else: username = request.form.get('lg-username') password = request.form.get('lg-password') try: user = user_data_access.get_user(username) if sha256_crypt.verify(password, user.password): # Check if user is inactive if not user.is_active: flash(u"This user is inactive and can't log in.", 'warning') return render_template('user_service/login-form.html') # Login and validate the user. # user should be an instance of your `User` class login_user(user) return redirect(url_for('main.index')) else: flash(u"Failed to log in. Check the provided username/password", 'danger') return render_template('user_service/login-form.html') except Exception as e: flash(u"Failed to log in. Check the provided username/password.", 'danger') # app.logger.exception(e) return render_template('user_service/login-form.html')
def login_page(): '''The login page. If the user inputs a login&password, first check if the username exists, if so check the password and send the user to the chat room after updating the session and active_users. Else, display "invalid credentials" and render the template again. It's easy to flash different error messages for invalid username and invalid password, but that feels hacker-friendly. Easy to change anyway.''' try: if request.method == "POST": cursor,conn = connection() user_exists = cursor.execute("SELECT * FROM users WHERE username = (%s)", [request.form["username"]]) # first see if the username exists if int(user_exists) > 0: # puts together the namespace and the values from the db... safer than doing things like row[2] assuming order etc. user = dict(zip(map(lambda x:x[0], cursor.description), cursor.fetchone())) # see if the password also checks out if sha256_crypt.verify(request.form['password'], user['password']): session['logged_in'] = True session['name'] = user['username'] active_users['lobby'].add(session['name']) flash("You are now logged in") return redirect(url_for("chat")) else: flash('Invalid credentials, please try again.') return render_template("login.html") return render_template("login.html") except Exception as e: return render_template("500.html", error = e)
def verify_password(username, password): if username != 'admin': return False pw = None with open(load_passfile(), 'r') as fd: pw = fd.read() return sha256_crypt.verify(password, pw)
def update_passwd(self, username, new_password, old_password=None): ''' Change a logged in user's password. :param username: username who's password will be updated :param new_password: new password to apply to user's profile :param old_password: old (current) password for validation ''' # FIXME: take out a lock... for updating any properties if not self.is_self(username): self._raise(401, "not authorized") self.user_exists(username, raise_if_not=True) if not new_password: self._raise(400, 'new password can not be null') if not old_password: if not self.is_superuser(): self._raise(400, 'old password can not be null') old_passhash = None if old_password: old_passhash = self.get_user_profile(username, ['_passhash']) if old_passhash and sha256_crypt.verify(old_password, old_passhash): new_passhash = sha256_crypt.encrypt(new_password) else: self._raise(400, "old password does not match") else: new_passhash = sha256_crypt.encrypt(new_password) self.update_user_profile(username, 'set', '_passhash', new_passhash) logger.debug( "password updated (%s) by %s" % (username, self.current_user)) return True
def login_page(): print "login page" error = '' try: c, conn = connection() if request.method == "POST": print "login POST" data = c.execute("SELECT * FROM users WHERE username = (%s)", [thwart(request.form['username'])] ) if not data: flash('username does not exist') data = c.fetchone()[2] print "data fetchone" if sha256_crypt.verify(request.form['password'], data): session['logged_in'] = True session['username'] = request.form['username'] flash('You are now logged in') return redirect(url_for("dashboard")) else: flash('incorrect password') e = "Invalid credentials, try again." gc.collect() return render_template("login.html", error=error) except Exception as e: print e error = "EXCEPTIONInvalid credentials, try again." return render_template("login.html", error = error)
def login(): """ Login handler. Check password from user file and add <username> to session storage. """ if request.method == 'POST': username = escape(request.form.get('username', None)) password = request.form.get('password', None) next_url = request.args.get('next', url_for('main')) if not username or not password: flash('Fill all fields!', 'error') return redirect(url_for('login', next=next_url)) try: user_file = safe_join(app.config['USERS_FOLDER'], username) with open(user_file, 'r') as uf: user_conf = load(uf) # user_file on json format if not sha256_crypt.verify(password, user_conf['password']): # check password flash('Wrong password!', 'error') return redirect(url_for('login', next=next_url)) else: flash('You successfully logged in!', 'info') session['username'] = username settings_write(username, 'last_login', int(time.time())) except FileNotFoundError: flash('User not exist!', 'error') return redirect(url_for('login', next=next_url)) except Exception: abort(500) return redirect(next_url) return render_template('login.html')
def login(): """ Confirm that a username and password match a User record in the db. """ username = request.args.get('username') password = request.args.get('password') success = False message = '' if username and password: user_match = db.session.query(User)\ .filter(User.username == username).first() if user_match and sha256_crypt.verify(password, user_match.password): if user_match.active: session.update({ 'username': user_match.username, 'userId': user_match.id, 'loggedIn': True }) success = True else: message = 'Please confirm your registration before logging in' else: message = 'Login credentials invalid' else: message = 'You must provide a username and password' return jsonify(success=success, message=message)
def login(): error = None try: c, conn = connection() flash("db ok") if request.method == "POST": flash("method is POST") data = c.execute("SELECT * FROM users WHERE username = (%s)", [thwart(request.form['username'])]) data = c.fetchone()[2] name = request.form['username'] if sha256_crypt.verify(request.form['password'], data): session['logged_in'] = True session['username'] = request.form['username'] flash("You are now logged in") if name == 'ubuntu': session['is_admin']= True flash("welcome Admin!") else: flash("Welcome Standard User") return redirect("/") else: error = "Invalid credentials, try again." gc.collect() return render_template("register/login.html", error=error) except Exception as e: #flash(e) error = "Invalid credentials, try again." return render_template('register/login.html',error = error)
def login(self, username, password): if ((username != '') and (password != '')): db = dbFunctions.db_class() table = "login" fields = ["id","password"] condition = "WHERE username='******'".format(username) res = db.select_from_table(table, fields, condition)[0] # print(res) if len(res) == 0: return {"code": "01", "msg": "User account does not exist"} else: # all action goes here!!! if sha256_crypt.verify(password, res['password']): table = "login" fields = {"status": "1", "last_login": "******"} condition = "WHERE username='******'".format(username) update_login = db.update_table(table, fields, condition) # condition = "WHERE tbl_user_id='{0}'".format(res['id']) # update_login = db.update_table(table, fields, condition) db.closeInstanceConnection() if update_login == True: # res[0]['last_login'] = res[0]['last_login'].strftime("%Y-%m-%d %H:%M:%S") return {"code": "00", "msg": res} else: return {"code": "01", "msg": "Failed to update tbl_login"} else: return {"code": "01", "msg": "Invalid username or password"} else: return {"code": "01", "msg": "username or password cannot be empty"}
def verify_pw(username, password): user = Users.query.filter_by(username=username).first() if user: g.uid = user.id g.scope = set(user.scope.split(',')) return sha256_crypt.verify(password, user.password) return False
def Login_User() -> 'html': User = request.form['User'] Password1 = request.form['Password'] with DBcm.UseDatabase(DBconfig) as cursor: _SQL = "SELECT confrom FROM usertable WHERE User=%s" cursor.execute(_SQL, (User,)) data = cursor.fetchall() test = ','.join(str(v) for v in data[0]) if test != "1": return 'Your accont in not validation please validation your accont' else: with DBcm.UseDatabase(DBconfig) as cursor: _SQL = "SELECT Password FROM usertable WHERE User=%s" cursor.execute(_SQL, (User,)) data = cursor.fetchall() if not data: return 'Sorry you login faled please go back and try again 1' else: test = ','.join(str(v) for v in data[0]) if sha256_crypt.verify(Password1 , test): with DBcm.UseDatabase(DBconfig) as cursor: _SQL = "SELECT Admin FROM usertable WHERE User=%s" cursor.execute(_SQL, (User,)) data = cursor.fetchall() test = ','.join(str(v) for v in data[0]) session['logged_in'] = True if test == "1": session['Admin'] = True return 'You are login' else: return 'Sorry you login faled please go back and try again'
def login(): try: c, conn = connection() error = None if request.method == 'POST': if 'login' in request.form : username = request.form['username'] password = request.form['password'] c.execute("SELECT * from users where username = %s", [thwart(username)]) data = c.fetchone()[4] # salt = uuid.uuid4().hex # saltpassword = str(salt + request.form['password']) if not sha256_crypt.verify(password , data): error = 'Invalid Credentials. Please try again.' else : flash("You are now logged in") session['logged_in'] = True session['username'] = username return redirect(url_for('upload_file')) c.close() conn.close() elif 'register' in request.form : return redirect(url_for('register')) return render_template('login.html', error=error) except Exception as e: return(str(e))
def login(): """ Logs user into session and returns user data and success message. """ email = request.form.get("email").lower() response = {"status": "warning"} if email == "": response["message"] = "Please enter an email address." else: user = model.session.query(model.User).filter_by(email=email).first() if user is None: response["message"] = "There is no user with that email address." elif sha256_crypt.verify(request.form.get("password"), user.password): flask_session['id'] = user.id flask_session['firstname'] = user.firstname response["status"] = "success" response["message"] = "Welcome back!" response["firstname"] = user.firstname response["user"] = user.id else: response["message"] = "Invalid password." return jsonify(response)
def login_page(): error = '' try: c, conn = connection() if request.method == "POST": data = c.execute("select * from users where username = (%s)", [thwart(request.form['username'])]) #get the first record data = c.fetchone()[2] #check if password matches if sha256_crypt.verify(request.form['password'], data): session['logged_in'] = True session['username'] = request.form['username'] flash("You are now logged in!") return redirect(url_for('dashboard')) else: error = "Invalid credentials, try again!" gc.collect() return render_template("login.html", error=error) except Exception as e: error = "Invalid credentials, try again!" return render_template("login.html", error = error)
def comfirm_password(userid, email, password): c, conn = connection() sql = """ SELECT paswrd FROM user_tbl WHERE email = %s AND iduser = %s; """ data = (email, userid) info = c.execute(sql, data) if info == 1: pas_hash = c.fetchone() output = sha256_crypt.verify(password, pas_hash[0]) pas_hash = random.random() password = random.random() else: output = False conn_close(c, conn) return output
def login(): error = "" try: if request.method == 'POST': c, conn = connection() data = c.execute("SELECT * FROM data WHERE username = (%s)", thwart(str(request.form['username']))) data = c.fetchone()[3] if sha256_crypt.verify(str(request.form['password']), str(data)): session['logged_in'] = True session['username'] = request.form['username'] c.close() conn.close() gc.collect() flash('Logged in Successfully') return redirect(url_for('show_vault')) else: error = "Invalid Credentials" return render_template("login.html", error=error) return render_template("login.html", error=error) except Exception as e: error = "Invalid Credentials" #str(e) return render_template('login.html', error=error)
def delUser(): form = AnotherForm(request.form) if request.method == 'POST': #Creating session for user registration to send form data to database Session = sessionmaker(bind=engine) sess = Session() name=request.form['name'] password=request.form['password'] sessname = session['user'] #Query for user records myuser = sess.query(User).filter_by(username=name).first() adminuser = sess.query(User).filter_by(username=sessname).first() #If the myuser exists in the database if myuser is not None: #Delete myuser from the database sess.delete(myuser) #Check if form is valid and the admin password is correct if error rollback and log if form.validate() and sha256_crypt.verify(password, adminuser.password): try: sess.commit() except Exception as e: sess.rollback() print(e) finally: return render_template('delsuccess.html', form=form) else: #display error message in case of incorrect form data flash('Error: All the form fields are required OR Enter correct email address ') return render_template('deluser.html', form=form)
def login(): #Fetch login form data and store it in a variable POST_USERNAME = str(request.form['username']) POST_PASSWORD = str(request.form['password']) #Create a session Session = sessionmaker(bind=engine) s = Session() try: #Make the query with database against the form data query = s.query(User).filter(User.username.in_([POST_USERNAME])) result = query.first() #Compare password from form and from the database if (sha256_crypt.verify(POST_PASSWORD, result.password)) : #Set session to true if login is successful. Set username and role in session. session['logged_in'] = True session['role'] = result.role session['user'] = result.username else: #Display credential if passwords don't match flash('Invalid Credentials. Please try again') except: #Display error message if login is unsuccessful flash('Invalid Credentials. Please try again') #Return to home page return index()
def token_post(): try: if request.json is None: return jsonify({'message': 'Problems parsing JSON'}), 415 if not request.json.get('username', None): error = { 'resource': 'Token', 'field': 'username', 'code': 'missing_field' } return jsonify({'message': 'Validation Failed', 'errors': error}), 422 if not request.json.get('password', None): error = {'resource': 'Token', 'field': 'password', 'code': 'missing_field'} return jsonify({'message': 'Validation Failed', 'errors': error}), 422 user = Users.query.filter_by(username=request.json.get('username'), banned=0).first() if not user: return jsonify({'message': 'username or password error'}), 422 if not sha256_crypt.verify(request.json.get('password'), user.password): return jsonify({'message': 'username or password error'}), 422 s = Serializer(app.config['SECRET_KEY'], expires_in=app.config['EXPIRES']) token = s.dumps({'uid': user.id, 'scope': user.scope.split(',')}) except Exception as e: print e return jsonify({ 'uid': user.id, 'access_token': token, 'token_type': 'self', 'scope': user.scope, 'expires_in': app.config['EXPIRES'] }), 201
from passlib.hash import sha256_crypt password = sha256_crypt.encrypt("password") password2 = sha256_crypt.encrypt("password") print(password) print(password2) print(sha256_crypt.verify("password", password))
def changeAdminPassword(self, request_data): """ This function handles all logic related to login on the platform @Params : void """ self.logger.write_to_console( "EVENT", "{0} changing Admin password {1}".format(self.user['username'], str(request_data))) if request_data['newPassword'] == request_data['oldPassword']: return { "code": language.CODES['FAIL'], "msg": "New password can not be the same as the old password.", "data": [] } utl = Utilites() comple = utl.password_complexity_check(request_data['newPassword']) print(comple) if comple['strength'] < 10: self.logger.write_to_console( "EVENT", "password_weak_password" + self.user['username'] + " | Password change.") return { "code": language.CODES['FAIL'], "msg": "The password entered is weak. Kindly make sure the password length is 8 and above and contains a a least one digit symbol uppercase and lowercase", "data": [] } if request_data['newPassword'] == request_data['newPasswordRep']: admin_data = self.model.getAdminByUsername_chg( self.user['username']) if admin_data == []: self.logger.write_to_console( "EVENT", "User does not exit " + self.user['username'] + " | Non-Existing User.") return { "code": language.CODES['FAIL'], "msg": self.lang['wrong_username'], "data": [] } else: verify_pass = sha256_crypt.verify(request_data['oldPassword'], admin_data[0]['password']) self.logger.write_to_console( "EVENT", "varify Password | " + str(verify_pass)) if verify_pass == True: password = sha256_crypt.encrypt( request_data['newPassword']) res = self.model.updateAdministrator({ "password": password, "username": self.user['username'], "pass_date": "NOW()" }) if res == True: admin_data = self.model.getAdminByUsernameLogin( self.user['username']) try: Utilites.send_mail( Utilites, "SSNIT PASSWORD CHANGE", "<p>Hi {0}</p><p>Your SSNIT password has been changed. If you are not aware of this change kindly send a mail to <a>[email protected]</a>.<br><br>Best Regards</p><p>FUSION PLATFORM</p>" .format(admin_data[0]['first_name']), [admin_data[0]['email']]) except Exception as e: pass return { "code": language.CODES['SUCCESS'], "msg": self.lang['admin_sucessful_pass_change'], "data": admin_data[0] } else: return { "code": language.CODES['FAIL'], "msg": self.lang['admin_update_failed'], "data": [] } else: self.logger.write_to_console( "EVENT", "wrong previous password " + self.user['username'] + " | Password change.") return { "code": language.CODES['FAIL'], "msg": self.lang['wrong_old_password'], "data": [] } else: self.logger.write_to_console( "EVENT", "password_mismatch " + self.user['username'] + " | Password change.") return { "code": language.CODES['FAIL'], "msg": self.lang['password_mismatch'], "data": [] }
def passwordMatch(user, pword): if sha256_crypt.verify(pword, user.getPassword()): return True else: return False
def checkPassword(self, password): return sha256_crypt.verify(password, self.password)
from passlib.hash import sha256_crypt password = sha256_crypt.encrypt("test") print(password) print(sha256_crypt.verify("test", password))
def run(self): # if there is a signal, run the following coding while self.signal: try: # receiving the data from agent_pi data = self.socket.recv(200) except: # show the message that signal is disconnected print("Client " + str(self.address) + " has disconnected") self.signal = False connections.remove(self) break if data: try: new_data = json.loads(data) print("ID " + str(self.id) + ": " + str(data.decode("utf-8"))) data_type = new_data["type"] # There will be 2 types of data that send by agent pi, they are: "credentials" and "location" # check if the data type is "credentials" if data_type == "credentials": # assigning the variables to the user account information that entered in the agent_pi username = new_data["username"] password = new_data["password"] customer_id = new_data["customer_id"] car_id = new_data["car_id"] # checking whether the user account information of agent pi match that on cloud database user_data = db.login_account(username) # if the account information successfully match that on cloud database if user_data is not None and sha256_crypt.verify( password, user_data['password']): # Request from agent pi for unlocking the car if new_data["status"] == "collected": # validate whether the user has booked the car verify = db.validate_collection( customer_id, car_id) # if verify successfully if verify is not None: for client in connections: if client.id == self.id: client.socket.send( str.encode( "The Car has successfully unlocked." )) db.update_booking( verify["booking_id"], new_data["status"]) # if verify failed else: for client in connections: if client.id == self.id: client.socket.send( str.encode( "Unlocking Denied")) # Request from agent pi for returning the car if new_data["status"] == "returned": # validate whether the user has collected the car before verify = db.validate_return_car( customer_id, car_id) # if verify successfully if verify is not None: for client in connections: if client.id == self.id: client.socket.send( str.encode( "Car Return Successfully." )) # booking_status = new_data["status"] db.update_booking( verify["booking_id"], new_data["status"]) # if verify failed else: for client in connections: if client.id == self.id: client.socket.send( str.encode( "Car Return Denied")) # if the account information DOES NOT match that on cloud database else: for client in connections: if client.id == self.id: client.socket.send( str.encode( "Username or password is incorrect" )) # check if the data type is "location" elif data_type == "location": car_id = new_data["car_id"] longitude = new_data["longitude"] latitude = new_data["latitude"] db.update_car_location(car_id, latitude, longitude) elif data_type == "face recog fail": for client in connections: if client.id == self.id: client.socket.send( str.encode("Facial Recognition fail.")) # if the received data from agent_pi cannot loaded properly except: pass
def inspect_the(meat, oldmeat): meat2_inspect = meat meat = sha256_crypt.verify(meat2_inspect,oldmeat) return meat
from passlib.hash import sha256_crypt pwd = sha256_crypt.encrypt('password') pwd2 = sha256_crypt.encrypt('password') print(len(pwd), type(pwd), pwd) print(pwd2) print() print(sha256_crypt.verify('password', pwd2)) # print(sha256_crypt.verify('password', pwd2))
def verify(self, password: str): return sha256_crypt.verify(password, self.__value)
def adminlogin(self, request_data, try_var): """ This function handles all logic related to login on the platform @Params : void """ self.logger.write_to_console( "EVENT", "Login request for " + request_data['username']) admin_data = self.model.getAdminByUsernameLogin( request_data['username']) if admin_data == []: self.logger.write_log( "USER_ACCESS", "Login request | " + request_data['username'] + " | Failed | Non-Existing User.") return { "code": language.CODES['FAIL'], "msg": self.lang['wrong_username'], "data": [] } else: print(try_var) if try_var != None and try_var >= 3: self.model.updateAdministrator({ "active": "2", "last_login": "******", "username": request_data['username'] }) if try_var == 3: return { "code": language.CODES['FAIL'], "msg": "Sorry your account has been blocked. Kindly contact your administrator.", "data": 2, "username": request_data['username'] } else: return { "code": language.CODES['FAIL'], "msg": "Sorry your account has been blocked. Kindly contact your administrator.", "data": [] } else: if admin_data[0]['active'] == 1: print(admin_data[0]) verify_pass = sha256_crypt.verify( request_data['password'], admin_data[0]['password']) self.logger.write_to_console( "EVENT", "varify Password | " + str(verify_pass)) if verify_pass == True: self.model.updateAdministrator({ "status": "1", "last_login": "******", "username": request_data['username'] }) self.logger.write_log( "USER_ACCESS", "Login request | " + request_data['username'] + " | Successful | Login Successful") return { "code": language.CODES['SUCCESS'], "msg": self.lang['login_successful'], "data": admin_data[0], "username": request_data['username'] } else: self.logger.write_to_console( "EVENT", "Login request failed for " + request_data['username'] + " | Failed | Wrong Password.") return { "code": language.CODES['FAIL'], "msg": self.lang['wrong_username'], "data": 1, "username": request_data['username'] } else: self.logger.write_to_console( "EVENT", "Login request failed for " + request_data['username'] + " | Failed | Blocked User") return { "code": language.CODES['FAIL'], "msg": "Sorry your account has been blocked. Kindly contact your administrator.", "data": 2, "username": request_data['username'] }
def decrypt_password(user, password): _sql = """SELECT password from users where user_id=%s""" with UseDataBase(dbconn) as cursor: cursor.execute(_sql, (user, )) content = cursor.fetchall() return sha256_crypt.verify(password, content[0][0])
def authenticate(username, password): user = UserModel.find_user_name(username) if user and sha256_crypt.verify(password, user.password): return user
def authenticate(email, password): user = User.query.filter_by(email=email).first() if user and sha256_crypt.verify(password, user.password): return user
def check_password(self, plaintext_password): return sha256_crypt.verify(plaintext_password, self._password)
def check_password(self, password): if sha256_crypt.verify(password, self['password']): return True
def test_verify_password_success(auth_env): encrypted = sha256_crypt.encrypt("secret") password = '******' assert sha256_crypt.verify(password, encrypted)
def verify_password(self, password): encrypt_str = '%s%s' % (password, self.salt) verify_result = sha256_crypt.verify(encrypt_str, self.password) return verify_result
from passlib.hash import sha256_crypt password = sha256_crypt.encrypt("password") #encrypt 바꿔준다는 의미 print(password) print(sha256_crypt.verify("password", password)) #비밀번호가 뭔지 모르지만 검증해주는것 맞으면 True 틀리면 False
def test_from_string(self): password = Password.fromString("password") self.assertTrue(sha256_crypt.verify("password", password.value))
def is_authenticated(self): if (self.query.isempty() is True): return False if sha256_crypt.verify(self.password, self.userId.password): return True return False
def check_password(self, password): if self.password_hash: return sha256_crypt.verify(password, self.password_hash) else: return False
def test_constructor(self): password = Password(sha256_crypt.encrypt("password")) self.assertTrue(sha256_crypt.verify("password", password.value))
#-*- coding:utf-8 -*- from passlib.hash import sha256_crypt password = sha256_crypt.encrypt("password") password2 = sha256_crypt.encrypt("password") password3 = sha256_crypt.encrypt("danal") password4 = sha256_crypt.encrypt("danal") password5 = sha256_crypt.encrypt("danal") print(password) print(password2) print(password3) print(password4) print(password5) print(sha256_crypt.verify("password", password)) print(sha256_crypt.verify("password", password2)) print(sha256_crypt.verify("danal", password3)) print(sha256_crypt.verify("danal", password4)) print(sha256_crypt.verify("danal", password5))
pass2 = "password2" salt = "password3" saltpass1 = pass1 + salt saltpass2 = pass2 + salt new_pass1 = sha256_crypt.encrypt("password1") new_pass2 = sha256_crypt.encrypt("password2") print(pass1) print(pass2) print(sha256_crypt.verify("password2" + salt, new_pass1)) """ import hashlib user_password ="******" salt = "chocolate" new_password = user_password + salt hashpass = hashlib.md5(new_password.encode()) print(hashpass.hexdigest()) """
def verify_password(self, password): return sha256_crypt.verify(password, self.password_hash)
def check_password(self, password: str): return sha256_crypt.verify(password, self.password_hash)
def check_password_hash(cls, account, password): if account is not None: if sha256_crypt.verify(password, account.password): return True return False
def verifyPasswords(password, dbpassword): return sha256_crypt.verify(password, dbpassword)
from passlib.hash import sha256_crypt salt = "password3" pass1 = "password1" + salt pass2 = "password2" + salt saltpass1 = sha256_crypt.encrypt(pass1) saltpass2 = sha256_crypt.encrypt(pass2) print(saltpass1) print(saltpass2) print(sha256_crypt.verify("password1"+salt, saltpass1)) """ # simple md5 with salt import hashlib user_password = "******" salt = "thinmints" new_password = user_password + salt hashpass = hashlib.md5(new_password.encode()) print(hashpass.hexdigest()) """
def compare(self, pwd): return sha256_crypt.verify(pwd, self.password)