def signup():
if request.method=='POST':
users = mongo.db.users
api_list=[]
existing_user = users.find({'$or':[{"username":request.form['username']} ,{"email":request.form['email']}]})
for i in existing_user:
# print (str(i))
api_list.append(str(i))
# print (api_list)
if api_list == []:
users.insert({
"email": (request.form['email']).lower(),
"id": random.randint(1,1000),
"name": request.form['name'],
"password": bcrypt.hashpw(request.form['pass'].encode('utf-8'), bcrypt.gensalt()),
"username": request.form['username']
})
session['username'] = request.form['username']
return redirect(url_for('home'))
return 'That user already exists'
else :
return render_template('signup.html')
python类hashpw()的实例源码
def do_admin_login():
users = mongo.db.users
api_list=[]
login_user = users.find({'username': request.form['username']})
for i in login_user:
api_list.append(i)
print (api_list)
if api_list != []:
#print (api_list[0]['password'].decode('utf-8'), bcrypt.hashpw(request.form['password'].encode('utf-8'), api_list[0]['password']).decode('utf-8'))
if api_list[0]['password'].decode('utf-8') == bcrypt.hashpw(request.form['password'].encode('utf-8'), api_list[0]['password']).decode('utf-8'):
session['logged_in'] = api_list[0]['username']
return redirect(url_for('index'))
return 'Invalide username/password!'
else:
flash("Invalid Authentication")
return 'Invalid User!'
def signup():
if request.method=='POST':
users = mongo.db.users
api_list=[]
existing_user = users.find({'$or':[{"username":request.form['username']} ,{"email":request.form['email']}]})
for i in existing_user:
# print (str(i))
api_list.append(str(i))
# print (api_list)
if api_list == []:
users.insert({
"email": (request.form['email']).lower(),
"id": random.randint(1,1000),
"name": request.form['name'],
"password": bcrypt.hashpw(request.form['pass'].encode('utf-8'), bcrypt.gensalt()),
"username": request.form['username']
})
session['username'] = request.form['username']
return redirect(url_for('home'))
return 'That user already exists'
else :
return render_template('signup.html')
def signup():
if request.method=='POST':
users = mongo.db.users
api_list=[]
existing_user = users.find({'$or':[{"username":request.form['username']} ,{"email":request.form['email']}]})
for i in existing_user:
# print (str(i))
api_list.append(str(i))
# print (api_list)
if api_list == []:
users.insert({
"email": (request.form['email']).lower(),
"id": random.randint(1,1000),
"name": request.form['name'],
"password": bcrypt.hashpw(request.form['pass'].encode('utf-8'), bcrypt.gensalt()),
"username": request.form['username']
})
session['username'] = request.form['username']
return redirect(url_for('home'))
return 'That user already exists'
else :
return render_template('signup.html')
def login(self, postData):
status = True
errorlist = []
user = User.objects.filter(username = postData['username'])
if len(postData['username']) < 1:
errorlist.append('Must fill in Username!')
status = False
if len(postData['password']) < 1:
errorlist.append('Must fill in Password!')
status = False
else:
if len(user) < 1:
errorlist.append('Username not registered!')
status = False
if status == False:
return {'errors': errorlist}
else:
if bcrypt.hashpw(postData['password'].encode(), user[0].password.encode()) == user[0].password:
return {'login': True}
else:
status = False
errorlist.append('Password does not match username!')
return {'errors': errorlist}
def fuzz_verifier_pybcrypt(self):
# test against py-bcrypt, if available
from passlib.handlers.bcrypt import IDENT_2, IDENT_2A, IDENT_2X, IDENT_2Y
from passlib.utils import to_native_str
try:
import bcrypt
except ImportError:
return
if hasattr(bcrypt, "_ffi"):
return
def check_pybcrypt(secret, hash):
"pybcrypt"
secret = to_native_str(secret, self.fuzz_password_encoding)
if hash.startswith(IDENT_2Y):
hash = IDENT_2A + hash[4:]
try:
return bcrypt.hashpw(secret, hash) == hash
except ValueError:
raise ValueError("py-bcrypt rejected hash: %r" % (hash,))
return check_pybcrypt
def _calc_checksum_bcrypt(self, secret):
# bcrypt behavior:
# hash must be ascii bytes
# secret must be bytes
# returns bytes
if self.ident == IDENT_2:
# bcrypt doesn't support $2$ hashes; but we can fake $2$ behavior
# using the $2a$ algorithm, by repeating the password until
# it's at least 72 chars in length.
if secret:
secret = repeat_string(secret, 72)
config = self._get_config(IDENT_2A)
else:
config = self._get_config()
if isinstance(config, unicode):
config = config.encode("ascii")
hash = _bcrypt.hashpw(secret, config)
assert hash.startswith(config) and len(hash) == len(config)+31
assert isinstance(hash, bytes)
return hash[-31:].decode("ascii")
def register():
username = loggedIn(session, LoggedIn)
if username != False:
return render_template('index.html', username=username)
form = RegisterForm()
if form.validate_on_submit():
hashedPwd = hashpw(str(request.form['password']).encode('utf-8'), gensalt()) # encrypt user's password
user = User(username=request.form['username'], password=hashedPwd) # create user
db.session.add(user)
db.session.commit() # save new user in User table
new_user = User.query.filter_by(username=request.form['username']).first() # new profile
user_profile = Profile(user_id=new_user.id, name="no-name", surname="no-surname", avatar="saitama-batman.jpg", description="no-description", skills="no-skills,")
db.session.add(user_profile)
db.session.commit() # save new profile in Profile table
return render_template('registration_success.html', username=request.form['username'])
return render_template('register.html', form=form)
def manage_users_add():
if request.method == 'POST':
u = User()
error = None
u.name = request.form['username'].lower()
if u.name is None:
error = "Username not unique!"
if request.form['password1'] == request.form['password2']:
#u.password = request.form['password1']
u.password = bcrypt.hashpw(request.form['password1'], bcrypt.gensalt())
else:
error = "Passwords do not match!"
u.longname = request.form['longname']
u.email = request.form['email']
u.rfid_id = request.form['rfid_id']
if error is None:
add_user(u)
return render_template('manage_users_add.html', success="User created!", user=get_user_by_name(session.get('name')));
return render_template('manage_users_add.html', error=error, user=get_user_by_name(session.get('name')))
return render_template('manage_users_add.html', user=get_user_by_name(session.get('name')))
test_handlers_bcrypt.py 文件源码
项目:python-flask-security
作者: weinbergdavid
项目源码
文件源码
阅读 19
收藏 0
点赞 0
评论 0
def fuzz_verifier_pybcrypt(self):
# test against py-bcrypt, if available
from passlib.handlers.bcrypt import IDENT_2, IDENT_2A, IDENT_2B, IDENT_2X, IDENT_2Y, _detect_pybcrypt
from passlib.utils import to_native_str
try:
import bcrypt
except ImportError:
return
if not _detect_pybcrypt():
return
def check_pybcrypt(secret, hash):
"""pybcrypt"""
secret = to_native_str(secret, self.fuzz_password_encoding)
if len(secret) > 200: # vulnerable to wraparound bug
secret = secret[:200]
if hash.startswith((IDENT_2B, IDENT_2Y)):
hash = IDENT_2A + hash[4:]
try:
return bcrypt.hashpw(secret, hash) == hash
except ValueError:
raise ValueError("py-bcrypt rejected hash: %r" % (hash,))
return check_pybcrypt
def reset_password(token):
form = ResetForm()
tokenemail = confirm_token(token)
if tokenemail is False:
flash('The confirmation link is invalid or has expired.', 'danger')
return redirect(url_for('regular.home'))
user = User.query.filter_by(email = tokenemail).first()
if user:
if request.method == 'POST':
if form.validate_on_submit():
user.pw_hash = bcrypt.hashpw(form.password.data.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')
db.session.commit()
login_user(user,remember=True)
flash('Your password has been reset.')
return redirect(url_for('regular.home'))
else:
return render_template('reset.html', form=form, token=token)
elif request.method == 'GET':
return render_template('reset.html', form=form, token=token)
else:
flash('The confirmation link is invalid or has expired.', 'danger')
def process_login():
"""Processes user input and either logs user in if input is in database"""
# gets the user input from the username field and looks it up in the database
username = request.form.get('username')
user = User.query.filter_by(username=username).first()
# if username entered exists in db, gets the password entered and compares
# it to the one in the database
if user:
# if password is correct, adds user to the current session and redirects to home page
if bcrypt.hashpw(request.form.get('password').encode('utf-8'), user.password.encode('utf-8')).decode() == user.password:
session['logged_in'] = user.user_id
print 'logged in'
return jsonify(session)
# if password is incorrect, redirects to login page
else:
return 'error'
# if username is not in the database, redirects to the registration form
else:
return 'error'
def update_user():
"""Saves updated user info."""
user_id = request.form.get('id')
user_to_update = User.query.get(int(user_id))
if bcrypt.hashpw(request.form.get('password').encode('utf-8'), user_to_update.password.encode('utf-8')).decode() == user_to_update.password:
if request.form.get('email'):
user_to_update.email = request.form.get('email')
if request.form.get('phone'):
user_to_update.phone = request.form.get('phone')
else:
return "bad password"
db.session.commit()
return "ok"
# PlantUser Routes *********************************
def post(self):
username = tornado.escape.xhtml_escape(self.get_argument("username", ""))
password = tornado.escape.xhtml_escape(self.get_argument("password", "")).encode('utf-8')
returnUrl = self.get_argument("returnUrl", "/")
self.logger.info("login request with username={0} from ip={1}".format(username, self.request.remote_ip))
if username == "admin" and bcrypt.hashpw(password, self.adminPasswordHash) == self.adminPasswordHash:
self.set_secure_cookie("user", username, expires_days=1)
self.redirect(returnUrl)
else:
self.logger.warning("Invalid login/password request with username={0} from ip={1}".format(username, self.request.remote_ip))
self.render("views/login.html", errormsg="Invalid username or password.", returnUrl=returnUrl)
def hash_password(password):
print(password, bcrypt.hashpw(password, bcrypt.gensalt()))
def confirm_password(attempt, password_hash):
"""
Verifies the password attempt
Args:
attempt: the password attempt
password_hash: the real password pash
"""
return bcrypt.hashpw(attempt.encode('utf-8'), password_hash) == password_hash
def hash_password(password):
"""
Hash plaintext password.
Args:
password: plaintext password
Returns:
Secure hash of password.
"""
return bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt(8))