我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用werkzeug.security.check_password_hash()。
def post(self): """Login the user""" username = request.json['username'] password = request.json['password'] us = User.query\ .filter(User.disabled is False)\ .filter(User.sigaa_user_name == username)\ .first() abort_if_none(us, 403, 'Username or password incorrect') if not check_password_hash(us.password, password): return msg('Username or password incorrect'), 403 token = jwt.encode( {'id_user': us.id_user, 'tid': random.random()}, config.SECRET_KEY, algorithm='HS256' ).decode('utf-8') return msg(token, 'token')
def put(self): """Change the password""" us = User.query \ .filter(User.disabled == 0) \ .filter(User.id_user == g.current_user) \ .first() abort_if_none(us, 404, 'User not found') if not check_password_hash(us.password, request.json['old_password']): return msg('Old password incorrect'), 403 us.password = request.json['password'] db.session.commit() cache.blacklisted_tokens.append(request.headers['Authorization']) return msg('success!')
def login(): username = request.headers.get('username') password = request.headers.get('password') if username is None or password is None: raise InvalidRequest() user = UsersCollection().find_one({'username': username}) if user is None: raise AuthFailed() is_valid = check_password_hash(user['password_hash'], password) if not is_valid: raise AuthFailed() return jsonify({'token': UserJWT.new(username, user['scope'])})
def validate(self): #check for old pw hash and upadte password if needed self.user = db.session.query(models.User).filter(models.User.email == self.email.data).first() if self.user and self.user.password.startswith("pbkdf2:sha1"): if check_password_hash(self.user.password, self.password.data): self.user.password = encrypt_password(self.password.data) self.user.active = 1 self.user.roles.append(db.session.query(models.Role).filter(models.Role.name=="admin").first()) db.session.commit() return True #do the flask-security checks if not super(Login, self).validate(): return False return True
def validate(self): check_validate = super(LoginForm, self).validate() if not check_validate: return False user = User.query.filter_by(email=self.email.data).first() if not user: check_password_hash('A dumb password', self.password.data) self.email.errors.append('Invalid email or password') self.password.errors.append('Invalid email or password') return False if not user.check_password(self.password.data): self.email.errors.append('Invalid email or password') self.password.errors.append('Invalid email or password') return False return True
def change_passwd(): if session.get('login_in',None): if session.get('username',None): oldpassword = request.values['oldpassword'] newpassword = request.values['newpassword'] try: user = models.User.query.filter_by(username = session['username']).first() if check_password_hash(user.password, oldpassword): user.password = generate_password_hash(newpassword) db.session.add(user) db.session.commit() return jsonify(result="change sucessfull") else: return jsonify(result="change failed") except: db.session.rollback() return jsonify(result="change failed") finally: db.session.close() else: return redirect('/login') else: return redirect('/login')
def validate(self): print 'validate' if not Form.validate(self): print 'validate False' return False login = self.login.data if login[1:-1].find('@') >= 0: user = User.query.filter_by(email=login).first() login_type = 'email' else: user = User.query.filter_by(username=login).first() login_type = 'username' print user, login_type if user is None: self.login.errors.append('Unknown %s' % login_type) return False if not check_password_hash(user.password, self.password.data): self.password.errors.append('Invalid password') return False self.user = user return True
def modifypwd(username): #???????? if username!=session.get('name'): #????????????????????? return redirect('/auth') else: form=ChangePersonalPwd() user=User.query.filter_by(name=username).first() if form.validate_on_submit(): if user is not None and check_password_hash(user.password,form.oldpassword.data): if form.newpassword.data!=form.confirmpassword.data: flash('??????????') else: user.password=generate_password_hash(form.newpassword.data) db.session.commit() flash('?????') return redirect('/auth') else: flash('??????????????') return render_template('modifypwd.html',form=form,writer=session.get('name'))
def validate_login(self): user = self.get_user() if user is None: self.username.errors = ('Invalid username', ) return False if not check_password_hash(user.password, self.password.data): self.password.errors = ('Invalid password', ) return False if not user.is_active: self.username.errors = ('You are not an user active', ) return False if not user.is_admin: self.username.errors = ('You are not an administrator', ) return False return True
def check_password(self, password): """Validate the plain text `password`. Since all users from third-party authentication providers will store :data:`None` in this attribute, you may call :func:`railgun.website.userauth.authenticate` if you just want to validate a user login at a very high-level stage. This method, however, is called mainly by the utilities in :mod:`~railgun.website.userauth`. :param password: The plain text password. :type password: :class:`str` :return: True if `password` passes validation, False otherwise. """ return check_password_hash(self.password, password)
def loginProfessor(): email = request.args['email'] password = request.args['password'] cur.execute("""SELECT hashpswd from professor where email = %s;""", (email,)) lst = cur.fetchall() conn.commit() # Check password to hashed pass in table if len(lst) == 0: return "Professor account not created. Please create an account first." if check_password_hash(lst[0][0], password): cur.execute("""SELECT pid from professor where email = %s;""", (email,)) mylst = cur.fetchall() conn.commit() pid = mylst[0][0] return redirect("/admin/dashboard/"+str(pid)) if not check_password_hash(lst[0][0], password): return "Password is wrong. Shame on you." return "Some error -- Contact Webmaster"
def request_loader(request): email = request.form.get('email') cur.execute("""SELECT sid from students where email = %s;""", (email,)) lst = cur.fetchall() print("IN request_loader: THIS IS THE lst RESULT (before init return): ", str(lst)) if len(lst) == 0: return user = User() sid = lst[0][0] user.id = sid print("IN request_loader: THIS IS THE sid RESULT: ", str(sid)) cur.execute("""SELECT hashpswd from students where email = %s;""", (email,)) lst = cur.fetchall() conn.commit() print("IN request_loader: THIS IS THE lst RESULT: ", str(lst), "AND THE hashpswd RESULT: ", str(lst[0][0])) user.is_authenticated = check_password_hash(lst[0][0], request.form['pw']) return user ## SECURITY V2 ##SV2##(2-E) # Function used to generate password hash with the werkzeug.security package
def loginStudent(): email = request.args['email'] myemail = email.replace('%40', "@") password = request.args['hp'] cur.execute("""SELECT * from students where email = %s;""", (myemail,)) lst = cur.fetchall() conn.commit() if len(lst) == 0: return "Please create a student account first" cur.execute("""SELECT hashpswd from students where email = %s;""", (email,)) lst = cur.fetchall() conn.commit() if check_password_hash(lst[0][0], password): cur.execute("""SELECT sid from students where email = %s;""", (email,)) lst = cur.fetchall() conn.commit() return redirect("/games/"+str(lst[0][0])) if not check_password_hash(lst[0][0], password): return "Password is wrong. Shame on you." return "Student account does not exist yet"
def login(): if flask.request.method == 'GET': return flask.render_template("login.html", curid = 0) email = flask.request.form['email'] print("IN /LOGIN: THIS IS THE email RESULT:", str(email)) cur.execute("""SELECT hashpswd, sid, validated from students where email = %s;""", (email,)) lst = cur.fetchall() conn.commit() if len(lst) != 0: print("IN /LOGIN: THIS IS lst RESULT:", str(lst)) if not lst[0][2]: return "You must validate your account first!" print("IN /LOGIN: THIS IS check_password_hash RESULT:", str(check_password_hash(lst[0][0], flask.request.form['pw']))) if check_password_hash(lst[0][0], flask.request.form['pw']): user = User() user.id = lst[0][1] flask_login.login_user(user) return flask.redirect(flask.url_for('student_games')) return 'Bad login' #==========================# STUDENT PROTECTED VIEW #==========================#
def loginProfessor(): email = flask.request.args['email'] password = flask.request.args['pw'] cur.execute("""SELECT hashpswd from professor where email = %s;""", (email,)) lst = cur.fetchall() conn.commit() # Check password to hashed pass in table if len(lst) == 0: return "Professor account not created. Please create an account first." if check_password_hash(lst[0][0], password): cur.execute("""SELECT pid from professor where email = %s;""", (email,)) mylst = cur.fetchall() conn.commit() pid = mylst[0][0] user = User() user.id = pid flask_login.login_user(user) return flask.redirect(flask.url_for('admin_dashboard')) if not check_password_hash(lst[0][0], password): return "Password is wrong. Shame on you." return "Some error -- Contact Webmaster"
def login_user(cls, name, password): session = SessionManager.Session() try: user = session.query(User).filter(User.name == name).one() if check_password_hash(user.password, password): credential = cls(user) SessionManager.Session.remove() return credential else: raise ClientError(ClientError.LOGIN_FAIL) except NoResultFound: raise ClientError(ClientError.LOGIN_FAIL) except DataError: raise ClientError(ClientError.LOGIN_FAIL) except ClientError as error: raise error except Exception as error: raise ServerError(error.message) finally: SessionManager.Session.remove()
def verify_password(self, password): return check_password_hash(self.password_hash, password)
def authenticate(self, password): return check_password_hash(self.pw_hash, password)
def check_werkzeug(password_hash,password_input): check = check_password_hash(password_hash,password_input) return check
def check_password(self,rawpwd): return check_password_hash(self._password,rawpwd)
def validate_login(user): # db_user = current_app.db.users.find_one({"_id": user['username']}) db_user = current_app.db.get('users', {"_id": user['username']}) if not db_user: return False if check_password_hash(db_user['password'], user['password']): return True 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, password)
def verify_password(self, password): """Verified password. """ return check_password_hash(self.password_hash, password)
def check_password(self, password): return check_password_hash(self.password, password)
def authenticate(self, password): checked = check_password_hash(self.password, password) self._authenticated = checked return self._authenticated
def check_password(self, password): """Check passwords. If passwords match it returns true, else false.""" if self.password is None: return False return check_password_hash(self.password, password)
def login(): form = LoginForm() # Shows login form if form.validate_on_submit(): user = User.query.filter_by(username=form.username.data).first() if user: if user.confirmed_email: if check_password_hash(user.password, form.password.data): login_user( user, remember=form.remember.data ) admin = User.query.filter_by( username=str(user.username) ).first() admin.is_active = True db.session.commit() session['logged'] = 'YES' if current_user: hriks( 'SUCCESS! Welcome, you are logged in %s' % ( user.username ) ) return redirect(url_for('index')) return redirect(url_for('login')) hriks( 'WARNING! Invalid Combination,\ Please check username and password' ) return render_template('login.html', form=form) return render_template('login.html', form=form) # This is Signup form route, it accepts both GET and POST # request. It renders signup form page using GET and submit # form using POST request. # This method also send confirm mail to user # clicking on which user needs to verify his identity
def verify_password(self, password): return check_password_hash(self.password_hash, password) # Gravatar??????
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 login(): if 'username' in session: return jsonify(status_error_already_logged_in) else: if request.method == 'POST': if Users.query.filter_by(USERNAME=request.form['username']).first() is None: return jsonify(status_error_wrong_username_or_password) else: user = Users.query.filter_by(USERNAME=request.form['username']).first() if check_password_hash(user.PASSWORD, request.form['password']) is False: return jsonify(status_error_wrong_username_or_password) else: session['username'] = request.form['username'] return jsonify(status_ok_login_successfully) return render_template("user/login.html")
def user_password_change(): if 'username' in session: if session['username'] != "admin": if request.method == "POST": if Users.query.filter_by(USERNAME=session['username']).first() is None: return jsonify(status_error_does_not_exist_username) else: user = Users.query.filter_by(USERNAME=session['username']).first() if check_password_hash(user.PASSWORD, request.form['password']) is False: return jsonify(status_error_wrong_username_or_password) else: user.PASSWORD = generate_password_hash(request.form['password_new']) try: db.session.add(user) db.session.commit() except: return jsonify(status_error_unknown_error) else: return jsonify(status_ok_edit_successfully) else: return render_template('user/user_change_password.html') else: if request.method == "POST": if Users.query.filter_by(ID_USER=request.form['id_user']).first() is None: return jsonify(status_error_does_not_exist_username) else: user = Users.query.filter_by(ID_USER=request.form['id_user']).first() user.PASSWORD = generate_password_hash(request.form['password_new']) try: db.session.add(user) db.session.commit() except: return jsonify(status_error_unknown_error) else: return jsonify(status_ok_edit_successfully) else: return render_template('user/user_change_password_admin.html') else: return jsonify(status_error_permission_denied)
def verify_password(self, password): """ ???? :param password: ????? :return: ???? True,???? False """ return check_password_hash(self.password, password) ## # ?????? ##
def verify_password(self,password) : return check_password_hash(self.password_hash,password)
def _change_password(): current = request.form.get('current_password', '') new = request.form.get('new_password', '') confirm = request.form.get('confirm_password', '') if not check_password_hash(current_user['pwd_hash'], current): flash('Current password is invalid', 'danger') elif valid_new_password(new, confirm): change_password(current_user, new) flash('Password was successfully changed.', 'success') return redirect(request.referrer)
def authenticate(email, password): user = User.get(email=email.lower()) if user_if_enabled(user): if 'pwd_hash' in user: if check_password_hash(user['pwd_hash'], password): if 'auth_token' not in user: user.update_value('auth_token', auth_token(user)) login_user(user) return user return None