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')
python类check_password_hash()的实例源码
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 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 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 verify_password(self, password):
return check_password_hash(self.password_hash, password)
def verify_password(self, password):
return check_password_hash(self.password_hash, password)
def verify_password(self, password):
return check_password_hash(self.password_hash, password)
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 verify_password(self, 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, password):
return check_password_hash(self._password, password)
def verify_password(self, password):
"""Verified password.
"""
return check_password_hash(self.password_hash, password)