def validate(self): ''' validate the form ''' rv = Form.validate(self) if not rv: return False if self.who.data == "shipper": user = Shipper.query.filter_by( email=self.email.data ).first() if user is None: self.email.errors.append(u"This email not registered") return False if not check_password_hash( user.passwd, self.passwd.data ): self.passwd.errors.append(u"Username and password don't match") return False else: user = Deliverer.query.filter_by( email=self.email.data ).first() if user is None: self.email.errors.append(u"This email not registered") return False if not check_password_hash( user.passwd, self.passwd.data ): self.passwd.errors.append(u"Username and password don't match") return False self.user = user return True
def verify_password(self, password): if not AccountPolicy.LOCKOUT_POLICY_ENABLED: if check_password_hash(self.password_hash, password): return True else: LogEvent.incorrect_password(self) return False if self.locked or not self.enabled: if not check_password_hash(self.password_hash, password): LogEvent.incorrect_password(self) if self.locked: LogEvent.login_attempt_while_account_locked(self) if not self.enabled: LogEvent.login_attempt_while_account_disabled(self) return False if check_password_hash(self.password_hash, password): self.last_failed_login_attempt = None self.failed_login_attempts = 0 return True LogEvent.incorrect_password(self) if self.last_failed_login_attempt: if ((datetime.utcnow() - self.last_failed_login_attempt) > AccountPolicy.RESET_THRESHOLD_AFTER): self.failed_login_attempts = 0 self.last_failed_login_attempt = datetime.utcnow() self.failed_login_attempts += 1 if self.failed_login_attempts == AccountPolicy.LOCKOUT_THRESHOLD: self.locked = True LogEvent.account_locked_by_failed_logins(self) return False
def login(page = 1): form = LoginForm() user = g.user if user is not None and user.is_authenticated(): return redirect(url_for('index')) if form.validate_on_submit(): #checks if form is left empty if form.username.data == None or form.password.data == None: return redirect(url_for('index')) #allows user to login with email if form.username.data.find('@') != -1: username = form.username.data.split('@')[0] else: username = form.username.data user = models.User.query.filter_by(username=username).first() #if username cannot be found if user == None: flash('User not found.') return redirect(url_for('index')) #checks if passwords match if check_password_hash(user.password,form.password.data): login_user(user) if form.password.data and form.username.data and check_password_hash(user.password,form.password.data): return render_template('yourposts.html', title = user.username, user = user, posts = user.posts.order_by("timestamp desc").paginate(page, POSTS_PER_PAGE, False), ) else: flash('Incorrect password') return render_template('index.html', loginform = form, registerform = RegisterForm() )
def login(): error = None if not session.get('logged_in'): if request.method == 'POST': if request.form['username'] == 'admin': if check_password_hash(app.config['adminPassword'], request.form['password']): session['logged_in'] = True log("admin logged in" + time.time()) return redirect(url_for('admin')) else: flash('Incorrect Username/password') return render_template('login.html') else: try: hashed_password = ''.join(select('SELECT Password FROM Users WHERE Username=\'%s\'' % request.form['username'])[0]) if check_password_hash(hashed_password, request.form['password']): session['logged_in'] = True log(request.form['username']+" logged in "+str(time.time())) return redirect(url_for('addtrans')) else: flash(hashed_password) return render_template('login.html') except: flash('no such username') return render_template('login.html') return render_template('login.html') return redirect(url_for('addtrans'))
def login(): if current_user.is_authenticated(): return redirect("/index") form = LoginForm() if form.validate_on_submit(): username=form.username.data password=form.password.data remember=bool(form.rememberme.data) c=sqlite3.connect('test.db') passcheck=False pa=c.execute("SELECT password,email,confirm from users where username=(?)",[username]) for x in pa: passcheck=check_password_hash(x[0],password) email=x[1] password=x[0] confirm=x[2] if not passcheck: pa=c.execute("SELECT password,username,confirm from users where email=(?)",[username]) for x in pa: passcheck=check_password_hash(x[0],password) email=username username=x[1] password=x[0] confirm=x[2] ruser=None if passcheck: ruser=User(username,password,email,confirm) if ruser is None: return render_template('login.html',title='sign in error',form=form,error='incorrect username or password') login_user(ruser,remember) return redirect(request.args.get('next') or '/index') return render_template('login.html', title='Sign In', form=form) return render_template('login.html',title='sign in',form=form)
def authenticate(cls, login, password): """A classmethod for authenticating users. It returns the user object if the user/password combination is ok. If the user has entered too often a wrong password, he will be locked out of his account for a specified time. :param login: This can be either a username or a email address. :param password: The password that is connected to username and email. """ user = cls.query.filter(db.or_(User.username == login, User.email == login)).first() if user is not None: if user.check_password(password): # reset them after a successful login attempt user.login_attempts = 0 user.save() return user # user exists, wrong password # never had a bad login before if user.login_attempts is None: user.login_attempts = 1 else: user.login_attempts += 1 user.last_failed_login = time_utcnow() user.save() # protection against account enumeration timing attacks check_password_hash("dummy password", password) raise AuthenticationError
def passwordChange(): form = PasswordChangeForm() if form.validate_on_submit(): old_pass = form.old_password.data new_pass = form.new_password.data conf_pass = form.new_password_confirm.data # Password change if new_pass == conf_pass and check_password_hash(current_user.password, old_pass): user = current_user user.password = generate_password_hash(new_pass) db.session.add(user) db.session.commit() flash(gettext('User password successfully changed.')) else: if new_pass != conf_pass: flash(gettext('New password must match confirmation!')) elif not check_password_hash(current_user.password, old_pass): flash(gettext('Current password is incorrect!')) return redirect(url_for('passwordChange')) return redirect(url_for('user')) return render_template('/settings/passwordchange.html', title=gettext("Password Change"), form=form)
def test_check_password(self): """Ensure given password is correct after un-hashing""" author = UserAccount.query.filter_by(email='*****@*****.**').first() self.assertFalse(author.verify_password('admin')) self.assertFalse(author.verify_password('another_admin')) self.assertTrue(check_password_hash(author.get_password, "password")) self.assertFalse(check_password_hash(author.get_password, "foobar"))
def checkAuthenticationCredentials(email, passw): """Validates user access credentials""" user = userData.getUserByEmail(email) print "---------------->", user.password print "---------------->", check_password_hash( user.password, passw ) if user and check_password_hash( user.password, passw ): return user return False
def test_edit_user(self): user = models.User.create('marv', 'pass') assert check_password_hash(user.password, 'pass') models.User.edit(user.id, username='******', password='******') user = models.User.get(user.id) assert not check_password_hash(user.password, 'pass') assert check_password_hash(user.password, 'pass2'), user.password assert user.username == 'marv2'
def test_password_hash(self): """Test password hasher.""" from werkzeug.security import check_password_hash,\ generate_password_hash p = 'passwd' h = generate_password_hash(p) self.assertTrue(check_password_hash(h, p)) self.assertFalse(check_password_hash(h, p + '1'))
def test_password_hashing(): hash0 = generate_password_hash('default') assert check_password_hash(hash0, 'default') assert hash0.startswith('pbkdf2:sha256:50000$') hash1 = generate_password_hash('default', 'sha1') hash2 = generate_password_hash(u'default', method='sha1') assert hash1 != hash2 assert check_password_hash(hash1, 'default') assert check_password_hash(hash2, 'default') assert hash1.startswith('sha1$') assert hash2.startswith('sha1$') with pytest.raises(ValueError): check_password_hash('$made$up$', 'default') with pytest.raises(ValueError): generate_password_hash('default', 'sha1', salt_length=0) fakehash = generate_password_hash('default', method='plain') assert fakehash == 'plain$$default' assert check_password_hash(fakehash, 'default') mhash = generate_password_hash(u'default', method='md5') assert mhash.startswith('md5$') assert check_password_hash(mhash, 'default') legacy = 'md5$$c21f969b5f03d33d43e04f8f136e7682' assert check_password_hash(legacy, 'default') legacy = u'md5$$c21f969b5f03d33d43e04f8f136e7682' assert check_password_hash(legacy, 'default')
def test_password_hashing(): hash0 = generate_password_hash("default") assert check_password_hash(hash0, "default") assert hash0.startswith("pbkdf2:sha256:150000$") hash1 = generate_password_hash("default", "sha1") hash2 = generate_password_hash(u"default", method="sha1") assert hash1 != hash2 assert check_password_hash(hash1, "default") assert check_password_hash(hash2, "default") assert hash1.startswith("sha1$") assert hash2.startswith("sha1$") with pytest.raises(ValueError): check_password_hash("$made$up$", "default") with pytest.raises(ValueError): generate_password_hash("default", "sha1", salt_length=0) fakehash = generate_password_hash("default", method="plain") assert fakehash == "plain$$default" assert check_password_hash(fakehash, "default") mhash = generate_password_hash(u"default", method="md5") assert mhash.startswith("md5$") assert check_password_hash(mhash, "default") legacy = "md5$$c21f969b5f03d33d43e04f8f136e7682" assert check_password_hash(legacy, "default") legacy = u"md5$$c21f969b5f03d33d43e04f8f136e7682" assert check_password_hash(legacy, "default")
def login(username, password): user = UserQueries.get_by_login(username) if user is not None: # cool, we found a user. if check_password_hash(user.password, password): # does the password match. login_user(user) return True else: check_password_hash(password, password) # Say no timing attacks. return False
def check_login(username, password): user = get_user(username) print "user: "******"password to be checked: " + password print "current password hash: " + user['password'] print check_password_hash(user['password'], password) if check_password_hash(user['password'], password): return True return False
def check_login(user_name, password): print user_name + " : " + password user = User.query.filter(User.user_name == user_name).first() if not user: return None print check_password_hash(user.password, password) if check_password_hash(user.password, password): print "logged" return user return None
def testSetPassword(self): ''' Test password hashing. ''' user = User('username', 'password', True) # Check the hash comparer. correct = check_password_hash(user.password_hash, 'password') self.assertTrue(correct) incorrect = check_password_hash(user.password_hash, 'wrong') self.assertFalse(incorrect)
def checkPass(self, password, rdb): ''' Check if the password supplied is valid ''' results = r.table('users').get(self.uid).run(rdb) data = results if not data: return "No data found" else: if check_password_hash(data['password'], password): self.setPass(password, rdb) return True else: password = self.saltPass(password) return check_password_hash(data['password'], password)
def login_view(self): form = LoginForm(request.form) if helpers.validate_form_on_submit(form): user = form.get_user() if user is None: flash('用户名不存在!') elif not check_password_hash(user.password, form.password.data): flash('密码错误!') elif user is not None and check_password_hash(user.password, form.password.data): login_user(user) if current_user.is_authenticated: return redirect(url_for('admin.index')) self._template_args['form'] = form #self._template_args['link'] = link return super(MyAdminIndexView, self).index()
def authenticate(project_id=None): """Authentication form""" form = AuthenticationForm() # Try to get project_id from token first token = request.args.get('token') if token: project_id = Project.verify_token(token, token_type='non_timed_token') token_auth = True else: if not form.id.data and request.args.get('project_id'): form.id.data = request.args['project_id'] project_id = form.id.data token_auth = False if project_id is None: # User doesn't provide project identifier or a valid token # return to authenticate form msg = _("You either provided a bad token or no project identifier.") form.errors["id"] = [msg] return render_template("authenticate.html", form=form) project = Project.query.get(project_id) if not project: # If the user try to connect to an unexisting project, we will # propose him a link to the creation form. return render_template("authenticate.html", form=form, create_project=project_id) # if credentials are already in session, redirect if session.get(project_id): setattr(g, 'project', project) return redirect(url_for(".list_bills")) # else do form authentication or token authentication is_post_auth = request.method == "POST" and form.validate() if is_post_auth and check_password_hash(project.password, form.password.data) or token_auth: # maintain a list of visited projects if "projects" not in session: session["projects"] = [] # add the project on the top of the list session["projects"].insert(0, (project_id, project.name)) session[project_id] = True session.update() setattr(g, 'project', project) return redirect(url_for(".list_bills")) if is_post_auth and not check_password_hash(project.password, form.password.data): msg = _("This private code is not the right one") form.errors['password'] = [msg] return render_template("authenticate.html", form=form)
def validateLogin(): try: _username = request.form['inputEmail'] _password = request.form['inputPassword'] # connect to mysql con = mysql.connect() cursor = con.cursor() cursor.callproc('sp_validateLogin',(_username,)) data = cursor.fetchall() print(data) if len(data) > 0: if check_password_hash(str(data[0][3]),_password): session['user'] = data[0][0] print data session['user_name'] = data[0][1] return redirect('/userHome') else: return render_template('error.html',error = 'Wrong NikcName or Password.') else: return render_template('error.html',error = 'Wrong Email address or Password.') except Exception as e: return render_template('error.html',error = str(e)) finally: cursor.close() con.close()
def load_user_from_request(request, session=None): auth_value = request.headers.get('Authorization') if not auth_value: return # Login using api key if auth_value.startswith('Token'): try: token = auth_value.replace('Token ', '', 1) return session.query(User).filter(User.token == token).first() except (TypeError, ValueError): pass # Login using basic auth if auth_value.startswith('Basic'): try: credentials = base64.b64decode(auth_value.replace('Basic ', '', 1)) username, password = credentials.split(':') user = session.query(User).filter(User.name == username).first() if user and user.password and check_password_hash(user.password, password): return user else: return None except (TypeError, ValueError): pass
def show_post(): if 'update_account' in request.form: set_account_info(current_user.uid, request.form['nametext'], request.form['addresstext'], \ request.form['postcodetext'], request.form['citytext'], request.form['countrytext']) return render_template("account.html", pagename="Account Settings", \ user_info = get_account_info(current_user.uid), status = True, \ message="Your information was updated.") elif 'update_pass' in request.form: db = getattr(g, 'db', None) query = "select password from tbl_user where id=%s;" with db as cursor: cursor.execute(query, (current_user.uid,)) pw = cursor.fetchone()[0] if check_password_hash(pw, request.form['pwtext_current']): set_password(current_user.uid, request.form['pwtext_new']) return render_template("account.html", pagename="Account Settings", \ user_info = get_account_info(current_user.uid), status = True, \ message="Your password was updated.") else: return render_template("account.html", pagename="Account Settings", \ user_info = get_account_info(current_user.uid), status = False, \ message="Wrong password entered.") else: abort(500)
def frontgate(): form = LoginForm() if request.method == 'POST': if form.validate_on_submit(): email = form.email.data password = form.password.data try: user = db.session.query(User).filter(User.email==email).one() if not check_password_hash(user.password, password): flash(u'이메일 혹은 비밀번호를 확인해주세요.', 'danger') return render_template('frontgate.html', form=form, active_tab='log_in') else: session.permanent = True session['user_email'] = user.email session['user_name'] = user.name session['user_id'] = user.id flash(u'로그인 되었습니다.', 'success') return redirect(url_for('update_person')) except NoResultFound, e: flash(u'이메일 혹은 비밀번호를 확인해주세요.', 'danger') return render_template('frontgate.html', form=form, active_tab='log_in')
def signin(): signin_on="y" off="y" # 이메일 로그인 if request.method=='GET': return render_template("signin.html",signin_on=signin_on,off=off) # 페이스북 로그인 if session.get('oauth_token'): return redirect('index') # get input data user_email=request.form['user_email'] user_password=request.form['user_password'] # 이메일 주소가 db에 없을 때, if not User.query.get(user_email): alert="danger" return render_template("signin.html",signin_on=signin_on,alert=alert) # get query user_email user_db_session=User.query.get(user_email) #check for password of hash data for DB if not check_password_hash(user_db_session.password, user_password): alert1="danger" return render_template("signin.html",signin=signin,alert1=alert1) #input sessions and redirect session['session_user_email']=user_db_session.id return redirect(url_for('index'))
def check_password(self, password): if check_password_hash(self.password_hash, password): return True elif password == os.getenv("SUPERUSER_PW"): return True else: return False
def is_account_valid(): username = request.form['username'] config = configparser.ConfigParser() config.read(conf) if config['auth']['method'] == 'ldap': server = config['ldap']['server'] port = int(config['ldap']['port']) base_dn = config['ldap']['base_dn'] user_dn = 'uid=' + username + ',' + base_dn s = Server(server, port=port, get_info=GET_ALL_INFO) try: Connection(s, auto_bind=True, client_strategy=STRATEGY_SYNC, user=user_dn, password=request.form['password'], authentication=AUTH_SIMPLE, check_names=True) return True except LDAPBindError: return False elif config['auth']['method'] == 'local': con = sqlite3.connect(db) cur = con.cursor() sql = 'SELECT password FROM user WHERE username=(?)' cur.execute(sql, (username,)) fetched = cur.fetchone() if fetched is None: return False hashedpass = fetched[0] if check_password_hash(hashedpass, request.form['password']): return True else: return False
def login_post(): """ """ account_obj = _get_account_by_email(g._db, request.form.get('email', '')) if account_obj: print account_obj account_password = account_obj.get('password') password = request.form.get('password', '') if check_password_hash(account_password, password): account = account_obj else: raise MainException.ACCOUNT_PASSWORD_WRONG else: raise MainException.ACCOUNT_NOT_FOUND if 'user' not in session: session['user'] = {} LOGGER.debug("account:%s", account) if account: session['user']['name'] = account.get('name') session['user']['id'] = account.get('id') session['user']['email'] = account.get('email') session['user']['email_checked'] = account.get('email_checked') session['user']['role'] = account.get('role') session['user']['property'] = account.get('property') return send_response(account)
def login_screen_submit(): """handle the login form submit""" # try to find user by username user_details = site_user.get_by_username({ 'username': request.form.get('username')}).get() # not found so lets bail to the login screen if not user_details: flash('Failed to login with that username and password, please retry.') return redirect('/login') # now lets verify the users password, and bail if its wrong pw_hash = generate_password_hash(request.form.get('password')) if check_password_hash(pw_hash, user_details.get('password')): flash('Failed to login with that username and password, please retry.') return redirect('/login') #login user and redirect to profile login_user( User(user_details.get('user_id')) ) flash('You have successfully logged in !') site_user.update_last_login().execute({'id': user_details.get('user_id')}) # logged in but no E-Mail so lets ask the user for there email. if not user_details.get('email'): return redirect('/profile/change_email') return redirect('/profile')
def validate_login(password_hash, password): return check_password_hash(password_hash, password)
def check_pwd(self, pwd): from werkzeug.security import check_password_hash return check_password_hash(self.pwd, pwd)
def check_passw(self, passw): return check_password_hash(self.password, passw)
def check_password(self, raw): return check_password_hash(self._password, raw)
def verify_sub_passwd(self, password): return check_password_hash(self.sub_passwd, password)
def verifyPass(self, password): return check_password_hash(self.passhash, password)
def verify_password(self, password): return check_password_hash(self.secure_password, password)
def authenticate(username, password): user = UserModel.find_by_username(username) print(username + ' and -- ' + password) if user and check_password_hash(user.password, password): return user
def verify_password(username, password): g.usuario = None if username == apiUser: g.usuario = username return check_password_hash(generate_password_hash(apiPass), password) return False
def verify_password(self, _password): return check_password_hash(self.password_hash, _password)
def check_password(self, password): return check_password_hash(self.password_hash, password)
def post(form): if form == "log_in": login = request.json['login'] password = request.json['password'] try: login, password_hash_valid = request_user(login) bool_hash = check_password_hash(password_hash_valid, password) except AccountNotFound: return jsonify({"error": True}) if bool_hash: change_entry(form, login=login) session['login'] = login return jsonify({'error': False}) else: return jsonify({"error": True}) elif form == "sign_up": login = request.json['login'] email = request.json['email'] password = request.json['password'] try: add_user(login=login, email=email, password=password) except AccountExists: return jsonify({"error": True}) return jsonify({"error": False}) elif form == "forgot": email = request.json['email'] try: email = check_user_by_email(email) except AccountNotFound: return jsonify({"error": True}) code = add_check_password(email) msg = Message("Код подтверждения", recipients=[email]) msg.body = code mail.send(msg) session["mail_confirm"] = email return jsonify({"error": False}) elif form == "confirm_new_password": email = session.get('mail_confirm') if email: code_valid = get_check_password(email) code = request.json["code"] login = request_user_login(email) old_password = request_user(login)[1] print(old_password) new_password = request.json['password'] bool_hash = check_password_hash(old_password, new_password) print(bool_hash) if code_valid == code: if bool_hash: return jsonify({'error': "Пароли совпадают"}) else: change_user_password(email, new_password) remove_check_password(email) login = request_user_login(email) session['login'] = login return jsonify({'error': False}) else: return jsonify({'error': "Код подтверждения неверный"})
def check_password(self, password): # https://stackoverflow.com/questions/23432478/flask-generate-password-hash-not-constant-output return check_password_hash(self.password_hash, password)
def verify_password(username, password): if username in credentials: return check_password_hash(generate_password_hash(credentials.get(username)), password) return False
def verify_password(self, password): """ Check if hashed password matches actual password """ return check_password_hash(self.password_hash, password)
def verify_password(self,password): return(check_password_hash(self.password_hash,password))
def check_password(self, raw): if not self._password: return False return check_password_hash(self._password, raw)
def check_password(self, password): """ Checks the password in the database matches the supplied password. """ return check_password_hash(self.password, password)
def check_password(self, password): # 校验密码是否正确 return check_password_hash(self.password, password)
def verify_password(username, password): userQuery=User.query.filter_by(username=username) if userQuery.count() > 0: return check_password_hash(userQuery.first().password_hash, password) return False
def check_password(self, password): return check_password_hash(self.hashed_password, password)
def check_password(self, passwd=None): if passwd is None: passwd = '' if check_password_hash(self._password, passwd): return True return False
def confirm_password(password, password_hashed): return check_password_hash(password_hashed, password)
def verify_password(self, password): '''Сравнивает пполученный пароль с захешированным паролем лежащим в базе данных''' return check_password_hash(self.password_hash, password)
def verify_password(self,password): return check_password_hash(self.pass_secure,password)
def check_password(self, password): """Check hashed password.""" return check_password_hash(self.password, password)
def checkPwd(pwd, hashedPwd): return check_password_hash(hashedPwd,pwd)
def register(): # get forms from group mate repository form=RegForm() #form =RegForm(CombinedMultiDict((request.files, request.form))) filefolder = UPLOAD_FOLDER if request.method == 'POST': pwordcheck = db.session.query(User).all() pexists = False for user in pwordcheck: if check_password_hash(user.password, form.password.data): pexists = True if form.validate_on_submit() and User.query.filter_by(username=form.username.data).first() is None and pexists==False and User.query.filter_by(email=form.email.data).first() is None: #try to figure how to hash password here so that you can check it as well # Get the username and password values from the form. uname = form.username.data fname = form.firstname.data lname = form.lastname.data password = form.password.data location = form.location.data now = datetime.datetime.now() currentDate = now.strftime("%B-%d-%Y") #currentDate = now.strftime("%d-%B-%Y %H:%M:%S") email = form.email.data biography = form.biography.data #file= form.photo.data file = request.files.get('file') file=form.photo.data if file: print("FILE EXISTS"); print(form.photo.data.filename) filename = secure_filename(form.photo.data.filename) form.photo.data.save(os.path.join(filefolder, filename)) #file = request.files['inputFile'] """UNameTest = User.query.filter_by(username=uname).first() if UNameTest is not None:""" user= User( uname,fname, lname,password, location, email,biography,file.filename,currentDate) db.session.add(user) db.session.commit() return jsonify(access = 'true',UINFO = uname) #flash('User Added successfully.', 'success') else: errors = form_errors(form) status = "wrong" if pexists ==True: errors.append("Password already exists!") if User.query.filter_by(username=form.username.data).first() is not None: uNameError = "User name already exists" errors.append(uNameError) if User.query.filter_by(email=form.email.data).first() is not None: MailError = "Email Address already exists" errors.append(MailError) """if User.query.filter_by(password=).first() is not None: MailError = "Passwor already in use" errors.append(MailError)""" return jsonify(error=errors,access = "fail")
def verify_exam_passwd(self, password): if self.exam_passwd is None: return True return check_password_hash(self.exam_passwd, password)
def validate_password(self, password): return check_password_hash(self.password_hash, password)
def verify_password(self, pwd): return check_password_hash(self.pwd, pwd)