def auth_admin(self): """Authenticate administrator trying to login.""" try: conn = Connect(host=HOST, user=USER, password=PASSWORD, database=DATABASE) except ConnectionError as e: print(e) return False cur = conn.cursor() query = "SELECT `password` FROM `administrator` WHERE `user_name` = '{}'".format(self.user_name) try: cur.execute(query) except errors.ProgrammingError as e: print(e) return False response = cur.fetchall() conn.close() bcrypt = Bcrypt() try: return bcrypt.check_password_hash(response[0][0], self.password) except IndexError: return False
def create_admin(self): if not self.check_duplicate(): try: conn = Connect(host=HOST, user=USER, password=PASSWORD, database=DATABASE) except ConnectionError as e: print(e) return False cur = conn.cursor() bcrypt = Bcrypt() query = ("INSERT INTO " "`administrator`(name, user_name, password, street, city, state, zipcode, phone, email, join_date)" "VALUES ('{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}')" "".format(self.name, self.user_name, bcrypt.generate_password_hash(self.password), self.address['street'], self.address['city'], self.address['state'], self.address['zipcode'], self.phone, self.email, self.join_date)) try: cur.execute(query) except errors.ProgrammingError as e: print(e) return False conn.commit() conn.close() return True return False
def is_login(sk): """This method is used to verify if at least one administrator has been setup.""" try: conn = Connect(host=HOST, user=USER, password=PASSWORD, database=DATABASE) except ConnectionError as e: print(e) return False cur = conn.cursor() query = "SELECT * FROM `administrator`" try: cur.execute(query) except errors.ProgrammingError as e: print(e) return False conn.close() response = cur.fetchall() if response: b = Bcrypt() try: return b.check_password_hash(request.cookies['admin_session'], sk) except KeyError as e: return False else: return True
def save(self, force_insert=False, validate=True, clean=True, write_concern=None, cascade=None, cascade_kwargs=None, _refs=None, **kwargs): crypt = Bcrypt() hash = crypt.generate_password_hash(self.passHash) self.passHash = hash super(User, self).save()
def login(): if request.method == "GET": next_redirect = request.args.get("next", False) return render_template("public/login.html", next=next_redirect) else: errs = [] password = request.form.get("password", "") email = request.form.get("email", "") next = request.form.get("next", "") try: bc = Bcrypt(None) conn = db.get_db() sql_query = "SELECT * FROM users WHERE email = %s;" sql_data = (escape(email), ) cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor) cur.execute( sql_query, sql_data ) user = cur.fetchone() cur.close() if user == None: errs.append("No User Found.") else: if bc.check_password_hash(user["password"], password): # add user to the session tools.setCookie( email, user["username"], user["userid"] ) # return the errors and redirect path redirect_url = "/welcome/" if next: redirect_url = next return redirect("/welcome/") else: print "bad pass" errs.append("Incorrect Password.") except Exception, e: print e errs.append("Unable to sign in at this time.") return render_template("public/login.html", next=next, errors=errs, email=email)
def check_old_password(pwdhash, password): """Check the old password hash from :func:`password_hash`. .. versionadded:: 1.1.0 :param str pwdhash: Hash from :func:`password_hash` to check :param str password: Password in plaintext :return: password match :rtype: bool """ from flask.ext.bcrypt import Bcrypt app.config['BCRYPT_LOG_ROUNDS'] = 12 bcrypt = Bcrypt(app) return bcrypt.check_password_hash(pwdhash, password)
def signup(): if request.method == "POST": email = request.form.get("email", "") username = request.form.get("username", "") password = request.form.get("password", "") try: bc = Bcrypt(None) hashed_pw = bc.generate_password_hash( password ) # Open a cursor to perform database operations conn = db.get_db() cur = conn.cursor() sql_query = "SELECT * FROM users WHERE email = %s;" sql_data = ( email, ) cur.execute( sql_query, sql_data ) old_email = cur.fetchone() if old_email: errs.append("Email already exists.") else: sql_query = "INSERT INTO users (email, password, username) VALUES (%s, %s, %s) RETURNING userid;" sql_data = ( email, hashed_pw, username ) cur.execute( sql_query, sql_data ) userid = cur.fetchone()[0] # sql_query = "INSERT INTO email_confirmation (userid, token) VALUES (%s, %s);" # sql_data = (userid, token) # cur.execute( sql_query, sql_data ) conn.commit() cur.close() tools.setCookie( email, username, userid ) except db.psycopg2.DatabaseError, e: # if I have a connection print e if conn: conn.rollback() return redirect("/welcome/")
def main(): """Main entry point for script.""" with app.app_context(): bcrypt = Bcrypt(app) if User.query.all(): print('A user already exists! Create another? (y/n):'), create = input() if create == 'n': return print('Enter email address: '), email = input() password = getpass() assert password == getpass('Password (again):') user = User(email=email, password=bcrypt.generate_password_hash(password)) db_session.add(user) db_session.commit() print('User added.')
def login(self): print '***** login' email = request.form['email'] password = request.form['password'] results = self.models['User'].get_user_by_email(email) if results == []: flash('Bad password or email', 'error') return redirect('/') app = Flask(__name__) bcrypt = Bcrypt(app) if bcrypt.check_password_hash(results[0]['pw_hash'], password): session['id'] = results[0]['id'] session['fname'] = results[0]['fname'] session['lname'] = results[0]['lname'] session['email'] = results[0]['email'] print '*** session id: {}'.format(session['id']) return redirect('/articles') else: flash('Bad password or email', 'error') return redirect('/')
def init_app(self, app, config): print 'Attaching LoginManager to app.' self.__login_manager.init_app(app) self.__login_manager.anonymous_user = Auth.Anonymous self.config = config def load_user(user_id): if user_id == '': return None Users = Database['Users'] try: return Users.User.find_one({'_id': ObjectId(user_id)}) except: return None def unauthorized(): return jsonify(error='Unauthorized'), HTTP_401_UNAUTHORIZED self.__login_manager.user_loader(load_user) self.__login_manager.unauthorized_handler(unauthorized) self.__bcrypt = Bcrypt(app)
def create_app(): app = flask.Flask(__name__) app.debug = True # Configurations set above in the ConfigClass ... app.config.from_object(__name__ + '.ConfigClass') #app.logger.debug(ssl.PROTOCOL_TLSv1) # Initialize Flask extensions db = SQLAlchemy(app) # Initialize Flask-SQLAlchemy mail = Mail(app) # Initialize Flask-Mail ... bcrypt = Bcrypt(app) # Inifialize Bcrypt ... # Define the User data model. Make sure to add flask.ext.user UserMixin !!! class User(db.Model, UserMixin): id = db.Column(db.Integer, primary_key=True) password = db.Column(db.String(255), nullable=False, server_default='') #reset_password_token = db.Column(db.String(100), nullable=False, server_default='') authenticate = db.Column(db.Boolean) email = db.Column(db.String(255), nullable=False, unique=True) confirmed_at = db.Column(db.DateTime()) is_enabled = db.Column(db.Boolean(), nullable=False, default=False) active = db.Column('is_active', db.Boolean(), nullable=False, server_default='0') registered_on = db.Column('registered_on', db.DateTime) chrome_hash = db.Column(db.String(500)) secure_token = db.Column(db.String(500)) def hash_password(self, password): self.password = bcrypt.generate_password_hash(password) def verify_password(self, password): return bcrypt.check_password_hash(self.password, password) def activate(self): self.authenticate = True def is_authenticated(self): return True def is_active(self): return True def is_anonymous(self): return False def get_id(self): return unicode(self.id) def set_chrome_hash(self): self.chrome_hash = str(hashlib.sha224(self.email).hexdigest()) def set_secure_token(self): secure_token = make_secure_token(self.email) class Path(db.Model): __tablename__ = 'paths' id = db.Column(db.Integer, primary_key=True) path = db.Column(db.String(50), nullable=False, unique=True) url = db.Column(db.String(250), nullable=False) creator_id = db.Column(db.Integer, nullable=True) clicks = db.Column(db.Integer, default=0) note = db.Column(db.String(300), default="No note.") timestamp = db.Column(db.DateTime) ### INITIALIZE THE DB, USER MODEL, LOGIN MANAGER, ETC. ... ### db.create_all() # Create all database tables if they don't exist ... db_adapter = SQLAlchemyAdapter(db, User) # Register the User model user_manager = UserManager(db_adapter, app) # Initialize Flask-User login_manager = LoginManager() # Initialize the Login manager? ... login_manager.init_app( app) # this needs a secret key, set above in the Config class @login_manager.user_loader def load_user(id): return User.query.get(int(id)) ###################################################################### # # # CONFIRMATION EMAILS # # # ###################################################################### def get_serializer(secret_key=None): app.logger.debug("in get_serializer") if secret_key is None: secret_key = app.secret_key return URLSafeSerializer(secret_key) @app.route('/users/activate/<payload>') def activate_user(payload): app.logger.debug("in activate_user") s = get_serializer() try: user_id = s.loads(payload) except BadSignature: abort(404) user = User.query.get_or_404(user_id) user.authenticate = True db.session.commit() flash('User activated') return flask.redirect(home_url) def get_activation_link(user): app.logger.debug("in get_activation_link") s = get_serializer() payload = s.dumps(user.id) return url_for('activate_user', payload=payload) def send_confirmation_email(user): link = get_activation_link(user) msg = Message("Hello", sender="*****@*****.**") msg.add_recipient(user.email) msg.body = "people.ischool.berkeley.edu/~brian.carlo/server" + link mail.send(msg) ###################################################################### # # # REGISTRATION AND LOGIN # # # ###################################################################### @app.route('/login.html', methods=["GET", "POST"]) def login(): if request.method == 'GET': return render_template('login.html') email = request.form['email'] password = request.form['password'] registered_user = User.query.filter_by(email=email).first() if registered_user.verify_password(password): login_user(registered_user) flash('Logged in successfully') return flask.redirect(dashboard_url) else: flash('Username or Password is invalid', 'error') return render_template('login.html') @app.route('/register.html', methods=['GET', 'POST']) def register(): if request.method == 'GET': return render_template('register.html') try: user = User(email=request.form['email']) user.hash_password(request.form['password']) db.session.add(user) db.session.commit() registered_user = User.query.filter_by(email=user.email).first() send_confirmation_email(registered_user) registered_user.set_chrome_hash() app.logger.debug(registered_user.chrome_hash) db.session.commit() response = make_response(flask.redirect(home_url)) response.set_cookie('chrome_id', value=registered_user.chrome_hash, max_age=2592000) return response except: flash( "That e-mail address is already Nerping for real. Maybe Nerp a different e-mail?" ) return render_template('register.html') ###################################################################### # # # POSTING PATHS! # # # ###################################################################### @app.before_request def validate(): # runs before any app.route() """ Helper validates URLs and handles errors for CHROME_PUT(), SHORTS_PUT(). """ if request.path == '/shorts': # if the server request is to '/shorts' ... shortpath = str( request.form.get('shortpath')).strip() # grab the shortpath if shortpath == "": pass # if there's no path, no worries else: if Path.query.filter_by(path=shortpath).first(): app.logger.debug("made it here") flash("already taken!") inputURL = str( request.form.get('url')).lower().strip() # grab the URL if inputURL == None or inputURL == "": # if it's not there ... abort(412) # throw the 412 def insert_path_for_user_or_not(path, inputURL): """ HELPER FOR CHROME_PUT(), SHORTS_PUT() """ try: new_path = Path(path=path, url=inputURL, creator_id=current_user.id, timestamp=datetime.utcnow()) app.logger.debug("UID!") except: app.logger.debug("NOID!") new_path = Path(path=path, url=inputURL, creator_id=None, timestamp=datetime.utcnow()) db.session.add(new_path) db.session.commit() def make_random_path(): """ HELPER FOR CHROME_PUT(), SHORTS_PUT() """ myPath = "" for i in range(7): myPath = myPath + chr(random.choice(possible)) return myPath def format_url(inputURL): """ HELPER FOR CHROME_PUT(), SHORTS_PUT() """ parsed = urlparse(inputURL) if parsed.scheme == "": inputURL = "http://" + inputURL h = httplib2.Http() try: response = h.request(inputURL, 'HEAD') inputURL = response[0]['content-location'] return inputURL except: return False def insert_note(path): added_path = Path.query.filter_by(path=path).first() added_path.note = str(request.form.get('note', '')) @app.route('/chrome', methods=['PUT', 'POST']) def chrome_put(): if 'chrome_id' not in request.cookies: user_id = 0 else: chrome_hash = request.cookies.get('chrome_id') user = User.query.filter_by(chrome_hash=chrome_hash).first() user_id = user.id inputURL = str(request.form.get('url', '')).lower() inputURL = format_url(inputURL) if not inputURL: response = make_response("Broken URL. Try another") return response shortpath = str(request.form.get('shortpath', '')) if not shortpath: myPath = make_random_path() while Path.query.filter_by(path=myPath).first(): myPath = make_random_path() insert_path_for_user_or_not(myPath, inputURL) insert_note(myPath) else: insert_path_for_user_or_not(shortpath, inputURL) insert_note(shortpath) return flask.redirect( 'http://people.ischool.berkeley.edu/~brian.carlo/server/chrome.html' ) @app.route('/shorts', methods=['PUT', 'POST']) def shorts_put(): try: inputURL = str(request.form.get('url', '')).lower() inputURL = format_url(inputURL) if not inputURL: response = make_response("Broken URL. Try another") return response shortpath = str(request.form.get('shortpath', '')) app.logger.debug(inputURL + "," + shortpath) if not shortpath: myPath = make_random_path() while Path.query.filter_by(path=myPath).first(): myPath = make_random_path() insert_path_for_user_or_not(myPath, inputURL) path = myPath else: insert_path_for_user_or_not(shortpath, inputURL) path = shortpath try: if current_user.id: return flask.redirect(dashboard_url) except: flash("nerp.me/" + path) return render_template('promo.html') except: abort(405) @app.route('/delete', methods=['POST', 'PUT']) @login_required def delete_nerp(): nerp_id = str(request.form.get('nerp_id', '')) # REMEMBER TO CHANGE "NERP-ID" death_row_nerp = Path.query.filter_by(id=nerp_id).first() db.session.delete(death_row_nerp) db.session.commit() ###################################################################### # # # GET METHODS! # # # ###################################################################### @app.route('/shorts/<shortpath>', methods=['GET']) def shorts_shortpath(shortpath): try: path = Path.query.filter_by(path=shortpath).first() url = path.url path.clicks = path.clicks + 1 db.session.commit() return flask.redirect(url) except: abort(404) @app.route('/chrome.html', methods=['GET']) def chrome_dash(): return render_template('chrome.html') @app.route('/home.html', methods=['GET']) def root(): return render_template('promo.html') @app.route('/dashboard.html', methods=['GET']) @login_required def dashboard(): items = Path.query.filter_by(creator_id=current_user.id).order_by( Path.timestamp.desc()).all() top_nerps = Path.query.order_by(Path.clicks.desc()).limit(10) return render_template('dashboard.html', items=items, top_nerps=top_nerps) @app.route('/logout', methods=['GET']) def logout(): logout_user() return flask.redirect(home_url) ###################################################################### # # # ERROR HANDLERS! # # # ###################################################################### @app.errorhandler(412) def precondition_failed(e): flash("put in a url, dumbass") try: if current_user.is_authenticated: return flask.redirect(dashboard_url) except: return render_template('promo.html') @app.errorhandler(404) def page_not_found(e): return render_template('404.html'), 404 @app.errorhandler(405) def method_not_allowed(e): return render_template('promo.html'), 405 @app.errorhandler(409) def conflict(e): return render_template( 'final_temp_3.html', code=409, message="Short path already exists. Please choose a different path." ), 409 return app
from flask import Flask from flask.ext.bcrypt import Bcrypt app = Flask(__name__) bcrypt = Bcrypt(app) # to generate bcrypt hash. pw_hash = bcrypt.generate_password_hash('idfumg') # to compare with an existing hash. bcrypt.check_password_hash(pw_hash, 'idfumg')
from datetime import datetime from inspect import stack from flask import Flask, render_template, request, redirect, url_for, flash, make_response from flask.ext.bcrypt import Bcrypt from flask.ext.mail import Mail, Message from mysql.connector import errors from models import Item, Costumer, Business, Invoice, Employee, Admin, Security from tools import prepare_items app = Flask(__name__) b = Bcrypt() SK = 'F*CM)@_!($":.@!#$E++)_-_;A"S;' SK_hash = b.generate_password_hash(SK) app.secret_key = SK sec = Security() app.config["MAIL_SERVER"] = "smtp.gmail.com" app.config["MAIL_PORT"] = 465 app.config["MAIL_USE_SSL"] = True app.config["MAIL_USERNAME"] = '******' app.config["MAIL_PASSWORD"] = '******' mail = Mail() mail.init_app(app) @app.route('/')
from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.bcrypt import Bcrypt from momentjs import momentjs from rendering_options import options app = Flask(__name__) app.config.from_object('config') app.jinja_env.globals['momentjs'] = momentjs #Allow Jinja templates to use momentjs for key, value in options.iteritems(): app.jinja_env.globals[key] = value # Tell Jinja to strip whitespace app.jinja_env.trim_blocks = True app.jinja_env.lstrip_blocks = True db = SQLAlchemy(app) #Generate an encrypter bcrypt = Bcrypt(app) ''' bcrypt has two essential functions: pw_hash = bcrypt.generate_password_hash('some_string') bcrypt.check_password_hash(pw_hash, 'some_string) returns True ''' from app import views, models
from flask import Flask from flask.ext.mongoengine import MongoEngine from flask.ext.bcrypt import Bcrypt # Index page index = Flask(__name__) # Add mongoDB stuff index.config['MONGODB_SETTINGS'] = {'DB': 'index'} index.config['SECRET_KEY'] = 'root' index_db = MongoEngine(index) # Encryption index_bcrypt = Bcrypt(index) # Use the blueprints def register_blueprints(index): # Put the blueprint import here to prevent circular imports from index.views import index_bp index.register_blueprint(index_bp) # Call the newly defined function to actually use the blueprints register_blueprints(index) if __name__ == '__main__': index.run()
def verify_password(self, password): bcrypt = Bcrypt() return bcrypt.check_password_hash(self.password, password)
def set_password(self, clear): bcrypt = Bcrypt(current_app) self.password = bcrypt.generate_password_hash(clear.encode('utf-8'))
def createApp(): """Set up the application.""" try : # Create application app = Flask(__name__, instance_path=CONFIG_PATH) local = CONFIG_BROKER['local'] app.config.from_object(__name__) app.config['LOCAL'] = local app.config['REST_TRACE'] = CONFIG_SERVICES['rest_trace'] app.config['SYSTEM_EMAIL'] = CONFIG_BROKER['reply_to_email'] # Future: Override config w/ environment variable, if set app.config.from_envvar('BROKER_SETTINGS', silent=True) # Set parameters broker_file_path = CONFIG_BROKER['broker_files'] AccountHandler.FRONT_END = CONFIG_BROKER['full_url'] sesEmail.SIGNING_KEY = CONFIG_BROKER['email_token_key'] sesEmail.isLocal = local if sesEmail.isLocal: sesEmail.emailLog = os.path.join(broker_file_path, 'email.log') # If local, make the email directory if needed if local and not os.path.exists(broker_file_path): os.makedirs(broker_file_path) # When runlocal is true, assume Dynamo is on the same server # (should be false for prod) JsonResponse.debugMode = app.config['REST_TRACE'] if CONFIG_SERVICES['cross_origin_url'] == "*": cors = CORS(app, supports_credentials=True, allow_headers = "*", expose_headers = "X-Session-Id") else: cors = CORS(app, supports_credentials=True, origins=CONFIG_SERVICES['cross_origin_url'], allow_headers = "*", expose_headers = "X-Session-Id") # Enable AWS Sessions app.session_interface = DynamoInterface() # Set up bcrypt bcrypt = Bcrypt(app) # Root will point to index.html @app.route("/", methods=["GET"]) def root(): return "Broker is running" if local: localFiles = os.path.join(broker_file_path, "<path:filename>") # Only define this route when running locally @app.route(localFiles) def sendFile(filename): if(config["local"]) : return send_from_directory(broker_file_path, filename) else: # For non-local installs, set Dynamo Region SessionTable.DYNAMO_REGION = CONFIG_BROKER['aws_region'] # Add routes for modules here add_login_routes(app, bcrypt) add_file_routes(app, CONFIG_BROKER['aws_create_temp_credentials'], local, broker_file_path, bcrypt) add_user_routes(app, app.config['SYSTEM_EMAIL'], bcrypt) add_domain_routes(app, local, bcrypt) SessionTable.LOCAL_PORT = CONFIG_DB['dynamo_port'] SessionTable.setup(app, local) if local: checkDynamo() return app except Exception as e: exc_type, exc_obj, exc_tb = sys.exc_info() trace = traceback.extract_tb(exc_tb, 10) CloudLogger.logError('Broker App Level Error: ', e, trace) del exc_tb raise
def hash_passwords(): from flask.ext.bcrypt import Bcrypt # CONFIG num_hashing_rounds = 4 # (higher means slower but more secure) print_frequency = 200 num_threads = 4 try: conn = database_connect() cursor = conn.cursor() print( 'Password hashing will now commence. This process only needs to run once.' ) #get every password cursor.execute("""SELECT pass_word, member_id FROM member WHERE pass_word IS NOT NULL""") valid_user_passwords = cursor.fetchall() #change columns cursor.execute("""ALTER TABLE member DROP pass_word""") cursor.execute( """ALTER TABLE member ADD pass_word VARCHAR(255) DEFAULT NULL""") #multithreaded hash creation print( 'creating password hashes expect this to take up to a minute (only needs to run once)' ) bc = Bcrypt(None) from multiprocessing.dummy import Pool as ThreadPool pool = ThreadPool(num_threads) password_arguments = [[bc, num_hashing_rounds, member[0], member[1]] for member in valid_user_passwords] password_changes = pool.map(create_individual_hash, password_arguments) cursor.execute(""" CREATE OR REPLACE FUNCTION insert_hashed(hashed_pwd VARCHAR(255), mem_id CHAR(10)) RETURNS void AS $$ BEGIN UPDATE member SET pass_word = hashed_pwd WHERE member_id=mem_id; END; $$ LANGUAGE plpgsql; """) print('prepared statement created') print( 'inserting hashed passwords to database (expect this to also take a while)' ) sql_statement = """SELECT insert_hashed(%s,%s)""" #insert changed passwords cursor.executemany(sql_statement, password_changes) print('Hashed passwords have been inserted into the database.') conn.commit() print('changes have been commited') print( 'The alter table statements are executed from within the python code (to ensure that no unhashed passwords remain after hashing is complete).' ) print( 'To verify that the hashed passwords are stored in the database you can just look in the member table.' ) finally: cursor.close() conn.close()
class Auth: GHOST = 0 USER = 1 ADMIN = 2 SUPER_ADMIN = 3 class Anonymous(AnonymousUserMixin): def __init__(self): self._id = None def get_id(self): return unicode('') def __init__(self): self.__login_manager = LoginManager() self.config = {} def init_app(self, app, config): print 'Attaching LoginManager to app.' self.__login_manager.init_app(app) self.__login_manager.anonymous_user = Auth.Anonymous self.config = config def load_user(user_id): if user_id == '': return None Users = Database['Users'] try: return Users.User.find_one({'_id': ObjectId(user_id)}) except: return None def unauthorized(): return jsonify(error='Unauthorized'), HTTP_401_UNAUTHORIZED self.__login_manager.user_loader(load_user) self.__login_manager.unauthorized_handler(unauthorized) self.__bcrypt = Bcrypt(app) def login_manager(self): return self.__login_manager def require(self, user_level): def login_required(f): @wraps(f) def decorated_function(*args, **kwargs): if current_user.is_authenticated() and current_user.get_access_level() >= user_level: return f(*args, **kwargs) return self.__login_manager.unauthorized() return decorated_function return login_required def login(self, user_object, password): if user_object is not None: if self.__bcrypt.check_password_hash(user_object['password'], password): if not login_user(user_object): return resource_strings["USER_NOT_ACTIVATED"] else: return 'Invalid password' else: return 'Invalid email' return None def login_social(self, login_type, token): user_object = None try: user_object = SocialSignin.verify(login_type, token) except SocialSignin.Invalid as e: return str(e) login_user(user_object) def logout(self): logout_user() def hash_password(self, password): return self.__bcrypt.generate_password_hash(password) # decorator that protects other users from PUT/POST/DELETE on you stuff # user_id _must_ be passed in as 'user_id' def only_me(self, function): @wraps(function) def inner(*args, **kwargs): if kwargs['user_id'] != 'me': return '{}', HTTP_401_UNAUTHORIZED return function(*args, **kwargs) return inner
def set_password(self, password): bcrypt = Bcrypt() self.password = bcrypt.generate_password_hash(password, 12)
from flask.ext.bcrypt import Bcrypt from flask.ext.markdown import Markdown from flask.ext.mail import Mail from itsdangerous import URLSafeTimedSerializer # START THE APPLICATION cwd = os.getcwd() static = cwd + "/static" application = Flask( __name__, instance_relative_config=True, static_folder=static) # AWS expects this to be "application," not "app" application.config.from_pyfile("config.py") bcrypt = Bcrypt(application) md = Markdown(application) mail = Mail(application) ts = URLSafeTimedSerializer(application.config["SECRET_KEY"]) # REQUEST HANDLERS @application.before_request def before_request(): g.db = database g.db.connect() @application.after_request def after_request(response): g.db.close()
""" .. module: lemur.extensions :copyright: (c) 2015 by Netflix Inc., see AUTHORS for more :license: Apache, see LICENSE for more details. """ from flask.ext.sqlalchemy import SQLAlchemy db = SQLAlchemy() from flask.ext.migrate import Migrate migrate = Migrate() from flask.ext.bcrypt import Bcrypt bcrypt = Bcrypt() from flask.ext.principal import Principal principal = Principal() from flask_mail import Mail smtp_mail = Mail() from lemur.metrics import Metrics metrics = Metrics()
def hash_result(user): bcrypt = Bcrypt(None) password_hash = bcrypt.generate_password_hash(user["password"]) user["password"] = password_hash return user
from flask import Flask, request from flask.ext.bcrypt import Bcrypt import settings from database import db import users app = Flask(__name__) bcrypt = Bcrypt(app) app.config.from_object('settings') @app.route("/login", methods=['GET', 'POST']) def login(): if request.method == 'POST': users = db.session.query(user).filter( user.username == request.form['username']).first() if users is not None: pw_hash = bcrypt.generate_password_hash(user.password, 10) bcrypt.check_password_hash(pw_hash, user.password) return {"status": True}, "Autorizado" return {"status": False}, "Nao autorizado" @app.route("/cadastrar", methods=['POST']) def cadastrar(): if request.method == 'POST': username = request.form['username'] password = request.form['password'] db.session.add(username, password) db.session.commit()
# bcrypt notes # pw_hash is of type varchar(255) # do not store password in db from flask import Flask, request, render_template from mysqlconnection import MySQLConnector # imports the Bcrypt module from flask.ext.bcrypt import Bcrypt app = Flask(__name__) bcrypt = Bcrypt(app) mysql = MySQLConnector(app, 'my_database_here') # this will load a page that has 2 forms one for registration and login @app.route('/', methods=['GET']) def index(): return render_template('index.html') # we are going to add functions to create new users and login users # generate_password_hash @app.route('/create_user', methods=['POST']) def create_user(): email = request.form['email'] username = request.form['username'] password = request.form['password'] # run validations and if they are successful we can create the password hash with bcrypt pw_hash = bcrypt.generate_password_hash(password) # now we insert the new user into the database insert_query = "INSERT INTO users (email, username, pw_hash, created_at) VALUES (:email, :username, :pw_hash, NOW())" query_data = { 'email': email, 'username': username, 'pw_hash': pw_hash }
import os import sys import config from flask import Flask, render_template from flask.ext.login import LoginManager from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.bcrypt import Bcrypt server = Flask(__name__) server.config['SQLALCHEMY_DATABASE_URI'] = config.DATABASE_URI server.config['SECRET_KEY'] = config.SECRET_KEY server.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True db = SQLAlchemy(server) bcrypt = Bcrypt(server) login_manager = LoginManager() login_manager.init_app(server) from runnershigh.auth.views import mod as AuthModule server.register_blueprint(AuthModule) from runnershigh.path.views import mod as PathModule server.register_blueprint(PathModule) from runnershigh.user.views import mod as UserModule server.register_blueprint(UserModule)
from flask import Flask, url_for, render_template, redirect, abort, session, request from pymongo import MongoClient from flask.ext.bcrypt import Bcrypt app = Flask(__name__, static_url_path='/static') mongo = MongoClient() bcrypt = Bcrypt(app) # new database db = mongo.tutorial db.users.insert_one({"name": "Devin"}) # bcrypt pw_hash = bcrypt.generate_password_hash('hunter2') print bcrypt.check_password_hash(pw_hash, 'hunter2') # db ''' db.users.find(json_data) db.users.insert_one(json_data) db.users.remove(json_data) db.users.update(json_data) ''' # getting post
from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.login import LoginManager from config import basedir from flask.ext.bcrypt import Bcrypt app = Flask(__name__) app.config.from_object('config') db = SQLAlchemy(app) lm = LoginManager() bcrypt = Bcrypt() lm.init_app(app) bcrypt.init_app(app) from app import views, models app.secret_key = 'gogogo'
# perform required imports import redis from flask import Flask from flask.ext.bcrypt import Bcrypt from contextlib import closing from getpass import getpass # set up database connection and create database if not existent r0 = redis.StrictRedis(host='localhost', port=6379, db=0) # Create default admin user username = raw_input("Please create a default admin user: "******"Please set password for default admin user: "******"Email address for password reset and notifications: ") # Setup bcrypt instance and hash password before storing app = Flask(__name__) bcrypt = Bcrypt(app) pw_hash = bcrypt.generate_password_hash(password) # Commit changes and close database r0.hmset('users',{'username': username, 'password': pw_hash, 'email' : email})
def setUpClass(cls): """Set up resources to be shared within a test class""" #TODO: refactor into a pytest class fixtures and inject as necessary # Create an empty session ID cls.session_id = "" # update application's db config options so unittests # run against test databases suite = cls.__name__.lower() config = dataactcore.config.CONFIG_DB cls.num = randint(1, 9999) config['error_db_name'] = 'unittest{}_{}_error_data'.format( cls.num, suite) config['job_db_name'] = 'unittest{}_{}_job_tracker'.format( cls.num, suite) config['user_db_name'] = 'unittest{}_{}_user_manager'.format( cls.num, suite) config['validator_db_name'] = 'unittest{}_{}_validator'.format( cls.num, suite) config['staging_db_name'] = 'unittest{}_{}_staging'.format( cls.num, suite) dataactcore.config.CONFIG_DB = config # drop and re-create test user db/tables setupUserDB() # drop and re-create test job db/tables setupJobTrackerDB() # drop and re-create test error db/tables setupErrorDB() # drop and re-create test validation db/tables setupValidationDB() # load e-mail templates setupEmails() #get test users try: with open('test.json') as test_users_file: test_users = json.load(test_users_file) test_users = test_users except: #if no test.json, provide some default e-mail accounts for tests test_users = {} test_users['admin_email'] = '*****@*****.**' test_users['change_user_email'] = '*****@*****.**' test_users['password_reset_email'] = '*****@*****.**' test_users['inactive_email'] = '*****@*****.**' test_users['password_lock_email'] = '*****@*****.**' test_users['expired_lock_email'] = '*****@*****.**' test_users['agency_admin_email'] = '*****@*****.**' # This email is for a regular agency_user email that is to be used for testing functionality # expected by a normal, base user test_users['agency_user'] = '******' if 'approved_email' not in test_users: test_users['approved_email'] = '*****@*****.**' if 'submission_email' not in test_users: test_users['submission_email'] = '*****@*****.**' user_password = '******' admin_password = '******' #setup test users userEmails = [ "*****@*****.**", "*****@*****.**", "*****@*****.**", "*****@*****.**", "*****@*****.**", test_users["admin_email"], test_users["approved_email"], "*****@*****.**" ] userStatus = [ "awaiting_confirmation", "email_confirmed", "awaiting_approval", "awaiting_approval", "awaiting_approval", "approved", "approved", "denied" ] userPermissions = [ 0, AccountType.AGENCY_USER, AccountType.AGENCY_USER, AccountType.AGENCY_USER, AccountType.AGENCY_USER, AccountType.WEBSITE_ADMIN + AccountType.AGENCY_USER, AccountType.AGENCY_USER, AccountType.AGENCY_USER ] # Add new users userDb = UserHandler() userDb.createUserWithPassword(test_users["submission_email"], user_password, Bcrypt()) userDb.createUserWithPassword(test_users["change_user_email"], user_password, Bcrypt()) userDb.createUserWithPassword(test_users["password_reset_email"], user_password, Bcrypt()) userDb.createUserWithPassword(test_users["inactive_email"], user_password, Bcrypt()) userDb.createUserWithPassword(test_users["password_lock_email"], user_password, Bcrypt()) userDb.createUserWithPassword(test_users['expired_lock_email'], user_password, Bcrypt()) userDb.createUserWithPassword(test_users['agency_admin_email'], admin_password, Bcrypt(), permission=4) userDb.createUserWithPassword(test_users['agency_user'], user_password, Bcrypt()) # Set the Agency for the agency user agencyUser = userDb.getUserByEmail(test_users['agency_user']) userDb.session.commit() cls.agency_user_id = agencyUser.user_id # Set the specified account to be expired expiredUser = userDb.getUserByEmail(test_users['expired_lock_email']) today = parse(time.strftime("%c")) expiredUser.last_login_date = (today - timedelta(days=120)).strftime("%c") userDb.session.commit() # Create users for status testing for index in range(len(userEmails)): email = userEmails[index] userDb.addUnconfirmedEmail(email) user = userDb.getUserByEmail(email) userDb.changeStatus(user, userStatus[index]) userDb.setPermission(user, userPermissions[index]) #set up approved user user = userDb.getUserByEmail(test_users['approved_email']) user.username = "******" userDb.setPassword(user, user_password, Bcrypt()) cls.approved_user_id = user.user_id #set up admin user admin = userDb.getUserByEmail(test_users['admin_email']) userDb.setPassword(admin, admin_password, Bcrypt()) admin.name = "Mr. Manager" admin.cgac_code = "SYS" userDb.session.commit() #set up status changed user statusChangedUser = userDb.getUserByEmail( test_users["change_user_email"]) cls.status_change_user_id = statusChangedUser.user_id statusChangedUser.name = "Test User" statusChangedUser.user_status_id = userDb.getUserStatusId( "email_confirmed") userDb.session.commit() #set up deactivated user user = userDb.getUserByEmail(test_users["inactive_email"]) user.last_login_date = time.strftime("%c") user.is_active = False userDb.session.commit() #set up info needed by the individual test classes cls.test_users = test_users cls.user_password = user_password cls.admin_password = admin_password cls.interfaces = InterfaceHolder() cls.jobTracker = cls.interfaces.jobDb cls.errorDatabase = cls.interfaces.errorDb cls.userDb = cls.interfaces.userDb cls.local = CONFIG_BROKER['local']
def create_user(self, newuser): EMAIL_REGEX = re.compile(r"^[a-zA-Z0-9\.\+_-]+@[a-zA-Z0-9\._-]+\.[a-zA-Z]+$") any_nonletter_regex = re.compile("[^a-z A-Z]") error = False fname = newuser["fname"] lname = newuser["lname"] email = newuser["email"] password = newuser["password"] password2 = newuser["password2"] print "***** create_user" print fname print lname print email print password print password2 if len(fname) < 1: error = True flash("First name cannot be blank", "error") if len(lname) < 1: error = True flash("Last name cannot be blank", "error") if len(email) < 1: error = True flash("Email cannot be blank", "error") elif not EMAIL_REGEX.match(email): error = True flash("Invalid email address", "error") # ***************************************** # check if email is already registered # ***************************************** results = self.db.query_db("SELECT * FROM users WHERE email = '{}' LIMIT 1".format(email)) if results != []: error = True flash("Email is already registered", "error") if len(password) < 4: error = True flash("Password must be at least 4 chars", "error") if len(password2) < 4: error = True flash("Password confirmation must be at least 4 chars", "error") if password != password2: error = True flash("Password and password confirmation must be the same", "error") if not error: # encrypt password app = Flask(__name__) app.secret_key = "KeepItSecretKeepItSafe" bcrypt = Bcrypt(app) pw_hash = bcrypt.generate_password_hash(password) query = "INSERT INTO users (fname, lname, email, pw_hash, created_at, updated_at) VALUES ('{}', '{}', '{}', '{}', NOW(), NOW() )".format( fname, lname, email, pw_hash ) print query self.db.query_db(query) # registration was successful, so let's automatically # log in the user session["fname"] = fname session["lname"] = lname session["email"] = email # get user_id (since this is a new user it will be the largest id) query = "select * from users order by id desc limit 1" result = self.db.query_db(query) print "*** get session id" print result[0]["id"] session["id"] = result[0]["id"] # flash('Successful registration', 'success') return True else: return False
from flask import Flask from flask.ext.bcrypt import Bcrypt app = Flask(__name__) bcrypt = Bcrypt(app) pw_hash = bcrypt.generate_password_hash('insert awesome password here') print pw_hash print bcrypt.check_password_hash(pw_hash, 'insert awesome password here') # returns True
Allergen('crustaceans'), Allergen('eggs'), Allergen('fish'), Allergen('lupin'), Allergen('milk'), Allergen('molluscs'), Allergen('mustard'), Allergen('nuts'), Allergen('peanuts'), Allergen('sesame seeds'), Allergen('soya'), Allergen('sulphur dioxide'), Allergen('almonds'), ] BCRYPT = Bcrypt(app.APP) class User(DB.Model): id = DB.Column(DB.Integer, primary_key=True, nullable=False) email = DB.Column(DB.String(120), unique=True, nullable=False) passhash = DB.Column(DB.BINARY(60), nullable=False) firstname = DB.Column(DB.String(120), nullable=False) surname = DB.Column(DB.String(120), nullable=False) fullname = DB.column_property(firstname + ' ' + surname) phone = DB.Column(DB.String(20), nullable=False) send_email_alerts = DB.Column(DB.Boolean(), nullable=False) send_sms_alerts = DB.Column(DB.Boolean(), nullable=False) email_verification_key = DB.Column(DB.String(6), nullable=True) sms_verification_key = DB.Column(DB.String(6), nullable=True) email_verified = DB.Column(DB.Boolean(), nullable=False)
from wtforms.validators import DataRequired, Email #导入ORM模块 from flask.ext.sqlalchemy import SQLAlchemy #密码加密 from flask.ext.bcrypt import Bcrypt, generate_password_hash from sqlalchemy.ext.hybrid import hybrid_property #login from flask.ext.login import UserMixin, LoginManager, login_user, logout_user, login_required, current_user #=================载入插件================= bootstrap = Bootstrap() csrf = CsrfProtect() db = SQLAlchemy() # 实例化ORM对象 bcrypt = Bcrypt() #加密 login_manager = LoginManager() #=================应用设置================= from config import config, BASE_URL def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) config[config_name].init_app(app) bootstrap.init_app(app) csrf.init_app(app) db.init_app(app) #初始化数据库 bcrypt.init_app(app) #加密
app.config['TWITTER_CONSUMER_KEY'] = 'IRh7xn4AZfryNrsXQI3hXNIPu' app.config[ 'TWITTER_CONSUMER_SECRET'] = 'YhJ0JWYoS7am327ST6PQVkdxmbkvI10A5dIzJs3xv5FWNrgDjV' app.config[ 'TWITTER_ACCESS_TOKEN'] = '3305385699-0WEBODjVEuMn48QaK80hPCkA7xTJGNk2CU21YSc' app.config[ 'TWITTER_TOKEN_SECRET'] = 'g8cgsMCNtx8cohb3tNccJX2gEaKZ9u8QcqY1a8wKV7SiK' db = MongoEngine(app) app.session_interface = MongoEngineSessionInterface(db) twitter_oembedder = TwitterOEmbedder() cache = Cache(app, config={'CACHE_TYPE': 'simple'}) twitter_oembedder.init(app, cache) flask_bcrypt = Bcrypt(app) login_manager = LoginManager() login_manager.init_app(app) login_manager.refresh_view = 'auth_app.login' oauth = OAuth() twitter = oauth.remote_app( 'twitter', base_url='https://api.twitter.com/1/', request_token_url='https://api.twitter.com/oauth/request_token', access_token_url='https://api.twitter.com/oauth/access_token', authorize_url='https://api.twitter.com/oauth/authenticate', consumer_key=app.config['TWITTER_CONSUMER_KEY'], consumer_secret=app.config['TWITTER_CONSUMER_SECRET'])
sys.path.append('../lib/') from DBConsultas import DB #sudo /opt/anaconda/bin/pip install flask-bcrypt from flask.ext.bcrypt import Bcrypt import ConfigParser import argparse import os DEBUG = True SECRET_KEY = 'c9d883d5-634b-477a-ab87-2fecba340e0d' # create our little application :) app = Flask(__name__) bcrypt = Bcrypt(app) app.config.from_object(__name__) ALLOWED_EXTENSIONS = set(['txt', 'csv', 'png', 'jpg', 'jpeg', 'gif']) def allowed_file(filename): return '.' in filename and \ filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS @app.before_request def before_request(): config = ConfigParser.ConfigParser() config.read('consultas.cfg')
from flask import Flask, render_template, redirect, request, session, flash from mysqlconnection import MySQLConnector from flask.ext.bcrypt import Bcrypt import re onlyLetters = re.compile(r'^[a-zA-Z]+$') email_validation = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$') app = Flask(__name__) app.secret_key = "jimmy" mysql = MySQLConnector(app, 'the_wall') bcrypt = Bcrypt(app) # this needs to go after app gets defined app ==== @app.route("/") def landing_page(): return render_template("index.html") @app.route("/register", methods=["POST"]) def registerUser(): flag = False data = { 'email': request.form['email'], 'first': request.form['first_name'], 'last': request.form['last_name'], 'password': request.form['password'], 'cpassword': request.form['cpassword'] } # First Name - letters only, at least 2 characters and that it was submitted if not onlyLetters.match(data['first']):
from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.bcrypt import Bcrypt from blinker import Namespace from flask.ext.login import LoginManager # Initialize the db extension, but without configuring # it with an application instance. db = SQLAlchemy() flask_bcrypt = Bcrypt() login_manager = LoginManager() socializer_signals = Namespace() user_followed = socializer_signals.signal('user-followed') from signal_handlers import * def create_app(config=None): app = Flask(__name__) if config is not None: app.config.from_object(config) # Initialize any extensions and bind blueprints to the # application instance here. db.init_app(app) flask_bcrypt.init_app(app) login_manager.init_app(app)
import json from flask import Flask, request, session, g, redirect, url_for, \ abort, render_template, flash from flask.ext.bcrypt import Bcrypt # default config DEBUG = True SECRET_KEY = 'no so secret' CFG_FILE = '/etc/bradmin.cfg' CACHE_ROOT = '.' app = Flask(__name__) bcrypt = Bcrypt(app) app.config.from_object(__name__) try: app.config.from_pyfile(app.config['CFG_FILE']) except IOError: pass from fileStore import * db = fileStore(app.config['CACHE_ROOT'] + '/db') # load config from the database conf = None try: conf = json.loads(db.get('conf/bradmin'))
def __init__(self): self.db = current_app.db self.bcrypt = Bcrypt(current_app)
from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy import os from flask.ext.login import LoginManager from flask.ext.openid import OpenID from config import basedir, ADMINS, MAIL_SERVER, MAIL_PORT, MAIL_USERNAME, MAIL_PASSWORD from flask.ext.mail import Mail from .momentjs import momentjs from flask.ext.babel import Babel, lazy_gettext from flask.ext.bcrypt import Bcrypt from flask.ext.mobility import Mobility app = Flask(__name__) Mobility(app) bcrypt = Bcrypt(app) app.config.from_object('config') db = SQLAlchemy(app) lm = LoginManager() lm.init_app(app) lm.login_view = 'index' lm.login_message = lazy_gettext('Please log in to access this page.') oid = OpenID(app, os.path.join(basedir, 'tmp')) mail = Mail(app) babel = Babel(app) from flask.json import JSONEncoder class CustomJSONEncoder(JSONEncoder): """This class adds support for lazy translation texts to Flask's JSON encoder. This is necessary when flashing translated texts."""
csrf = SeaSurf(app) # apply SSL termination handling app.request_class = ProxiedRequest # configuration file if os.path.isfile('./DEV'): app.config.from_object('config.DebugConfiguration') else: app.config.from_object('config.BaseConfiguration') # other app'ish things login_manager = LoginManager(app) # login manager manager = Manager(app) # shell actions manager db = SQLAlchemy(app) # database connection bcrypt = Bcrypt(app) # hashing function # users module blueprint from webapp.handlers.userhandlers import mod as usersModule app.register_blueprint(usersModule) # configure module blueprint from webapp.handlers.configurehandlers import mod as configureModule app.register_blueprint(configureModule) # api module blueprint from webapp.handlers.apihandlers import mod as APIModule app.register_blueprint(APIModule) # socket module blueprint from webapp.handlers.sockethandlers import mod as socketModule