def signin():
# If sign in form is submitted
form = LoginForm(request.form)
# Verify the sign in form
if form.validate_on_submit():
user = User.query.filter_by(email=form.email.data).first()
if user and check_password_hash(user.password, form.password.data):
session['user_id'] = user.id
flash('Welcome %s' % user.name)
return redirect(url_for('auth.home'))
flash('Wrong email or password', 'error-message')
return render_template("auth/signin.html", form=form)
python类check_password_hash()的实例源码
def login():
form = LoginForm(request.form)
if form.validate_on_submit():
user = User.query.filter_by(email=form.email.data).first()
if user:
password = form.password.data
if user.ldap_auth:
ldap = current_app.ldap
dn = ldap.find_user_by_email(user.email)
if dn and ldap.check_password(dn, password):
return successful_login(user, password)
elif check_password_hash(user.password, password):
return successful_login(user, password)
flash('Incorrect email or password', 'error-message')
logging.debug('Incorrect email or password')
return render_template('auth/login.html', form=form)
def login():
"""Logs the user in."""
if g.user:
return redirect(url_for('timeline'))
error = None
if request.method == 'POST':
user = query_db('''select * from user where
username = ?''', [request.form['username']], one=True)
if user is None:
error = 'Invalid username'
elif not check_password_hash(user['pw_hash'],
request.form['password']):
error = 'Invalid password'
else:
flash('You were logged in')
session['user_id'] = user['user_id']
return redirect(url_for('timeline'))
return render_template('login.html', error=error)
def login():
"""Logs the user in."""
if g.user:
return redirect(url_for('timeline'))
error = None
if request.method == 'POST':
user = query_db('''select * from user where
username = ?''', [request.form['username']], one=True)
if user is None:
error = 'Invalid username'
elif not check_password_hash(user['pw_hash'],
request.form['password']):
error = 'Invalid password'
else:
flash('You were logged in')
session['user_id'] = user['user_id']
return redirect(url_for('timeline'))
return render_template('login.html', error=error)
def login():
"""Logs the user in."""
if g.user:
return redirect(url_for('timeline'))
error = None
if request.method == 'POST':
user = query_db('''select * from user where
username = ?''', [request.form['username']], one=True)
if user is None:
error = 'Invalid username'
elif not check_password_hash(user['pw_hash'],
request.form['password']):
error = 'Invalid password'
else:
flash('You were logged in')
session['user_id'] = user['user_id']
return redirect(url_for('timeline'))
return render_template('login.html', error=error)
def delete_db():
connection = connect_db()
c = connection.cursor()
print('you must log in as admin to delete the database')
username = raw_input('username: ')
password = getpass.getpass('password: ')
c.execute('SELECT password FROM admin WHERE username='+sqlesc,(username,))
passhash = c.fetchone()
if check_password_hash(passhash[0],password) == True:
a = raw_input('just to double check, you REALLY want to delete everything? (y/n): ')
if a=='y':
c.execute('DROP TABLE playerinfo')
c.execute('DROP TABLE errors')
c.execute('DROP TABLE todo')
c.execute('DROP TABLE blog')
c.execute('DROP TABLE users')
c.execute('DROP TABLE series')
c.execute('DROP TABLE plans')
connection.commit()
connection.close()
print('all (except admin) deleted')
else:
print('incorrect credentials')
def check_password(self, password):
return check_password_hash(self.passwdhash, password)
def check_password_hash(self, passwd_hash, password):
return check_password_hash(passwd_hash, password)
def check_password(self, password):
return check_password_hash(self.password, password)
def login():
if g.user:
return redirect(url_for('home.timeline'))
error = None
if request.method == 'POST':
user = db.session.query(User).filter_by(username=request.form['username']).first()
if user is None:
error = 'Invalid username'
elif not check_password_hash(user.pw_hash, request.form['password']):
error = 'Invalid password'
else:
flash('You were logged in')
session['user_id'] = user.id
return redirect(url_for('home.timeline'))
return render_template('login.html', error=error)
def login():
if g.user:
return redirect(url_for('home.timeline'))
error = None
if request.method == 'POST':
user = db.session.query(User).filter_by(username=request.form['username']).first()
if user is None:
error = 'Invalid username'
elif not check_password_hash(user.pw_hash, request.form['password']):
error = 'Invalid password'
else:
flash('You were logged in')
session['user_id'] = user.id
return redirect(url_for('home.timeline'))
return render_template('login.html', error=error)
def check_bcrypt_password_hash(passwordhash,attempt):
try:
result = bcrypt.check_password_hash(passwordhash,attempt)
except AssertionError:
return None
return result
def check_user_pw(email,password_attempt):
db = get_db()
cur = db.cursor()
cur.execute('SELECT id,password,auth_key FROM users WHERE email='+app.sqlesc,(email,))
result = cur.fetchall()
assert len(result) <= 1
if len(result) == 0:
return {'result':False, 'error':_('Username not found!')}
else:
hash_type = _get_hash_type(result[0][1])
if hash_type == 'sha1':
password_valid = check_password_hash(result[0][1],password_attempt)
if password_valid:
new_hash = generate_bcrypt_password_hash(password_attempt)
cur.execute('UPDATE users SET password='+app.sqlesc+' WHERE email='+app.sqlesc,(new_hash,email))
db.commit()
elif hash_type == 'bcrypt':
password_valid = check_bcrypt_password_hash(result[0][1],password_attempt)
else:
return {'result':None}
if password_valid == True:
if result[0][2] == None:
auth_key = dec2big(random.randint(0,(2**128)))
cur.execute('UPDATE users SET auth_key='+app.sqlesc+', login_time='+app.sqlesc+' WHERE id='+app.sqlesc,(auth_key,time.time(),result[0][0]))
db.commit()
else:
auth_key = result[0][2]
session['logged_in_user']=(result[0][0],auth_key)
return {'result':True}
elif password_valid == None:
return {'result':None}
else:
return {'result':False,'error':_('Incorrect password!')}
def check_password(self, password):
return check_password_hash(self.pwdhash, password)
# p = Place()
# places = p.query("1600 Amphitheater Parkway Mountain View CA")
def update_playerinfo():
if app.config['USE_SQLITE'] == True:
print('This is only for Postgres databases')
return
connection = connect_db()
c = connection.cursor()
c.execute("SELECT * FROM information_schema.columns WHERE table_schema='public' AND table_name='playerinfo'")
returned_database_structure = {row[3].lower():row[7].upper() for row in c.fetchall()}
current_design_structure = {key.lower():database_structure_dict[key].upper() for key in database_structure_dict.keys()}
redundant = {}
incorrect_type = {}
for key in returned_database_structure.keys():
try:
if current_design_structure[key] == returned_database_structure[key]:
#print(key,'matches')
pass
else:
#print(key,'by design:',current_design_structure[key],'db has:',returned_database_structure[key])
incorrect_type[key] = {'should be':current_design_structure[key],'was':returned_database_structure[key]}
del current_design_structure[key]
except KeyError:
#print(key,'in db but not in current design structure')
redundant[key] = {'redundant':returned_database_structure[key]}
not_implemented = current_design_structure
print('not implemented in db:')
for key in not_implemented.keys():
print(key,not_implemented[key])
print('redundant in db:')
for key in redundant.keys():
print(key,redundant[key])
print('incorrect type in db:')
for key in incorrect_type.keys():
print(key,incorrect_type[key])
a = raw_input('Alter database? (y/n): ')
if a == 'y':
print('you must log in as admin to alter the database')
username = raw_input('username: ')
password = getpass.getpass('password: ')
c.execute('SELECT password FROM admin WHERE username='+sqlesc,(username,))
passhash = c.fetchone()
if check_password_hash(passhash[0],password) == True:
print('implementing not-implemented keys (ADDing to database)')
for key in not_implemented.keys():
a = raw_input('Add column '+str(key)+' type '+str(not_implemented[key])+' to playerinfo? (y/n): ')
if a == 'y':
c.execute('ALTER TABLE playerinfo ADD COLUMN '+str(key)+' '+str(not_implemented[key]))
print('done')
print('removing no-longer-necessary keys (DROPping from database)')
for key in redundant.keys():
a = raw_input('Remove column '+str(key)+' from playerinfo? (y/n): ')
if a == 'y':
c.execute('ALTER TABLE playerinfo DROP COLUMN '+str(key))
else:
print('incorrect credentials')
connection.commit()
connection.close()
print('all modifications committed')
def update_users():
if app.config['USE_SQLITE'] == True:
print('This is only for Postgres databases')
return
connection = connect_db()
c = connection.cursor()
c.execute("SELECT * FROM information_schema.columns WHERE table_schema='public' AND table_name='users'")
returned_database_structure = {row[3].lower():row[7].upper() for row in c.fetchall()}
current_design_structure = {key.lower():users_structure_dict[key].upper() for key in users_structure_dict.keys()}
redundant = {}
incorrect_type = {}
for key in returned_database_structure.keys():
try:
if current_design_structure[key] == returned_database_structure[key]:
#print(key,'matches')
pass
else:
#print(key,'by design:',current_design_structure[key],'db has:',returned_database_structure[key])
incorrect_type[key] = {'should be':current_design_structure[key],'was':returned_database_structure[key]}
del current_design_structure[key]
except KeyError:
#print(key,'in db but not in current design structure')
redundant[key] = {'redundant':returned_database_structure[key]}
not_implemented = current_design_structure
print('not implemented in db:')
for key in not_implemented.keys():
print(key,not_implemented[key])
print('redundant in db:')
for key in redundant.keys():
print(key,redundant[key])
print('incorrect type in db:')
for key in incorrect_type.keys():
print(key,incorrect_type[key])
a = raw_input('Alter database? (y/n): ')
if a == 'y':
print('you must log in as admin to alter the database')
username = raw_input('username: ')
password = getpass.getpass('password: ')
c.execute('SELECT password FROM admin WHERE username='+sqlesc,(username,))
passhash = c.fetchone()
if check_password_hash(passhash[0],password) == True:
print('implementing not-implemented keys (ADDing to database)')
for key in not_implemented.keys():
a = raw_input('Add column '+str(key)+' type '+str(not_implemented[key])+' to users? (y/n): ')
if a == 'y':
c.execute('ALTER TABLE users ADD COLUMN '+str(key)+' '+str(not_implemented[key]))
print('done')
print('removing no-longer-necessary keys (DROPping from database)')
for key in redundant.keys():
a = raw_input('Remove column '+str(key)+' from users? (y/n): ')
if a == 'y':
c.execute('ALTER TABLE users DROP COLUMN '+str(key))
else:
print('incorrect credentials')
connection.commit()
connection.close()
print('all modifications committed')