def signup(): form = SignupForm() bcrypt = Bcrypt(app) if 'user_id' in session: return redirect(url_for('profile')) if request.method == 'POST': if form.validate() == False: return render_template('signup.html', form=form) else: password = bcrypt.generate_password_hash(form.su_password.data,10) cursor= cnx.cursor() cursor.callproc('create_new_user',[form.su_username.data,form.su_firstname.data, form.su_lastname.data, form.su_email.data,password]) user_id = cursor.fetchone() cursor.close() if request.method == 'POST': rolelist = RoleList(user_id[0]) session['user_id'] = user_id[0] session['roles'] = rolelist.roles return redirect(url_for('profile')) elif request.method == 'GET': return render_template('signup.html', form=form)
def reset_password_action(): hash = request.form["hash"] id = request.form["id"] password = request.form["password"] password2 = request.form["password2"] token = request.form["token"] error = validateResetForm(id, hash) if not error: if not password: error = 'Please enter a password' elif not password2: error = 'Please enter a password' elif password != password2: error = 'Passwords do not match' else: bcrypt = Bcrypt(app) pwHash = bcrypt.generate_password_hash(password) usersService = UsersService() userResult = usersService.first(id=int(id)) usersService.update(userResult, password=pwHash) error = 'Password updated' return render_custom_template('login/reset_password.html', id=id, hash=hash, error=error)
def login_action(): form=LoginForm(request.form) if request.method=='POST': username=request.form['username'] password=request.form['password'] user=User.query.filter_by(username=username).one() bcrypt=Bcrypt(app) if bcrypt.check_password_hash(user.password,password): session['user']=user.id return redirect(url_for('add_article')) return render_template('tachilab/login.html',form=form)
def setUp(self): self.app = application.app bcrypt = Bcrypt(self.app) # forcibly reconnect to testing db connection.disconnect() self.app.config['MONGO_CONFIG']['db_name'] = 'pipeline_testing' self.connection = connect( self.app.config['MONGO_CONFIG']['db_name'] , host=self.app.config['MONGO_CONFIG']['host'] , port=int(self.app.config['MONGO_CONFIG']['port']) ) # drop any lingering test dbs self.connection.drop_database( self.app.config['MONGO_CONFIG']['db_name']) member_user = User( admin_rights = False , email = '*****@*****.**' , email_confirmation_code = 'goodday' , email_confirmed = True , last_login_time = datetime.datetime.utcnow() , password_hash = bcrypt.generate_password_hash('hola!') , registration_time = datetime.datetime.utcnow() , verified = True) member_user.save() ''' create a test org ''' test_org = Organization( label = 'best-org' , name = 'best org') test_org.save() # save membership member_user.update(push__organizations = test_org) ''' create a test project ''' test_project = Project( creation_time = datetime.datetime.utcnow() , label = 'best-project' , name = 'best project' , organization = test_org) test_project.save() test_org.update(push__projects=test_project) ''' create a data-less upload ''' '''
def login(): form=LoginForm(request.form) if request.method=='POST' and form.validate(): try: admin=Admin.query.filter_by(username=request.form['username']).one() bcrypt=Bcrypt(app) if bcrypt.check_password_hash(admin.password,request.form['password']): session['admin_id']=admin.id return redirect('/') else: return render_template('admin_login.html',form=form,data='no password') except: return render_template('admin_login.html',form=form,data='no username') return render_template('admin_login.html',form=form,data='')
def register_action(): username = request.form["username"] email = request.form["email"] password = request.form["password"] password2 = request.form["password2"] token = request.form["token"] print email usersService = UsersService() if username: usernameResult = usersService.first(username=username) else: usernameResult = False if email: emailResult = usersService.first(email=email) else: emailResult = False #do validation checking if not username: error = 'Please enter a username' elif usernameResult: error = 'Username has been taken' elif not email: error = 'Please enter an email address' elif emailResult: error = 'Email address has been taken' elif not password: error = 'Please enter a password' elif password != password2: error = 'Passwords do not match' elif not isTokenValid(token): error = 'The request did not come from Pycamp' else: error = False #error = True if not error: bcrypt = Bcrypt(app) pwHash = bcrypt.generate_password_hash(password) usersService.create(username=username, email=email, password=pwHash, salt='', role_id=2, forgot_password_hash='') return render_custom_template('register/index.html', error=error, username=username, email=email)
def login_action(): username = request.form["username"] password = request.form["password"] token = request.form["token"] usersService = UsersService() if username: usernameResult = usersService.first(username=username) else: usernameResult = False if not username: error = 'Please enter a username' elif not password: error = 'Please enter a password' elif not usernameResult: error = 'This user does not exist' elif not isTokenValid(token): error = 'The request did not come from Pycamp' else: error = False if not error and usernameResult: bcrypt = Bcrypt(app) if not bcrypt.check_password_hash(usernameResult.password, password): error = 'Invalid password entered' else: print 'logged in again' user = load_user(usernameResult.id) login_user(user) return redirect("/projects/list-projects") """session = request.environ['beaker.session'] if not session.has_key('username'): session['username'] = username session.save() return "Session value set." else: return session['username'] """ return render_custom_template('login/login.html', error=error, username=username)
def login(email, password): """Tries to log in a user Args: email_or_username: obvi. password: plaintext plaintext password Returns: User object if login succeeded False if login failed """ ret = False bcrypt = Bcrypt() user = User.find_by_email(email) if user and bcrypt.check_password_hash(user.password, password): ret = user return ret
class BasicTestCase(unittest.TestCase): def setUp(self): app = flask.Flask(__name__) app.config['BCRYPT_LOG_ROUNDS'] = 6 self.bcrypt = Bcrypt(app) def test_is_string(self): pw_hash = self.bcrypt.generate_password_hash('secret') self.assertTrue(isinstance(pw_hash, str)) def test_not_string(self): pw_hash = self.bcrypt.generate_password_hash(42) self.assertTrue(isinstance(pw_hash, str)) def test_custom_rounds(self): password = '******' pw_hash1 = self.bcrypt.generate_password_hash(password, 5) self.assertNotEqual(password, pw_hash1) def test_check_hash(self): pw_hash = self.bcrypt.generate_password_hash('secret') # check a correct password self.assertTrue(self.bcrypt.check_password_hash(pw_hash, 'secret')) # check an incorrect password self.assertFalse(self.bcrypt.check_password_hash(pw_hash, 'hunter2')) # check unicode pw_hash = self.bcrypt.generate_password_hash(u'\u2603') self.assertTrue(self.bcrypt.check_password_hash(pw_hash, u'\u2603')) # check helpers pw_hash = generate_password_hash('hunter2') self.assertTrue(check_password_hash(pw_hash, 'hunter2')) def test_check_hash_unicode_is_utf8(self): password = u'\u2603' pw_hash = self.bcrypt.generate_password_hash(password) # check a correct password self.assertTrue(self.bcrypt.check_password_hash(pw_hash, '\xe2\x98\x83')) def test_rounds_set(self): self.assertEquals(self.bcrypt._log_rounds, 6)
from contextlib import closing from random import shuffle from flask import Flask, render_template, request, redirect, g, session, flash from flaskext.bcrypt import Bcrypt from access_db import * #configs DEBUG = True SECRET_KEY = "placeholder" database = 'quizgame.db' schema = 'schema.sql' csv = 'quiz_questions.csv' app = Flask(__name__) bcrypt = Bcrypt(app) app.config.from_object(__name__) def get_questions(n, ordered=False): question_nums = get_question_nums() if not ordered: shuffle(question_nums) questions = [] for i in range(n): question = get_question(question_nums[i]) questions.append(question) return questions @app.before_request def before_request(): g.db = connect_db()
def create_app(app_name, config_obj, with_api=True): """ Generates and configures the main shop application. All additional """ # Launching application app = Flask(app_name) # So the engine would recognize the root package # Load Configuration app.config.from_object(config_obj) # Loading assets assets = Environment(app) assets.from_yaml('assets.yaml') app.assets = assets # Initialize Mail app.mail = Mail(app) # Initializing login manager login_manager = LoginManager() login_manager.login_view = app.config.get('LOGIN_VIEW', 'main.index') # login_manager.login_message = 'You need to be logged in to access this page' login_manager.session_protection = 'strong' login_manager.setup_app(app) app.login_manager = login_manager # Initializing principal manager app.principal = Principal(app) # Initializing bcrypt password encryption bcrypt = Bcrypt(app) app.bcrypt = bcrypt # Initializing Database db = SQLAlchemy(app) app.db = db # Initializing Migrate migrate = Migrate(app, db, "from fitted.models import *") app.migrate = migrate photos = UploadSet('photos', IMAGES) archives = UploadSet('archives', ARCHIVES) configure_uploads(app, (photos, archives)) patch_request_class(app, 2 * 1024 * 1024) # Patches to 2MB file uploads max. app.photos = photos app.archives = archives # Integrate Elasticsearch es_config = app.config.get("ES_CONFIG", []) app.es = Elasticsearch(es_config) # Integrate sms with Twilio app.sms = TwilioRestClient(app.config.get("TWILIO_API_SID"), app.config.get("TWILIO_API_TOKEN")) # Redis store for session management # The process running Flask needs write access to this directory: # store = RedisStore(redis.StrictRedis()) # # this will replace the app's session handling # KVSessionExtension(store, app) # configure sentry # if not app.config.get("DEBUG", False): # sentry = Sentry(app) # app.sentry = sentry # inject celery into the app app.celery = make_celery(app) # injecting mongodb support # app.mongo = PyMongo(app) # flask s3 integration app.s3 = FlaskS3(app) # Facebook & Twitter Integration app.facebook = oauth.remote_app('facebook', app_key='FACEBOOK') oauth.init_app(app) # Initializing the restful API if with_api: api = restful.Api(app, prefix='/api/v1') app.api = api # Initialize Logging if not app.debug: import logging from logging.handlers import RotatingFileHandler file_handler = RotatingFileHandler( "/var/log/fitted/%s.log" % app.config.get("LOGFILE_NAME", app_name), maxBytes=500 * 1024) file_handler.setLevel(logging.WARNING) from logging import Formatter file_handler.setFormatter( Formatter('%(asctime)s %(levelname)s: %(message)s ' '[in %(pathname)s:%(lineno)d]')) app.logger.addHandler(file_handler) #include an api_registry to the application app.api_registry = [] #a simple list holding the values to be registered return app
def passwd(self, value=None): bcrypt = Bcrypt() password = bcrypt.generate_password_hash(value) self.password = password
from flask.ext.login import (LoginManager, current_user, login_required, login_user, logout_user, UserMixin, AnonymousUser, confirm_login, fresh_login_required) # Library from flaskext.bcrypt import Bcrypt #custom user library - maps User object to User model from libs.user import * app = Flask(__name__) app.debug = True app.secret_key = os.environ.get('SECRET_KEY') # SECRET_KEY=...... inside .env # Flask BCrypt will be used to salt the user password flask_bcrypt = Bcrypt(app) #mongolab connection # uses .env file to get connection string # using a remote db get connection string from heroku config # using a local mongodb put this in .env # MONGOLAB_URI=mongodb://localhost:27017/dwdfall2012 mongoengine.connect('userdemo', host=os.environ.get('MONGOLAB_URI')) # Login management defined # reference http://packages.python.org/Flask-Login/#configuring-your-application login_manager = LoginManager() login_manager.anonymous_user = Anonymous login_manager.login_view = "login" login_manager.login_message = u"Please log in to access this page." login_manager.refresh_view = "reauth"
from flask import Flask, render_template, url_for, redirect from flaskext.bcrypt import Bcrypt from flask.ext.login import logout_user, login_required from hat.views import LoginView, RegisterView, IndexView, TagView, APIView from hat.objects import db, login_manager app = Flask(__name__) app.config.from_object('config.Config') Bcrypt(app) db.init_app(app) login_manager.init_app(app) IndexView.register(app) LoginView.register(app) RegisterView.register(app) TagView.register(app) APIView.register(app) @app.route("/logout") @login_required def logout(): logout_user() return redirect('/') if __name__ == '__main__':
from flask import Flask, request, session, g, redirect, url_for, \ abort, render_template, flash from flaskext.bcrypt import Bcrypt import json # default config DEBUG = True SECRET_KEY = 'no so secret' CFG_FILE = '/etc/bradmin.cfg' CACHE_ROOT = '/var/cache/bradmin' 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')) except IOError:
def setUp(self): self.app = application.app bcrypt = Bcrypt(self.app) # forcibly reconnect to testing db connection.disconnect() self.app.config['MONGO_CONFIG']['db_name'] = 'pipeline_testing' mongo_config = self.app.config['MONGO_CONFIG'] mongodb_uri = 'mongodb://' if mongo_config['dbuser'] and mongo_config['dbpassword']: mongodb_uri += '%s:%s@' % (mongo_config['dbuser'] , mongo_config['dbpassword']) mongodb_uri += '%s/%s' % (mongo_config['hosts'], mongo_config['db_name']) self.connection = connect(mongo_config['db_name'], host=mongodb_uri) # drop any lingering test dbs self.connection.drop_database( self.app.config['MONGO_CONFIG']['db_name']) ''' create test user ''' member_user = User( admin_rights = False , email = '*****@*****.**' , email_confirmation_code = 'goodday' , email_confirmed = True , last_login_time = datetime.utcnow() , password_hash = bcrypt.generate_password_hash('hola!') , registration_time = datetime.utcnow() , verified = True) member_user.save() ''' create test org ''' test_org = Organization( label = 'euro-water' , name = 'Euro Water') test_org.save() # save membership member_user.update(push__organizations = test_org) ''' create test headers ''' date_header = Header(data_type = 'datetime', name = 'date', label = 'date') date_header.save() pH_header = Header(data_type = 'number', name = 'pH', label = 'pH') pH_header.save() city_header = Header(data_type = 'string', name = 'city', label = 'city') city_header.save() headers = [date_header, pH_header, city_header] # save ref to this header for later test self.date_header_id = date_header.id ''' create test project ''' test_project = Project( creation_time = datetime.utcnow() , label = 'water-quality' , name = 'water quality' , ordered_schema = headers , organization = test_org) test_project.save() test_org.update(push__projects=test_project) ''' update the headers with a ref to the project ''' for header in headers: header.update(set__project = test_project) ''' create test datapoints ''' test_data = [ {'date': datetime(2012, 3, 4), 'pH': 2.2, 'city': 'Madrid'} , {'date': datetime(2012, 3, 5), 'pH': 3, 'city': 'Paris'} , {'date': datetime(2012, 3, 6), 'pH': 4, 'city': 'London'} , {'date': datetime(2012, 3, 6), 'pH': 3, 'city': 'London'} , {'date': datetime(2012, 3, 6), 'pH': None, 'city': 'London'} ] for datapoint in test_data: new_entry = Entry( project = test_project , unique = True , values = datapoint) new_entry.save()
class UserApi(Resource): def __init__(self): self.db = current_app.config['DB'] self.bcrypt = Bcrypt(current_app) def abort(self, response=None): if response is None: abort(400) return (response, 400) def prettify(self, user): return { 'login': user['login'], 'role': 'Admin' if user['admin'] else 'User' } def find_user(self, login=None): if login is None: login = request.json['login'] return self.db.User.find_one({'login': login}) def get(self, login=None): if login: user = self.find_user(login) if user: return self.prettify(user) else: return [ self.prettify(r) for r in self.db.User.find() ] def post(self): if request.json is None: return self.abort({'message': "Data required"}) if self.find_user(): return {'message': "User already exists"} user = self.db.User() user['login'] = request.json['login'] user['password'] = self.bcrypt.generate_password_hash( request.json['password'] ) user.save() return ({'message': 'User created successfully!'}, 201) def put(self, login): user = self.find_user(login) if user is None: return self.abort({'message': "User not found"}) curr_pass = request.json.get('current_password', '') if not self.bcrypt.check_password_hash( user['password'], curr_pass): return self.abort({'message': "Invalid password"}) new_pass = request.json.get('new_password', '') if new_pass == curr_pass: return self.abort({'message': "New password should be different than the old one"}) confirm_pass = request.json.get('confirm_password') if not new_pass: return self.abort({'message': "Please provide new password"}) if new_pass != confirm_pass: return self.abort({'message': "New password confirmed incorrectly"}) user = self.db.User(user) user['password'] = self.bcrypt.generate_password_hash( request.json['new_password'] ) user.save() return {'message': "Password changed"} def delete(self, login): user = self.find_user(login) if user: self.db.User(user).delete() else: return self.abort({'message': "User was not found"}) if self.find_user(login) is not None: return self.abort({'message': "User still exists"}) return {'message': "User deleted successfully"}
def setUp(self): app = flask.Flask(__name__) app.config['BCRYPT_LOG_ROUNDS'] = 6 self.bcrypt = Bcrypt(app)
from flask_login import LoginManager from flaskext.markdown import Markdown from flaskext.bcrypt import Bcrypt from sqlalchemy import create_engine def versiontuple(v): return tuple(map(int, (v.split(".")))) app = Flask(__name__) app.config.from_object('kafein.config') Markdown(app) db = SQLAlchemy(app) bcrypt = Bcrypt(app) from hooks import * import models db.create_all() db.session.commit() # Config table initialization if app.config['VERSION'] == '0.2': try: version = get_config('version') except: # Hack: version is initialized to 0.1 in order to manage table migration db.session.add(Config('version', '0.1')) db.session.commit()
def __init__(self): self.db = current_app.config['DB'] self.bcrypt = Bcrypt(current_app)
import os.path import platform import urllib2 import urlparse from pprint import pprint import cssmin from jinja2 import Environment, FileSystemLoader from fabric.colors import * from fabric.api import * from fabric.contrib.console import * from fabric.contrib.files import * from fabric.utils import * from flaskext.bcrypt import Bcrypt bcrypt = Bcrypt() """ fabfile Heavily inspired by: https://github.com/samuelclay/NewsBlur/blob/master/fabfile.py """ # ============== # Color Printing # ============== def pblue(s, bold=False): puts(blue(s, bold)) def pcyan(s, bold=False):
def setUp(self): self.app = application.app bcrypt = Bcrypt(self.app) # forcibly reconnect to testing db connection.disconnect() self.app.config['MONGO_CONFIG']['db_name'] = 'pipeline_testing' mongo_config = self.app.config['MONGO_CONFIG'] mongodb_uri = 'mongodb://' if mongo_config['dbuser'] and mongo_config['dbpassword']: mongodb_uri += '%s:%s@' % (mongo_config['dbuser'] , mongo_config['dbpassword']) mongodb_uri += '%s/%s' % (mongo_config['hosts'], mongo_config['db_name']) self.connection = connect(mongo_config['db_name'], host=mongodb_uri) # drop any lingering test dbs self.connection.drop_database( self.app.config['MONGO_CONFIG']['db_name']) admin_user = User( admin_rights = True , email = '*****@*****.**' , email_confirmation_code = 'goodday' , email_confirmed = True , last_login_time = datetime.datetime.utcnow() , password_hash = bcrypt.generate_password_hash('hola!') , registration_time = datetime.datetime.utcnow() , verified = True) admin_user.save() # same as verified but will push into an org for membership member_user = User( admin_rights = False , email = '*****@*****.**' , email_confirmation_code = 'goodday' , email_confirmed = True , last_login_time = datetime.datetime.utcnow() , password_hash = bcrypt.generate_password_hash('hola!') , registration_time = datetime.datetime.utcnow() , verified = True) member_user.save() verified_user = User( admin_rights = False , email = '*****@*****.**' , email_confirmation_code = 'goodday' , email_confirmed = True , last_login_time = datetime.datetime.utcnow() , password_hash = bcrypt.generate_password_hash('hola!') , registration_time = datetime.datetime.utcnow() , verified = True) verified_user.save() unverified_user = User( admin_rights = False , email = '*****@*****.**' , email_confirmation_code = 'goodday' , email_confirmed = True , last_login_time = datetime.datetime.utcnow() , password_hash = bcrypt.generate_password_hash('hola!') , registration_time = datetime.datetime.utcnow() , verified = False) unverified_user.save() ''' create a test org ''' test_org = Organization( label = 'best-org' , name = 'best org') test_org.save() # save membership member_user.update(push__organizations = test_org) ''' create a test project ''' test_project = Project( creation_time = datetime.datetime.utcnow() , label = 'best-project' , name = 'best project' , organization = test_org) test_project.save() test_org.update(push__projects=test_project)