def password_hash(password): """Hash the password, using bcrypt+sha256. .. versionchanged:: 1.1.0 :param str password: Password in plaintext :return: password hash :rtype: str """ try: return bcrypt_sha256.encrypt(password) except TypeError: return bcrypt_sha256.encrypt(password.decode('utf-8'))
def admin_user(userid): user = Users.query.filter_by(id=userid).first() if request.method == 'GET': solves = Solves.query.filter_by(userid=userid).all() solve_ids = [s.chalid for s in solves] missing = Challenges.query.filter( not_(Challenges.id.in_(solve_ids) ) ).all() last_seen = db.func.max(Tracking.date).label('last_seen') addrs = db.session.query(Tracking.ip, last_seen) \ .filter_by(user=userid) \ .group_by(Tracking.ip) \ .order_by(last_seen.desc()).all() wrong_keys = WrongKeys.query.filter_by(userid=userid).order_by(WrongKeys.date.asc()).all() awards = Awards.query.filter_by(userid=userid).order_by(Awards.date.asc()).all() score = user.score() place = user.place() return render_template('admin/user.html', solves=solves, team=user, addrs=addrs, score=score, missing=missing, place=place, wrong_keys=wrong_keys, awards=awards) elif request.method == 'POST': admin_user = request.form.get('admin', None) if admin_user: admin_user = True if admin_user == 'true' else False user.admin = admin_user # Set user.banned to hide admins from scoreboard user.banned = admin_user db.session.commit() db.session.close() return jsonify({'data': ['success']}) name = request.form.get('name', None) password = request.form.get('password', None) email = request.form.get('email', None) # website = request.form.get('website', None) # affiliation = request.form.get('affiliation', None) # country = request.form.get('country', None) errors = [] name_used = Users.query.filter(Users.name == name).first() if name_used and int(name_used.id) != int(userid): errors.append('That name is taken') email_used = Users.query.filter(Users.email == email).first() if email_used and int(email_used.id) != int(userid): errors.append('That email is taken') if errors: db.session.close() return jsonify({'data':errors}) else: user.name = name user.email = email if password: user.password = bcrypt_sha256.encrypt(password) # user.website = website # user.affiliation = affiliation # user.country = country db.session.commit() db.session.close() return jsonify({'data':['success']})
def reset_password(data=None): if data is not None and request.method == "GET": return render_template('reset_password.html', mode='set') if data is not None and request.method == "POST": try: s = TimedSerializer(app.config['SECRET_KEY']) name = s.loads(data.decode('base64'), max_age=1800) except BadTimeSignature: return render_template('reset_password.html', errors=['Your link has expired']) team = Teams.query.filter_by(name=name).first() team.password = bcrypt_sha256.encrypt(request.form['password'].strip()) db.session.commit() db.session.close() return redirect(url_for('auth.login')) if request.method == 'POST': email = request.form['email'].strip() team = Teams.query.filter_by(email=email).first() if not team: return render_template('reset_password.html', errors=['Check your email']) s = TimedSerializer(app.config['SECRET_KEY']) token = s.dumps(team.name) text = """ Did you initiate a password reset? {0}/reset_password/{1} """.format(app.config['HOST'], token.encode('base64')) sendmail(email, text) return render_template('reset_password.html', errors=['Check your email']) return render_template('reset_password.html')
def register(): form = RegisterForm(request.form) if request.method == 'POST' and form.validate(): name = form.name.data username = form.username.data email = form.email.data password = bcrypt_sha256.encrypt(str(form.password.data)) # Create cursor cur = mysql.connection.cursor() # Query cur.execute( "INSERT INTO users(name, username, email, password) VALUES(%s, %s, %s, %s)", (name, username, email, password)) # COmmit to DB mysql.connection.commit() # Close connection cur.close() flash('You are now registered and can log in', 'success') return redirect(url_for('login')) return render_template('register.html', form=form)
def add_user(self): """Adds Test user to database""" try: user = User.query.filter_by(Client_id='testuser').first() db.session.delete(user) db.session.commit() user2 = User.query.filter_by(Client_id='testuser2').first() db.session.delete(user2) db.session.commit() except: pass pass_hash = bcrypt_sha256.encrypt("password", rounds=12) test_user_insert = User(Client_id='testuser', Password=pass_hash, api_key='api-key', current_login_ip='127.0.0.1') db.session.add(test_user_insert) db.session.commit() test_user_insert_2 = User(Client_id='testuser2', Password=pass_hash, api_key='api-key', current_login_ip='127.0.0.2') db.session.add(test_user_insert_2) db.session.commit() return test_user_insert
def check(self, value): self.txt_error='' self.error=False value.strip() if value=='': if self.model!=None: if self.model.updated==True: self.required=False self.check_blank=True return "" else: self.txt_error="The field is empty" self.error=True else: self.txt_error="The field is empty" self.error=True else: value = bcrypt_sha256.encrypt(value) return value
def reset_password(data=None): if utils.get_config('no_emails'): return redirect(url_for('auth.login')) logger = logging.getLogger('logins') if data is not None: try: s = TimedSerializer(app.config['SECRET_KEY']) name = s.loads(utils.base64decode(data, urldecode=True), max_age=1800) except BadTimeSignature: return render_template('reset_password.html', errors=['Your link has expired']) except (BadSignature, TypeError, base64.binascii.Error): return render_template('reset_password.html', errors=['Your reset token is invalid']) if request.method == "GET": return render_template('reset_password.html', mode='set') if request.method == "POST": team = Teams.query.filter_by(name=name).first_or_404() team.password = bcrypt_sha256.encrypt( request.form['password'].strip()) db.session.commit() logger.warn( "[{date}] {ip} - successful password reset for {username}". format(date=time.strftime("%m/%d/%Y %X"), ip=utils.get_ip(), username=team.name.encode('utf-8'))) db.session.close() return redirect(url_for('auth.login')) if request.method == 'POST': email = request.form['email'].strip() team = Teams.query.filter_by(email=email).first() errors = [] if utils.can_send_mail() is False: return render_template( 'reset_password.html', errors=[ 'Email could not be sent due to server misconfiguration' ]) if not team: return render_template( 'reset_password.html', errors=[ 'If that account exists you will receive an email, please check your inbox' ]) utils.forgot_password(email, team.name) return render_template( 'reset_password.html', errors=[ 'If that account exists you will receive an email, please check your inbox' ]) return render_template('reset_password.html')
def __init__(self, name, email, password, bracket, country, affiliation): self.name = name self.email = email self.password = bcrypt_sha256.encrypt(str(password)) self.bracket = bracket self.country = country self.affiliation = affiliation
def reset_password(data=None): if data is not None and request.method == "GET": return render_template('reset_password.html', mode='set') if data is not None and request.method == "POST": try: s = TimedSerializer(app.config['SECRET_KEY']) name = s.loads(urllib.unquote_plus(data.decode('base64')), max_age=1800) except BadTimeSignature: return render_template('reset_password.html', errors=['Your link has expired']) except: return render_template('reset_password.html', errors=['Your link appears broken, please try again.']) team = Teams.query.filter_by(name=name).first_or_404() team.password = bcrypt_sha256.encrypt(request.form['password'].strip()) db.session.commit() db.session.close() return redirect(url_for('auth.login')) if request.method == 'POST': email = request.form['email'].strip() team = Teams.query.filter_by(email=email).first() if not team: return render_template('reset_password.html', errors=['If that account exists you will receive an email, please check your inbox']) s = TimedSerializer(app.config['SECRET_KEY']) token = s.dumps(team.name) text = """ Did you initiate a password reset? {0}/{1} """.format(url_for('auth.reset_password', _external=True), urllib.quote_plus(token.encode('base64'))) utils.sendmail(email, text) return render_template('reset_password.html', errors=['If that account exists you will receive an email, please check your inbox']) return render_template('reset_password.html')
def admin_user(userid): user = Users.query.filter_by(id=userid).first() if request.method == 'GET': solves = Solves.query.filter_by(userid=userid).all() solve_ids = [s.chalid for s in solves] missing = Challenges.query.filter( not_(Challenges.id.in_(solve_ids) ) ).all() last_seen = db.func.max(Tracking.date).label('last_seen') addrs = db.session.query(Tracking.ip, last_seen) \ .filter_by(user=userid) \ .group_by(Tracking.ip) \ .order_by(last_seen.desc()).all() wrong_keys = WrongKeys.query.filter_by(userid=userid).order_by(WrongKeys.date.asc()).all() awards = Awards.query.filter_by(userid=userid).order_by(Awards.date.asc()).all() score = user.score() place = user.place() return render_template('admin/user.html', solves=solves, user=user, addrs=addrs, score=score, missing=missing, place=place, wrong_keys=wrong_keys, awards=awards) elif request.method == 'POST': admin_user = request.form.get('admin', None) if admin_user: admin_user = True if admin_user == 'true' else False user.admin = admin_user # Set user.banned to hide admins from scoreboard user.banned = admin_user db.session.commit() db.session.close() return jsonify({'data': ['success']}) name = request.form.get('name', None) password = request.form.get('password', None) email = request.form.get('email', None) website = request.form.get('website', None) affiliation = request.form.get('affiliation', None) country = request.form.get('country', None) errors = [] name_used = Users.query.filter(Users.name == name).first() if name_used and int(name_used.id) != int(userid): errors.append('That name is taken') email_used = Users.query.filter(Users.email == email).first() if email_used and int(email_used.id) != int(userid): errors.append('That email is taken') if errors: db.session.close() return jsonify({'data':errors}) else: user.name = name user.email = email if password: user.password = bcrypt_sha256.encrypt(password) user.website = website user.affiliation = affiliation user.country = country db.session.commit() db.session.close() return jsonify({'data':['success']})
def reset_password(): try: email = request.json['email'] code = request.json['code'] password = request.json['password'] temp_user = user_dao.get_by_email(email) if temp_user is None: return jsonify('User with this email doesn\'t exists!'), 400 else: user = temp_user.serialize temp_pr = password_reset_dao.get(user['id']) if temp_pr is None: return jsonify('No password reset request for this user!'), 400 else: pr = temp_pr.serialize if pr['code'] == code: # Encypt password encrypted_password = bcrypt_sha256.encrypt(password) temp_user.password = encrypted_password user_dao.update(temp_user) password_reset_dao.delete(temp_pr) return jsonify('Password reset successful!'), 202 else: return jsonify('Invalid verification code!'), 400 except KeyError as ke: passwordreset_sessionDB.rollback() return jsonify('Attribute ' + ke.args[0] + ' missing!'), 400
def create_user(): try: username = request.json["username"] password = request.json["password"] first_name = request.json["first_name"] last_name = request.json["last_name"] email = request.json["email"] val = validate(username, password, first_name, last_name, email) if val is not None: return jsonify(val[0]), val[1] # Encypt password encrypted_password = bcrypt_sha256.encrypt(password) user = User(username, encrypted_password, first_name, last_name, email) user_dao.save(user) return jsonify('User successfully created'), 201 except KeyError as ke: user_sessionDB.rollback() user_sessionDB.close() return jsonify('Attribute ' + ke.args[0] + ' missing!'), 400 except IntegrityError as ie: user_sessionDB.rollback() user_sessionDB.close() error = ie.args[0].split("\"") print error[1] return jsonify(error[1]), 500
def __init__(self, username, password, firstname, lastname, email, zip): self.username = username self.password = bcrypt_sha256.encrypt( password) # 11 password bcrypt protected (random salt) self.firstname = firstname self.lastname = lastname self.zip = zip
def reset_password(data=None): if data is not None and request.method == "GET": return render_template("reset_password.html", mode="set") if data is not None and request.method == "POST": try: s = TimedSerializer(app.config["SECRET_KEY"]) name = s.loads(data.decode("base64"), max_age=1800) except BadTimeSignature: return render_template("reset_password.html", errors=["Your link has expired"]) team = Teams.query.filter_by(name=name).first() team.password = bcrypt_sha256.encrypt(request.form["password"].strip()) db.session.commit() db.session.close() return redirect(url_for("auth.login")) if request.method == "POST": email = request.form["email"].strip() team = Teams.query.filter_by(email=email).first() if not team: return render_template("reset_password.html", errors=["Check your email"]) s = TimedSerializer(app.config["SECRET_KEY"]) token = s.dumps(team.name) text = """ Did you initiate a password reset? {0}/reset_password/{1} """.format( url_for("auth.reset_password", _external=True), token.encode("base64") ) sendmail(email, text) return render_template("reset_password.html", errors=["Check your email"]) return render_template("reset_password.html")
def profile(): if authed(): if request.method == "POST": errors = [] name = request.form.get('name') email = request.form.get('email') website = request.form.get('website') affiliation = request.form.get('affiliation') country = request.form.get('country') user = Teams.query.filter_by(id=session['id']).first() names = Teams.query.filter_by(name=name).first() emails = Teams.query.filter_by(email=email).first() valid_email = re.match("[^@]+@[^@]+\.[^@]+", email) name_len = len(request.form['name']) == 0 if ('password' in request.form.keys() and not len(request.form['password']) == 0) and \ (not bcrypt_sha256.verify(request.form.get('confirm').strip(), user.password)): errors.append("Your old password doesn't match what we have.") if not valid_email: errors.append("That email doesn't look right") if names and name!=session['username']: errors.append('That team name is already taken') if emails and emails.id != session['id']: errors.append('That email has already been used') if name_len: errors.append('Pick a longer team name') if website.strip() and not validate_url(website): errors.append("That doesn't look like a valid URL") if len(errors) > 0: return render_template('profile.html', name=name, email=email, website=website, affiliation=affiliation, country=country, errors=errors) else: team = Teams.query.filter_by(id=session['id']).first() team.name = name team.email = email session['username'] = name if 'password' in request.form.keys() and not len(request.form['password']) == 0: team.password = bcrypt_sha256.encrypt(request.form.get('password')) team.website = website team.affiliation = affiliation team.country = country db.session.commit() db.session.close() return redirect('/profile') else: user = Teams.query.filter_by(id=session['id']).first() name = user.name email = user.email website = user.website affiliation = user.affiliation country = user.country return render_template('profile.html', name=name, email=email, website=website, affiliation=affiliation, country=country) else: return redirect('/login')
def get(self): """Set a new token for the logged in user and return the token.""" token = uuid.uuid4().hex user = self.current_user_model with self.session.begin(): user.token = bcrypt_sha256.encrypt(token).encode() user.token_expiration = datetime.now() + timedelta(days=60) self.write(OrderedDict((("token", token), ("expires_on", user.token_expiration.isoformat()))))
def admin_team(teamid): user = Teams.query.filter_by(id=teamid).first() solves = Solves.query.filter_by(teamid=teamid).all() addrs = Tracking.query.filter_by(team=teamid).order_by( Tracking.date.desc()).group_by(Tracking.ip).all() wrong_keys = WrongKeys.query.filter_by(team=teamid).order_by( WrongKeys.date.desc()).all() score = user.score() place = user.place() if request.method == 'GET': return render_template('admin/team.html', solves=solves, team=user, addrs=addrs, score=score, place=place, wrong_keys=wrong_keys) elif request.method == 'POST': admin_user = request.form.get('admin', "false") admin_user = 1 if admin_user == "true" else 0 if admin: user.admin = 1 user.banned = 1 db.session.commit() return jsonify({'data': ['success']}) name = request.form.get('name', None) password = request.form.get('password', None) email = request.form.get('email', None) website = request.form.get('website', None) affiliation = request.form.get('affiliation', None) country = request.form.get('country', None) errors = [] name_used = Teams.query.filter(Teams.name == name).first() if name_used and int(name_used.id) != int(teamid): errors.append('That name is taken') email_used = Teams.query.filter(Teams.email == email).first() if email_used and int(email_used.id) != int(teamid): errors.append('That email is taken') if errors: db.session.close() return jsonify({'data': errors}) else: user.name = name user.email = email if password: user.password = bcrypt_sha256.encrypt(password) user.website = website user.affiliation = affiliation user.country = country db.session.commit() db.session.close() return jsonify({'data': ['success']})
def __init__(self, name, email, password, affiliation, bracket, country, website): self.name = name self.email = email self.password = bcrypt_sha256.encrypt(str(password)) self.affiliation = affiliation self.bracket = bracket self.country = country self.website = website
def setup(self, password=None, **kwargs): """ Given a bunch of information, setup the auth provider for user """ if not password: raise AuthSetupMissingInfo("No password provided") key = bcrypt_sha256.encrypt(password) data = dict() return key, data
def Index(): """Login portal for clients""" if current_user.is_authenticated: """If client is authenticated, return them back to their portal case view""" return render_template("Client_View.html", title='client_view', Client_id=current_user.Client_id, api_key=current_user.api_key) form = LoginForm() if (request.method == 'POST') and (form.validate_on_submit()): Client_id = form.Client_id.data Password = form.Password.data user = User.query.filter_by(Client_id=Client_id).first() if not user and app.config['NO_PASSWORD'] == True: """Allow anyone to create their own account""" pass_hash = bcrypt_sha256.encrypt(Password, rounds=12) user = User(Client_id=Client_id, Password=pass_hash, api_key='') Sample_date = Client_View(client_id=Client_id, case_name='sample case', priority='1', target_date='10/7/2016', product_area='Engineering', status='In Progress', description='something') db.session.add(user) db.session.commit() db.session.add(Sample_date) db.session.commit() """ If user is a vaild account, proceed with verifying \ their credentials and provide them the API key""" if user: if bcrypt_sha256.verify( Password, user.Password) and user.Client_id == Client_id: signer = TimestampSigner(SECRET_KEY) API_KEY = ''.join([ random.choice(string.ascii_letters + string.digits) for n in xrange(30) ]) user.api_key = signer.sign(API_KEY) user.current_login_ip = request.remote_addr db.session.commit() login_user(user) flash('You have successfully logged in') return render_template("Client_View.html", title='client_view', Client_id=Client_id, api_key=user.api_key) if form.errors: flash(form.errors, 'danger') flash( 'Incorrect Credentials, please enter the correct Client Id and Password' ) return render_template('Index.html', form=form) if form.errors: flash(form.errors, 'danger') return render_template('Index.html', form=form)
def encrypt_secret(secret): """ Generate a secure (one-way) hash from the given secret. Suitable for storing passwords. Returns: The hashed secret. """ return bcrypt_sha256.encrypt(secret, rounds=8)
def profile(): if authed(): if request.method == "POST": errors = [] name = request.form.get('name') email = request.form.get('email') user = Students.query.filter_by(id=session['id']).first() if not get_config('prevent_name_change'): names = Students.query.filter_by(name=name).first() name_len = len(request.form['name']) == 0 emails = Students.query.filter_by(email=email).first() valid_email = re.match(r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)", email) if ('password' in request.form.keys() and not len(request.form['password']) == 0) and \ (not bcrypt_sha256.verify(request.form.get('confirm').strip(), user.password)): errors.append("Your old password doesn't match what we have.") if not valid_email: errors.append("That email doesn't look right") if not get_config('prevent_name_change') and names and name != session['username']: errors.append('That student name is already taken') if emails and emails.id != session['id']: errors.append('That email has already been used') if not get_config('prevent_name_change') and name_len: errors.append('Pick a longer student name') if len(errors) > 0: return render_template('profile.html', name=name, email=email, errors=errors) else: student = Students.query.filter_by(id=session['id']).first() if not get_config('prevent_name_change'): student.name = name if student.email != email.lower(): student.email = email.lower() if get_config('verify_emails'): student.verified = False session['username'] = student.name if 'password' in request.form.keys() and not len(request.form['password']) == 0: student.password = bcrypt_sha256.encrypt(request.form.get('password')) db.session.commit() db.session.close() return redirect(url_for('views.profile')) else: user = Students.query.filter_by(id=session['id']).first() name = user.name email = user.email prevent_name_change = get_config('prevent_name_change') confirm_email = get_config('verify_emails') and not user.verified return render_template('profile.html', name=name, email=email, prevent_name_change=prevent_name_change, confirm_email=confirm_email) else: return redirect(url_for('auth.login'))
def password_hash(password): """Hash the password, using bcrypt+sha256. .. versionchanged:: 1.1.0 :param str password: Password in plaintext :return: password hash :rtype: str """ return bcrypt_sha256.encrypt(password)
def admin_team(teamid): user = Teams.query.filter_by(id=teamid).first() if request.method == 'GET': solves = Solves.query.filter_by(teamid=teamid).all() solve_ids = [s.chalid for s in solves] missing = Challenges.query.filter( not_(Challenges.id.in_(solve_ids) ) ).all() addrs = Tracking.query.filter_by(team=teamid).order_by(Tracking.date.desc()).group_by(Tracking.ip).all() wrong_keys = WrongKeys.query.filter_by(teamid=teamid).order_by(WrongKeys.date.asc()).all() awards = Awards.query.filter_by(teamid=teamid).order_by(Awards.date.asc()).all() score = user.score() place = user.place() return render_template('admin/team.html', solves=solves, team=user, addrs=addrs, score=score, missing=missing, place=place, wrong_keys=wrong_keys, awards=awards) elif request.method == 'POST': admin_user = request.form.get('admin', None) if admin_user: admin_user = 1 if admin_user == "true" else 0 user.admin = admin_user user.banned = admin_user db.session.commit() return jsonify({'data': ['success']}) name = request.form.get('name', None) password = request.form.get('password', None) email = request.form.get('email', None) website = request.form.get('website', None) affiliation = request.form.get('affiliation', None) country = request.form.get('country', None) errors = [] name_used = Teams.query.filter(Teams.name == name).first() if name_used and int(name_used.id) != int(teamid): errors.append('That name is taken') email_used = Teams.query.filter(Teams.email == email).first() if email_used and int(email_used.id) != int(teamid): errors.append('That email is taken') if errors: db.session.close() return jsonify({'data':errors}) else: user.name = name user.email = email if password: user.password = bcrypt_sha256.encrypt(password) user.website = website user.affiliation = affiliation user.country = country db.session.commit() db.session.close() return jsonify({'data':['success']})
def get(self): """Set a new token for the logged in user and return the token.""" token = uuid.uuid4().hex user = self.current_user_model with self.session.begin(): user.token = bcrypt_sha256.encrypt(token).encode() user.token_expiration = datetime.now() + timedelta(days=60) self.write(OrderedDict(( ('token', token), ('expires_on', user.token_expiration.isoformat()), )))
def profile(): if authed(): if request.method == "POST": errors = [] name = request.form.get('name') email = request.form.get('email') website = request.form.get('website') affiliation = request.form.get('affiliation') country = request.form.get('country') names = Teams.query.filter_by(name=name).first() emails = Teams.query.filter_by(email=email).first() valid_email = re.match("[^@]+@[^@]+\.[^@]+", email) name_len = len(request.form['name']) == 0 if not bcrypt_sha256.verify(request.form.get('confirm').strip(), names.password): errors.append("Your old password doesn't match what we have.") if not valid_email: errors.append("That email doesn't look right") if names and name!=session['username']: errors.append('That team name is already taken') if emails and emails.id != session['id']: errors.append('That email has already been used') if name_len: errors.append('Pick a longer team name') if not validate_url(website): errors.append("That doesn't look like a valid URL") if len(errors) > 0: return render_template('profile.html', name=name, email=email, website=website, affiliation=affiliation, country=country, errors=errors) else: team = Teams.query.filter_by(id=session['id']).first() team.name = name team.email = email if 'password' in request.form.keys() and not len(request.form['password']) == 0: team.password = bcrypt_sha256.encrypt(request.form.get('password')) team.website = website team.affiliation = affiliation team.country = country db.session.commit() db.session.close() return redirect('/profile') else: user = Teams.query.filter_by(id=session['id']).first() name = user.name email = user.email website = user.website affiliation = user.affiliation country = user.country return render_template('profile.html', name=name, email=email, website=website, affiliation=affiliation, country=country) else: return redirect('/login')
def reset_password(data=None): logger = logging.getLogger('logins') if data is not None and request.method == "GET": return render_template('reset_password.html', mode='set') if data is not None and request.method == "POST": try: s = TimedSerializer(app.config['SECRET_KEY']) name = s.loads(utils.base64decode(data, urldecode=True), max_age=1800) except BadTimeSignature: return render_template('reset_password.html', errors=['Your link has expired']) except: return render_template( 'reset_password.html', errors=['Your link appears broken, please try again.']) team = Teams.query.filter_by(name=name).first_or_404() team.password = bcrypt_sha256.encrypt(request.form['password'].strip()) db.session.commit() logger.warn( "[{date}] {ip} - successful password reset for {username}".format( date=time.strftime("%m/%d/%Y %X"), ip=utils.get_ip(), username=team.name.encode('utf-8'))) db.session.close() return redirect(url_for('auth.login')) if request.method == 'POST': email = request.form['email'].strip() team = Teams.query.filter_by(email=email).first() if not team: return render_template( 'reset_password.html', errors=[ 'If that account exists you will receive an email, please check your inbox' ]) s = TimedSerializer(app.config['SECRET_KEY']) token = s.dumps(team.name) text = """ Did you initiate a password reset? {0}/{1} """.format(url_for('auth.reset_password', _external=True), utils.base64encode(token, urlencode=True)) utils.sendmail(email, text) return render_template( 'reset_password.html', errors=[ 'If that account exists you will receive an email, please check your inbox' ]) return render_template('reset_password.html')
def __init__(self, fname, affiliation, year, city, gender, name, email, password, user_type): self.fname = fname self.affiliation = affiliation self.year = year self.city = city self.gender = gender self.name = name self.email = email self.password = bcrypt_sha256.encrypt(str(password)) if user_type == 'M': self.mentor = True elif user_type == 'A': self.admin = True
def __init__(self, name, email, password, website='', affiliation='', country=''): self.name = name self.email = email self.password = bcrypt_sha256.encrypt(str(password)) self.website = website self.affiliation = affiliation self.country = country
def reset_password(data=None): if data is not None: try: name = unserialize(data, max_age=1800) except (BadTimeSignature, SignatureExpired): return render_template('reset_password.html', errors=['Your link has expired']) except (BadSignature, TypeError, base64.binascii.Error): return render_template('reset_password.html', errors=['Your reset token is invalid']) if request.method == "GET": return render_template('reset_password.html', mode='set') if request.method == "POST": team = Users.query.filter_by(name=name).first_or_404() team.password = bcrypt_sha256.encrypt( request.form['password'].strip()) db.session.commit() log('logins', format="[{date}] {ip} - successful password reset for {name}") db.session.close() return redirect(url_for('auth.login')) if request.method == 'POST': email_address = request.form['email'].strip() team = Users.query.filter_by(email=email_address).first() errors = get_errors() if config.can_send_mail() is False: return render_template( 'reset_password.html', errors=[ 'Email could not be sent due to server misconfiguration' ]) if not team: return render_template( 'reset_password.html', errors=[ 'If that account exists you will receive an email, please check your inbox' ]) email.forgot_password(email_address, team.name) return render_template( 'reset_password.html', errors=[ 'If that account exists you will receive an email, please check your inbox' ]) return render_template('reset_password.html')
async def test_login(self): with self.session.begin(): self.session.add( models.User( username='******', password_hash=bcrypt_sha256.encrypt('b').encode(), )) response = await self.fetch('/auth/login?username=a&password=b', method='POST', follow_redirects=False, raise_error=False, body='') self.assertEqual(response.code, 302, msg=response.body) self.assertIn('user', response.headers['Set-Cookie'])
def reset_password(data=None): logger = logging.getLogger('logins') if data is not None: try: s = TimedSerializer(app.config['SECRET_KEY']) name = s.loads(utils.base64decode(data, urldecode=True), max_age=1800) except BadTimeSignature: return render_template('reset_password.html', errors=[get_tip('LINK_EXPIRED')]) except (BadSignature, TypeError, base64.binascii.Error): return render_template('reset_password.html', errors=[get_tip('INVIDE_RESET_TOKEN')]) if request.method == "GET": return render_template('reset_password.html', mode='set') if request.method == "POST": team = Teams.query.filter_by(name=name).first_or_404() team.password = bcrypt_sha256.encrypt( request.form['password'].strip()) db.session.commit() logger.warn( get_tip('PASS_HAVE_RESET').format( date=time.strftime("%m/%d/%Y %X"), ip=utils.get_ip(), username=team.name.encode('utf-8'))) db.session.close() return redirect(url_for('auth.login')) if request.method == 'POST': email = request.form['email'].strip() team = Teams.query.filter_by(email=email).first() errors = [] if utils.can_send_mail() is False: return render_template('reset_password.html', errors=[get_tip('EMAIL_NOT_CONFIG')]) if not team: return render_template('reset_password.html', errors=[get_tip('FORGOT_PASS_NOTICE')]) utils.forgot_password(email, team.name) return render_template('reset_password.html', errors=[get_tip('FORGOT_PASS_NOTICE')]) return render_template('reset_password.html')
def reset_password(data=None): logger = logging.getLogger('logins') if data is not None: try: s = TimedSerializer(app.config['SECRET_KEY']) name = s.loads(utils.base64decode(data, urldecode=True), max_age=1800) except BadTimeSignature: return render_template('reset_password.html', errors=['您的密码重置链接已经过期']) except (BadSignature, TypeError, base64.binascii.Error): return render_template('reset_password.html', errors=['您的密码重置令牌已经失效']) if request.method == "GET": return render_template('reset_password.html', mode='set') if request.method == "POST": team = Teams.query.filter_by(name=name).first_or_404() team.password = bcrypt_sha256.encrypt( request.form['password'].strip()) db.session.commit() logger.warn( "[{date}] {ip} - successful password reset for {username}". format(date=time.strftime("%m/%d/%Y %X"), ip=utils.get_ip(), username=team.name.encode('utf-8'))) db.session.close() return redirect(url_for('auth.login')) if request.method == 'POST': email = request.form['email'].strip() team = Teams.query.filter_by(email=email).first() errors = [] if utils.can_send_mail() is False: return render_template('reset_password.html', errors=['邮件信息配置异常,无法发送邮件,请联系管理员']) if not team: return render_template('reset_password.html', errors=['如果邮箱有效,将会收到一封密码重置邮件,请注意查收']) utils.forgot_password(email, team.name) return render_template('reset_password.html', errors=['如果邮箱有效,将会收到一封密码重置邮件,请注意查收']) return render_template('reset_password.html')
def admin_team(teamid): user = Teams.query.filter_by(id=teamid).first() solves = Solves.query.filter_by(teamid=teamid).all() addrs = Tracking.query.filter_by(team=teamid).group_by(Tracking.ip).all() score = user.score() place = user.place() if request.method == 'GET': return render_template('admin/team.html', solves=solves, team=user, addrs=addrs, score=score, place=place) elif request.method == 'POST': admin_user = request.form.get('admin', "false") admin_user = 1 if admin_user == "true" else 0 if admin: user.admin = 1 db.session.commit() return jsonify({'data': ['success']}) name = request.form.get('name', None) password = request.form.get('password', None) email = request.form.get('email', None) website = request.form.get('website', None) affiliation = request.form.get('affiliation', None) country = request.form.get('country', None) errors = [] name_used = Teams.query.filter(Teams.name == name).first() if name_used and int(name_used.id) != int(teamid): errors.append('That name is taken') email_used = Teams.query.filter(Teams.email == email).first() if email_used and int(email_used.id) != int(teamid): errors.append('That email is taken') if errors: db.session.close() return jsonify({'data':errors}) else: user.name = name user.email = email if password: user.password = bcrypt_sha256.encrypt(password) user.website = website user.affiliation = affiliation user.country = country db.session.commit() db.session.close() return jsonify({'data':['success']})
def create_user(username, password, access='minion'): """ if username does not exist creates a new user with username password and access (default=minion) username is not encrypted password encryption is salt and hash with bcrypt_sha256 12 rounds iterative hash with individual salt. hash is truncated and stored with salt in single variable """ try: Users.get(Users.username == username) except DoesNotExist: pass_hashed = bcrypt_sha256.encrypt(password, rounds=12) new_user = Users.create(username=username, password=pass_hashed, access=access) return True else: print("user already exists") return False
def set_api_token(*, expiration=timedelta(days=60), token: str, auth_user_id: str) -> Update: """ Set a new API token for the given user. :param expiration: how long the token will be valid, 60 days by default. :param token: the token to set. Use generate_api_token() :param auth_user_id: the id of the user :return: The Update object. Execute this! """ hashed_token = bcrypt_sha256.encrypt(token) expiration_time = datetime.now() + expiration return update_record(auth_user_table, 'auth_user_id', auth_user_id, token=hashed_token, expires_on=expiration_time)
def api_key(): """" Request url for API key for Restful API""" if request.method == "POST": content = request.get_json(silent=True) user = User.query.filter_by(Client_id=content['Client_id']).first() if not user and app.config['NO_PASSWORD'] == True: ##Allow anyone to create their own account pass_hash = bcrypt_sha256.encrypt(content['Password'], rounds=12) user = User(Client_id=content['Client_id'], Password=pass_hash, api_key='') Sample_date = Client_View(client_id=content['Client_id'], case_name='sample case', priority='1', target_date='10/7/2016', product_area='Engineering', status='In Progress', description='something') db.session.add(user) db.session.commit() db.session.add(Sample_date) db.session.commit() """ If user is a vaild account, proceed with verifying \ their credentials and provide them the API key""" if user: if bcrypt_sha256.verify( content['Password'], user.Password) and user.Client_id == content['Client_id']: signer = TimestampSigner(SECRET_KEY) API_KEY = ''.join([ random.choice(string.ascii_letters + string.digits) for n in xrange(30) ]) user.api_key = signer.sign(API_KEY) user.current_login_ip = request.remote_addr db.session.commit() return make_response(jsonify({'API KEY': user.api_key}), 200) return make_response( jsonify({'Failure': 'Incorrect Client id OR Password'}), 400)
def __init__(self, name, email, password): self.name = name self.email = email self.password = bcrypt_sha256.encrypt(str(password))
def admin_team(teamid): user = Teams.query.filter_by(id=teamid).first_or_404() if request.method == 'GET': solves = Solves.query.filter_by(teamid=teamid).all() solve_ids = [s.chalid for s in solves] missing = Challenges.query.filter(not_(Challenges.id.in_(solve_ids))).all() last_seen = db.func.max(Tracking.date).label('last_seen') addrs = db.session.query(Tracking.ip, last_seen) \ .filter_by(team=teamid) \ .group_by(Tracking.ip) \ .order_by(last_seen.desc()).all() wrong_keys = WrongKeys.query.filter_by(teamid=teamid).order_by(WrongKeys.date.asc()).all() awards = Awards.query.filter_by(teamid=teamid).order_by(Awards.date.asc()).all() score = user.score(admin=True) place = user.place(admin=True) return render_template('admin/team.html', solves=solves, team=user, addrs=addrs, score=score, missing=missing, place=place, wrong_keys=wrong_keys, awards=awards) elif request.method == 'POST': name = request.form.get('name', None) password = request.form.get('password', None) email = request.form.get('email', None) website = request.form.get('website', None) affiliation = request.form.get('affiliation', None) country = request.form.get('country', None) admin_user = True if request.form.get('admin', None) == 'on' else False verified = True if request.form.get('verified', None) == 'on' else False hidden = True if request.form.get('hidden', None) == 'on' else False errors = [] # if email: # valid_email = utils.check_email_format(email) # if not valid_email: # errors.append("That email address is invalid") if email: valid_email = utils.check_id_format(email) if not valid_email: errors.append("That student id is invalid") name_used = Teams.query.filter(Teams.name == name).first() if name_used and int(name_used.id) != int(teamid): errors.append('That name is taken') if utils.check_email_format(name) is True: errors.append('Team name cannot be an email address') email_used = Teams.query.filter(Teams.email == email).first() if email_used and int(email_used.id) != int(teamid): errors.append('That student id is taken') if website and (website.startswith('http://') or website.startswith('https://')) is False: errors.append('Websites must start with http:// or https://') if errors: db.session.close() return jsonify({'data': errors}) else: user.name = name if email: user.email = email if password: user.password = bcrypt_sha256.encrypt(password) user.website = website user.affiliation = affiliation user.country = country user.admin = admin_user user.verified = verified user.banned = hidden db.session.commit() db.session.close() return jsonify({'data': ['success']})
def setup_page(): if not is_setup(): if not session.get("nonce"): session["nonce"] = sha512(os.urandom(10)) if request.method == "POST": # print request.form db = db_conn() errors = [ ] config = [ ] verification = request.form.get("verification") actual_verification = db.config.find_one({ "key": "setup_verification" })["value"] if not(verification is not None and verification == actual_verification): errors.append("Verification is not correct.") if len(errors) == 0: # db.config.remove({ "key": "setup_verification" }) if request.form.get("ctf_name") is None: errors.append("Please enter a name for your CTF.") else: ctf_name = request.form.get("ctf_name") if not(len(ctf_name) >= 4 and len(ctf_name) <= 20): errors.append("CTF Name must be between 4 and 20 characters long.") config.append({ "key": "ctf_name", "value": ctf_name }) if request.form.get("ctf_start") is None or request.form.get("ctf_end") is None: errors.append("Please fill out the start and end times.") else: try: ctf_start_time = time.strptime(request.form.get("ctf_start"), "%m/%d/%Y %I:%M %p") ctf_start = time.mktime(ctf_start_time) ctf_end_time = time.strptime(request.form.get("ctf_end"), "%m/%d/%Y %I:%M %p") ctf_end = time.mktime(ctf_end_time) config.append({ "key": "ctf_start", "value": ctf_start }) config.append({ "key": "ctf_end", "value": ctf_end }) except: errors.append("Please use the correct format.") if request.form.get("username") is None or request.form.get("password") is None or request.form.get("email") is None: errors.append("Please fill out the admin details.") else: email = request.form.get("email").lower() if not re.match("[^@]+@[^@]+\.[^@]+", email): errors.append("Email is not valid.") if db.users.count({ "email": email }) > 0: errors.append("That email is taken.") config.append({ "key": "admin_email", "value": email }) username = request.form.get("username") if not(len(username) >= 4 and len(username) <= 20): errors.append("Username must be between 4 and 20 characters long.") if db.users.count({ "username_lower": username.lower() }) > 0: errors.append("That username is taken.") config.append({ "key": "admin_username", "value": username.lower() }) password = request.form.get("password") if not(len(password) >= 6 and len(password) <= 60): errors.append("Password must be between 6 and 60 characters long.") password = bcrypt_sha256.encrypt(password) if len(errors) != 0: admin = { "uid": token(), "email": email, "username": username, "username_lower": username.lower(), "password": password, } db.users.insert(admin) if len(errors) != 0: return render_template("setup.html", nonce=session.get("nonce"), errors=errors, data=request.form) else: for obj in config: db.config.update({ "key": obj["key"] }, obj, upsert=True) db.config.update({ "key": "setup_complete" }, { "key": "setup_complete", "value": True }, upsert=True) return redirect("/") else: db = db_conn() if db.config.count({ "key": "setup_verification" }) == 0: db.config.insert({ "key": "setup_verification", "value": token() }) return render_template("setup.html", nonce=session.get("nonce")) else: return redirect("/")
def __init__(self, name, email, schoolCode, password): self.name = name self.email = email self.schoolCode = schoolCode self.password = bcrypt_sha256.encrypt(str(password))
def admin_team(teamid): teamid = int(teamid) user = Teams.query.filter_by(id=teamid).first_or_404() if request.method == 'GET': solves_with_value = [ (solve, value) for solve, value in get_solves_and_value(is_admin=True) if isinstance(solve, Solves) and solve.teamid == teamid ] solves_with_value.sort(key=lambda solve_value: solve_value[0].date) solve_ids = [solve.chalid for solve, value in solves_with_value] missing = Challenges.query.filter(not_( Challenges.id.in_(solve_ids))).all() last_seen = db.func.max(Tracking.date).label('last_seen') addrs = db.session.query(Tracking.ip, last_seen) \ .filter_by(team=teamid) \ .group_by(Tracking.ip) \ .order_by(last_seen.desc()).all() wrong_keys = WrongKeys.query.filter_by(teamid=teamid).order_by( WrongKeys.date.asc()).all() awards = Awards.query.filter_by(teamid=teamid).order_by( Awards.date.asc()).all() score = user.score() place = user.place() return render_template('admin/team.html', solves=solves_with_value, team=user, addrs=addrs, score=score, missing=missing, place=place, wrong_keys=wrong_keys, awards=awards) elif request.method == 'POST': admin_user = request.form.get('admin', None) if admin_user: admin_user = True if admin_user == 'true' else False user.admin = admin_user # Set user.banned to hide admins from scoreboard user.banned = admin_user db.session.commit() db.session.close() return jsonify({'data': ['success']}) verified = request.form.get('verified', None) if verified: verified = True if verified == 'true' else False user.verified = verified db.session.commit() db.session.close() return jsonify({'data': ['success']}) name = request.form.get('name', None) password = request.form.get('password', None) email = request.form.get('email', None) website = request.form.get('website', None) affiliation = request.form.get('affiliation', None) country = request.form.get('country', None) errors = [] name_used = Teams.query.filter(Teams.name == name).first() if name_used and int(name_used.id) != int(teamid): errors.append('That name is taken') email_used = Teams.query.filter(Teams.email == email).first() if email_used and int(email_used.id) != int(teamid): errors.append('That email is taken') if errors: db.session.close() return jsonify({'data': errors}) else: user.name = name user.email = email if password: user.password = bcrypt_sha256.encrypt(password) user.website = website user.affiliation = affiliation user.country = country db.session.commit() db.session.close() return jsonify({'data': ['success']})
def profile(): if utils.authed(): if request.method == "POST": errors = [] name = request.form.get('name').strip() email = request.form.get('email').strip() website = request.form.get('website').strip() affiliation = request.form.get('affiliation').strip() country = request.form.get('country').strip() user = Teams.query.filter_by(id=session['id']).first() if not utils.get_config('prevent_name_change'): names = Teams.query.filter_by(name=name).first() name_len = len(request.form['name']) == 0 emails = Teams.query.filter_by(email=email).first() valid_email = utils.check_email_format(email) if utils.check_email_format(name) is True: errors.append('Team name cannot be an email address') if ('password' in request.form.keys() and not len(request.form['password']) == 0) and \ (not bcrypt_sha256.verify(request.form.get('confirm').strip(), user.password)): errors.append("Your old password doesn't match what we have.") if not valid_email: errors.append("That email doesn't look right") if not utils.get_config( 'prevent_name_change' ) and names and name != session['username']: errors.append('That team name is already taken') if emails and emails.id != session['id']: errors.append('That email has already been used') if not utils.get_config('prevent_name_change') and name_len: errors.append('Pick a longer team name') if website.strip() and not utils.validate_url(website): errors.append("That doesn't look like a valid URL") if len(errors) > 0: return render_template('profile.html', name=name, email=email, website=website, affiliation=affiliation, country=country, errors=errors) else: team = Teams.query.filter_by(id=session['id']).first() if team.name != name: if not utils.get_config('prevent_name_change'): team.name = name session['username'] = team.name if team.email != email.lower(): team.email = email.lower() if utils.get_config('verify_emails'): team.verified = False if 'password' in request.form.keys() and not len( request.form['password']) == 0: team.password = bcrypt_sha256.encrypt( request.form.get('password')) team.website = website team.affiliation = affiliation team.country = country db.session.commit() db.session.close() return redirect(url_for('views.profile')) else: user = Teams.query.filter_by(id=session['id']).first() name = user.name email = user.email website = user.website affiliation = user.affiliation country = user.country prevent_name_change = utils.get_config('prevent_name_change') confirm_email = utils.get_config( 'verify_emails') and not user.verified return render_template('profile.html', name=name, email=email, website=website, affiliation=affiliation, country=country, prevent_name_change=prevent_name_change, confirm_email=confirm_email) else: return redirect(url_for('auth.login'))
def gen_pwhash(password): return bcrypt_sha256.encrypt(password.encode('utf-8'))
import sqlite3 import string import random import os from passlib.hash import bcrypt_sha256 def id_generator(size=24, chars=string.ascii_uppercase + string.digits + string.ascii_lowercase): return ''.join(random.choice(chars) for _ in range(size)) dbfile = os.path.dirname(os.path.realpath(__file__)) + '/CTFd/ctfd.db' conn = sqlite3.connect(dbfile) c = conn.cursor() for x in range (2,20): password = id_generator() hash = bcrypt_sha256.encrypt(password) row = (hash, x) c.execute('UPDATE teams SET password=? WHERE id=?', row) conn.commit() row = (x) c.execute('SELECT name FROM teams WHERE id=?', (x,)) data = c.fetchone() if data is not None: print 'Name:'+ ''.join(data) + ' Pass:' + password conn.close()
def setpasswd (username, password): updateuser(userdb[username], 'secret', bcrypt.encrypt(password, rounds=12))
def _finalize(cls, new_value, entity=None): return bcrypt_sha256.encrypt(new_value)
def profile(): if authed(): if request.method == "POST": errors = [] name = request.form.get("name") email = request.form.get("email") website = request.form.get("website") affiliation = request.form.get("affiliation") country = request.form.get("country") user = Teams.query.filter_by(id=session["id"]).first() if not get_config("prevent_name_change"): names = Teams.query.filter_by(name=name).first() name_len = len(request.form["name"]) == 0 emails = Teams.query.filter_by(email=email).first() valid_email = re.match("[^@]+@[^@]+\.[^@]+", email) if ("password" in request.form.keys() and not len(request.form["password"]) == 0) and ( not bcrypt_sha256.verify(request.form.get("confirm").strip(), user.password) ): errors.append("Your old password doesn't match what we have.") if not valid_email: errors.append("That email doesn't look right") if not get_config("prevent_name_change") and names and name != session["username"]: errors.append("That team name is already taken") if emails and emails.id != session["id"]: errors.append("That email has already been used") if not get_config("prevent_name_change") and name_len: errors.append("Pick a longer team name") if website.strip() and not validate_url(website): errors.append("That doesn't look like a valid URL") if len(errors) > 0: return render_template( "profile.html", name=name, email=email, website=website, affiliation=affiliation, country=country, errors=errors, ) else: team = Teams.query.filter_by(id=session["id"]).first() if not get_config("prevent_name_change"): team.name = name team.email = email session["username"] = team.name if "password" in request.form.keys() and not len(request.form["password"]) == 0: team.password = bcrypt_sha256.encrypt(request.form.get("password")) team.website = website team.affiliation = affiliation team.country = country db.session.commit() db.session.close() return redirect("/profile") else: user = Teams.query.filter_by(id=session["id"]).first() name = user.name email = user.email website = user.website affiliation = user.affiliation country = user.country prevent_name_change = get_config("prevent_name_change") return render_template( "profile.html", name=name, email=email, website=website, affiliation=affiliation, country=country, prevent_name_change=prevent_name_change, ) else: return redirect("/login")
def hash_password(password): return bcrypt_sha256.encrypt(password, rounds=10).decode()
def __init__(self, user, password): self.user = user self.password = bcrypt_sha256.encrypt(password)
def __init__(self, name, email, password): self.name = name self.email = email self.password = bcrypt_sha256.encrypt(password)
def profile(): if authed(): if request.method == "POST": errors = [] name = request.form.get('name') email = request.form.get('email') schoolCode = request.form.get('schoolCode') website = request.form.get('website') affiliation = request.form.get('affiliation') country = request.form.get('country') user = Teams.query.filter_by(id=session['id']).first() if not get_config('prevent_name_change'): names = Teams.query.filter_by(name=name).first() name_len = len(request.form['name']) == 0 emails = Teams.query.filter_by(email=email).first() valid_email = re.match("[^@]+@[^@]+\.[^@]+", email) if ('password' in request.form.keys() and not len(request.form['password']) == 0) and \ (not bcrypt_sha256.verify(request.form.get('confirm').strip(), user.password)): errors.append("Your old password doesn't match what we have.") if not valid_email: errors.append("That email doesn't look right") if not get_config('prevent_name_change') and names and name!=session['username']: errors.append('That team name is already taken') if emails and emails.id != session['id']: errors.append('That email has already been used') if not get_config('prevent_name_change') and name_len: errors.append('Pick a longer team name') if website.strip() and not validate_url(website): errors.append("That doesn't look like a valid URL") if len(errors) > 0: return render_template('profile.html', name=name, email=email, schoolCode=schoolCode, website=website, affiliation=affiliation, country=country, errors=errors) else: team = Teams.query.filter_by(id=session['id']).first() if not get_config('prevent_name_change'): team.name = name if team.email != email.lower(): team.email = email.lower() if get_config('verify_emails'): team.verified = False session['username'] = team.name if 'password' in request.form.keys() and not len(request.form['password']) == 0: team.password = bcrypt_sha256.encrypt(request.form.get('password')) team.schoolCode = schoolCode team.website = website team.affiliation = affiliation team.country = country db.session.commit() db.session.close() return redirect(url_for('views.profile')) else: user = Teams.query.filter_by(id=session['id']).first() name = user.name email = user.email schoolCode = user.schoolCode website = user.website affiliation = user.affiliation country = user.country prevent_name_change = get_config('prevent_name_change') confirm_email = get_config('verify_emails') and not user.verified return render_template('profile.html', name=name, email=email, schoolCode=schoolCode, website=website, affiliation=affiliation, country=country, prevent_name_change=prevent_name_change, confirm_email=confirm_email) else: return redirect(url_for('auth.login'))